save.go 3.0 KB

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