1
0

enable.go 2.0 KB

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