enable.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package stream
  2. import (
  3. "fmt"
  4. "net/http"
  5. "os"
  6. "runtime"
  7. "sync"
  8. "github.com/0xJacky/Nginx-UI/internal/helper"
  9. "github.com/0xJacky/Nginx-UI/internal/nginx"
  10. "github.com/0xJacky/Nginx-UI/internal/notification"
  11. "github.com/go-resty/resty/v2"
  12. "github.com/uozi-tech/cosy"
  13. "github.com/uozi-tech/cosy/logger"
  14. )
  15. // Enable enables a site by creating a symlink in sites-enabled
  16. func Enable(name string) (err error) {
  17. configFilePath := nginx.GetConfPath("streams-available", name)
  18. enabledConfigFilePath := nginx.GetConfPath("streams-enabled", name)
  19. _, err = os.Stat(configFilePath)
  20. if err != nil {
  21. return
  22. }
  23. if helper.FileExists(enabledConfigFilePath) {
  24. return
  25. }
  26. err = os.Symlink(configFilePath, enabledConfigFilePath)
  27. if err != nil {
  28. return
  29. }
  30. // Test nginx config, if not pass, then disable the site.
  31. output, err := nginx.TestConfig()
  32. if err != nil {
  33. return
  34. }
  35. if nginx.GetLogLevel(output) > nginx.Warn {
  36. _ = os.Remove(enabledConfigFilePath)
  37. return cosy.WrapErrorWithParams(ErrNginxTestFailed, output)
  38. }
  39. output, err = nginx.Reload()
  40. if err != nil {
  41. return
  42. }
  43. if nginx.GetLogLevel(output) > nginx.Warn {
  44. return cosy.WrapErrorWithParams(ErrNginxReloadFailed, output)
  45. }
  46. go syncEnable(name)
  47. return
  48. }
  49. func syncEnable(name string) {
  50. nodes := getSyncNodes(name)
  51. wg := &sync.WaitGroup{}
  52. wg.Add(len(nodes))
  53. for _, node := range nodes {
  54. go func() {
  55. defer func() {
  56. if err := recover(); err != nil {
  57. buf := make([]byte, 1024)
  58. runtime.Stack(buf, false)
  59. logger.Error(err)
  60. }
  61. }()
  62. defer wg.Done()
  63. client := resty.New()
  64. client.SetBaseURL(node.URL)
  65. resp, err := client.R().
  66. SetHeader("X-Node-Secret", node.Token).
  67. Post(fmt.Sprintf("/api/streams/%s/enable", name))
  68. if err != nil {
  69. notification.Error("Enable Remote Stream Error", err.Error(), nil)
  70. return
  71. }
  72. if resp.StatusCode() != http.StatusOK {
  73. notification.Error("Enable Remote Stream Error", "Enable stream %{name} on %{node} failed", NewSyncResult(node.Name, name, resp))
  74. return
  75. }
  76. notification.Success("Enable Remote Stream Success", "Enable stream %{name} on %{node} successfully", NewSyncResult(node.Name, name, resp))
  77. }()
  78. }
  79. wg.Wait()
  80. }