enable.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package site
  2. import (
  3. "fmt"
  4. "github.com/0xJacky/Nginx-UI/internal/helper"
  5. "github.com/0xJacky/Nginx-UI/internal/nginx"
  6. "github.com/0xJacky/Nginx-UI/internal/notification"
  7. "github.com/go-resty/resty/v2"
  8. "github.com/uozi-tech/cosy/logger"
  9. "net/http"
  10. "os"
  11. "runtime"
  12. "sync"
  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(output)
  34. }
  35. output = nginx.Reload()
  36. if nginx.GetLogLevel(output) > nginx.Warn {
  37. return fmt.Errorf(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. Post(fmt.Sprintf("/api/sites/%s/enable", name))
  60. if err != nil {
  61. notification.Error("Enable Remote Site Error", err.Error())
  62. return
  63. }
  64. if resp.StatusCode() != http.StatusOK {
  65. notification.Error("Enable Remote Site Error", string(resp.Body()))
  66. return
  67. }
  68. notification.Success("Enable Remote Site Success", string(resp.Body()))
  69. }()
  70. }
  71. wg.Wait()
  72. }