save.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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. var output string
  36. output, err = nginx.TestConfig()
  37. if err != nil {
  38. return
  39. }
  40. if nginx.GetLogLevel(output) > nginx.Warn {
  41. return cosy.WrapErrorWithParams(ErrNginxTestFailed, output)
  42. }
  43. if postAction == model.PostSyncActionReloadNginx {
  44. output, err = nginx.Reload()
  45. if err != nil {
  46. return
  47. }
  48. if nginx.GetLogLevel(output) > nginx.Warn {
  49. return cosy.WrapErrorWithParams(ErrNginxReloadFailed, output)
  50. }
  51. }
  52. }
  53. s := query.Site
  54. _, err = s.Where(s.Path.Eq(path)).
  55. Select(s.EnvGroupID, s.SyncNodeIDs).
  56. Updates(&model.Site{
  57. EnvGroupID: envGroupId,
  58. SyncNodeIDs: syncNodeIds,
  59. })
  60. if err != nil {
  61. return
  62. }
  63. go syncSave(name, content)
  64. return
  65. }
  66. func syncSave(name string, content string) {
  67. nodes, postSyncAction := getSyncData(name)
  68. wg := &sync.WaitGroup{}
  69. wg.Add(len(nodes))
  70. // Map to track successful nodes for potential post-sync action
  71. successfulNodes := make([]*model.Environment, 0)
  72. var nodesMutex sync.Mutex
  73. for _, node := range nodes {
  74. go func(node *model.Environment) {
  75. defer func() {
  76. if err := recover(); err != nil {
  77. buf := make([]byte, 1024)
  78. runtime.Stack(buf, false)
  79. logger.Error(err)
  80. }
  81. }()
  82. defer wg.Done()
  83. client := resty.New()
  84. client.SetBaseURL(node.URL)
  85. resp, err := client.R().
  86. SetHeader("X-Node-Secret", node.Token).
  87. SetBody(map[string]interface{}{
  88. "content": content,
  89. "overwrite": true,
  90. "post_action": postSyncAction,
  91. }).
  92. Post(fmt.Sprintf("/api/sites/%s", name))
  93. if err != nil {
  94. notification.Error("Save Remote Site Error", err.Error(), nil)
  95. return
  96. }
  97. if resp.StatusCode() != http.StatusOK {
  98. notification.Error("Save Remote Site Error", "Save site %{name} to %{node} failed", NewSyncResult(node.Name, name, resp))
  99. return
  100. }
  101. notification.Success("Save Remote Site Success", "Save site %{name} to %{node} successfully", NewSyncResult(node.Name, name, resp))
  102. // Track successful sync for post-sync action
  103. nodesMutex.Lock()
  104. successfulNodes = append(successfulNodes, node)
  105. nodesMutex.Unlock()
  106. // Check if the site is enabled, if so then enable it on the remote node
  107. enabledConfigFilePath := nginx.GetConfPath("sites-enabled", name)
  108. if helper.FileExists(enabledConfigFilePath) {
  109. syncEnable(name)
  110. }
  111. }(node)
  112. }
  113. wg.Wait()
  114. }