save.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. package site
  2. import (
  3. "fmt"
  4. "net/http"
  5. "os"
  6. "runtime"
  7. "sync"
  8. "github.com/0xJacky/Nginx-UI/internal/config"
  9. "github.com/0xJacky/Nginx-UI/internal/helper"
  10. "github.com/0xJacky/Nginx-UI/internal/nginx"
  11. "github.com/0xJacky/Nginx-UI/internal/notification"
  12. "github.com/0xJacky/Nginx-UI/model"
  13. "github.com/0xJacky/Nginx-UI/query"
  14. "github.com/go-resty/resty/v2"
  15. "github.com/uozi-tech/cosy"
  16. "github.com/uozi-tech/cosy/logger"
  17. )
  18. // Save saves a site configuration file
  19. func Save(name string, content string, overwrite bool, envGroupId uint64, syncNodeIds []uint64, postAction string) (err error) {
  20. path := nginx.GetConfPath("sites-available", name)
  21. if !overwrite && helper.FileExists(path) {
  22. return ErrDstFileExists
  23. }
  24. err = config.CheckAndCreateHistory(path, content)
  25. if err != nil {
  26. return
  27. }
  28. err = os.WriteFile(path, []byte(content), 0644)
  29. if err != nil {
  30. return
  31. }
  32. enabledConfigFilePath := nginx.GetConfPath("sites-enabled", name)
  33. if helper.FileExists(enabledConfigFilePath) {
  34. // Test nginx configuration
  35. output := nginx.TestConf()
  36. if nginx.GetLogLevel(output) > nginx.Warn {
  37. return cosy.WrapErrorWithParams(ErrNginxTestFailed, output)
  38. }
  39. if postAction == model.PostSyncActionReloadNginx {
  40. output = nginx.Reload()
  41. if nginx.GetLogLevel(output) > nginx.Warn {
  42. return cosy.WrapErrorWithParams(ErrNginxReloadFailed, output)
  43. }
  44. }
  45. }
  46. s := query.Site
  47. _, err = s.Where(s.Path.Eq(path)).
  48. Select(s.EnvGroupID, s.SyncNodeIDs).
  49. Updates(&model.Site{
  50. EnvGroupID: envGroupId,
  51. SyncNodeIDs: syncNodeIds,
  52. })
  53. if err != nil {
  54. return
  55. }
  56. go syncSave(name, content)
  57. return
  58. }
  59. func syncSave(name string, content string) {
  60. nodes, postSyncAction := getSyncData(name)
  61. wg := &sync.WaitGroup{}
  62. wg.Add(len(nodes))
  63. // Map to track successful nodes for potential post-sync action
  64. successfulNodes := make([]*model.Environment, 0)
  65. var nodesMutex sync.Mutex
  66. for _, node := range nodes {
  67. go func(node *model.Environment) {
  68. defer func() {
  69. if err := recover(); err != nil {
  70. buf := make([]byte, 1024)
  71. runtime.Stack(buf, false)
  72. logger.Error(err)
  73. }
  74. }()
  75. defer wg.Done()
  76. client := resty.New()
  77. client.SetBaseURL(node.URL)
  78. resp, err := client.R().
  79. SetHeader("X-Node-Secret", node.Token).
  80. SetBody(map[string]interface{}{
  81. "content": content,
  82. "overwrite": true,
  83. "post_action": postSyncAction,
  84. }).
  85. Post(fmt.Sprintf("/api/sites/%s", name))
  86. if err != nil {
  87. notification.Error("Save Remote Site Error", err.Error(), nil)
  88. return
  89. }
  90. if resp.StatusCode() != http.StatusOK {
  91. notification.Error("Save Remote Site Error", "Save site %{name} to %{node} failed", NewSyncResult(node.Name, name, resp))
  92. return
  93. }
  94. notification.Success("Save Remote Site Success", "Save site %{name} to %{node} successfully", NewSyncResult(node.Name, name, resp))
  95. // Track successful sync for post-sync action
  96. nodesMutex.Lock()
  97. successfulNodes = append(successfulNodes, node)
  98. nodesMutex.Unlock()
  99. // Check if the site is enabled, if so then enable it on the remote node
  100. enabledConfigFilePath := nginx.GetConfPath("sites-enabled", name)
  101. if helper.FileExists(enabledConfigFilePath) {
  102. syncEnable(name)
  103. }
  104. }(node)
  105. }
  106. wg.Wait()
  107. }