enable.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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/logger"
  13. )
  14. // Enable enables a site by creating a symlink in sites-enabled
  15. func Enable(name string) (err error) {
  16. configFilePath := nginx.GetConfPath("sites-available", name)
  17. enabledConfigFilePath := nginx.GetConfSymlinkPath(nginx.GetConfPath("sites-enabled", name))
  18. _, err = os.Stat(configFilePath)
  19. if err != nil {
  20. return
  21. }
  22. if helper.FileExists(enabledConfigFilePath) {
  23. return
  24. }
  25. err = os.Symlink(configFilePath, enabledConfigFilePath)
  26. if err != nil {
  27. return
  28. }
  29. // Test nginx config, if not pass, then disable the site.
  30. res := nginx.Control(nginx.TestConfig)
  31. if res.IsError() {
  32. return res.GetError()
  33. }
  34. res = nginx.Control(nginx.Reload)
  35. if res.IsError() {
  36. return res.GetError()
  37. }
  38. go syncEnable(name)
  39. return
  40. }
  41. func syncEnable(name string) {
  42. nodes := getSyncNodes(name)
  43. wg := &sync.WaitGroup{}
  44. wg.Add(len(nodes))
  45. for _, node := range nodes {
  46. go func() {
  47. defer func() {
  48. if err := recover(); err != nil {
  49. buf := make([]byte, 1024)
  50. runtime.Stack(buf, false)
  51. logger.Error(err)
  52. }
  53. }()
  54. defer wg.Done()
  55. client := resty.New()
  56. client.SetBaseURL(node.URL)
  57. resp, err := client.R().
  58. SetHeader("X-Node-Secret", node.Token).
  59. Post(fmt.Sprintf("/api/sites/%s/enable", name))
  60. if err != nil {
  61. notification.Error("Enable Remote Site Error", err.Error(), nil)
  62. return
  63. }
  64. if resp.StatusCode() != http.StatusOK {
  65. notification.Error("Enable Remote Site Error", "Enable site %{name} on %{node} failed", NewSyncResult(node.Name, name, resp))
  66. return
  67. }
  68. notification.Success("Enable Remote Site Success", "Enable site %{name} on %{node} successfully", NewSyncResult(node.Name, name, resp))
  69. }()
  70. }
  71. wg.Wait()
  72. }