enable.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package site
  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("sites-available", name)
  18. enabledConfigFilePath := nginx.GetConfPath("sites-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 := nginx.TestConf()
  32. if nginx.GetLogLevel(output) > nginx.Warn {
  33. _ = os.Remove(enabledConfigFilePath)
  34. return cosy.WrapErrorWithParams(ErrNginxTestFailed, output)
  35. }
  36. output = nginx.Reload()
  37. if nginx.GetLogLevel(output) > nginx.Warn {
  38. return cosy.WrapErrorWithParams(ErrNginxReloadFailed, output)
  39. }
  40. go syncEnable(name)
  41. return
  42. }
  43. func syncEnable(name string) {
  44. nodes := getSyncNodes(name)
  45. wg := &sync.WaitGroup{}
  46. wg.Add(len(nodes))
  47. for _, node := range nodes {
  48. go func() {
  49. defer func() {
  50. if err := recover(); err != nil {
  51. buf := make([]byte, 1024)
  52. runtime.Stack(buf, false)
  53. logger.Error(err)
  54. }
  55. }()
  56. defer wg.Done()
  57. client := resty.New()
  58. client.SetBaseURL(node.URL)
  59. resp, err := client.R().
  60. SetHeader("X-Node-Secret", node.Token).
  61. Post(fmt.Sprintf("/api/sites/%s/enable", name))
  62. if err != nil {
  63. notification.Error("Enable Remote Site Error", err.Error(), nil)
  64. return
  65. }
  66. if resp.StatusCode() != http.StatusOK {
  67. notification.Error("Enable Remote Site Error", "Enable site %{name} on %{node} failed", NewSyncResult(node.Name, name, resp))
  68. return
  69. }
  70. notification.Success("Enable Remote Site Success", "Enable site %{name} on %{node} successfully", NewSyncResult(node.Name, name, resp))
  71. }()
  72. }
  73. wg.Wait()
  74. }