save.go 3.3 KB

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