sync.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. package config
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "io"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "github.com/0xJacky/Nginx-UI/internal/helper"
  12. "github.com/0xJacky/Nginx-UI/internal/nginx"
  13. "github.com/0xJacky/Nginx-UI/internal/notification"
  14. "github.com/0xJacky/Nginx-UI/internal/transport"
  15. "github.com/0xJacky/Nginx-UI/model"
  16. "github.com/0xJacky/Nginx-UI/query"
  17. "github.com/0xJacky/Nginx-UI/settings"
  18. "github.com/gin-gonic/gin"
  19. "github.com/uozi-tech/cosy/logger"
  20. )
  21. type SyncConfigPayload struct {
  22. Name string `json:"name" binding:"required"`
  23. BaseDir string `json:"base_dir"`
  24. Content string `json:"content"`
  25. Overwrite bool `json:"overwrite"`
  26. }
  27. func SyncToRemoteServer(c *model.Config) (err error) {
  28. if c.Filepath == "" || len(c.SyncNodeIds) == 0 {
  29. return
  30. }
  31. nginxConfPath := nginx.GetConfPath()
  32. if !helper.IsUnderDirectory(c.Filepath, nginxConfPath) {
  33. return e.NewWithParams(50006, ErrPathIsNotUnderTheNginxConfDir.Error(), c.Filepath, nginxConfPath)
  34. }
  35. configBytes, err := os.ReadFile(c.Filepath)
  36. if err != nil {
  37. return
  38. }
  39. payload := &SyncConfigPayload{
  40. Name: c.Name,
  41. BaseDir: strings.ReplaceAll(filepath.Dir(c.Filepath), nginx.GetConfPath(), ""),
  42. Content: string(configBytes),
  43. Overwrite: c.SyncOverwrite,
  44. }
  45. payloadBytes, err := json.Marshal(payload)
  46. if err != nil {
  47. return
  48. }
  49. q := query.Environment
  50. envs, _ := q.Where(q.ID.In(c.SyncNodeIds...), q.Enabled.Is(true)).Find()
  51. for _, env := range envs {
  52. go func() {
  53. err := payload.deploy(env, c, payloadBytes)
  54. if err != nil {
  55. logger.Error(err)
  56. }
  57. }()
  58. }
  59. return
  60. }
  61. func SyncRenameOnRemoteServer(origPath, newPath string, syncNodeIds []uint64) (err error) {
  62. if origPath == "" || newPath == "" || len(syncNodeIds) == 0 {
  63. return
  64. }
  65. nginxConfPath := nginx.GetConfPath()
  66. if !helper.IsUnderDirectory(origPath, nginxConfPath) {
  67. return e.NewWithParams(50006, ErrPathIsNotUnderTheNginxConfDir.Error(), origPath, nginxConfPath)
  68. }
  69. if !helper.IsUnderDirectory(newPath, nginxConfPath) {
  70. return e.NewWithParams(50006, ErrPathIsNotUnderTheNginxConfDir.Error(), newPath, nginxConfPath)
  71. }
  72. payload := &RenameConfigPayload{
  73. Filepath: origPath,
  74. NewFilepath: newPath,
  75. }
  76. q := query.Environment
  77. envs, _ := q.Where(q.ID.In(syncNodeIds...)).Find()
  78. for _, env := range envs {
  79. go func() {
  80. err := payload.rename(env)
  81. if err != nil {
  82. logger.Error(err)
  83. }
  84. }()
  85. }
  86. return
  87. }
  88. type SyncNotificationPayload struct {
  89. StatusCode int `json:"status_code"`
  90. ConfigName string `json:"config_name"`
  91. EnvName string `json:"env_name"`
  92. Response string `json:"response"`
  93. }
  94. func (p *SyncConfigPayload) deploy(env *model.Environment, c *model.Config, payloadBytes []byte) (err error) {
  95. t, err := transport.NewTransport()
  96. if err != nil {
  97. return
  98. }
  99. client := http.Client{
  100. Transport: t,
  101. }
  102. url, err := env.GetUrl("/api/configs")
  103. if err != nil {
  104. return
  105. }
  106. req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(payloadBytes))
  107. if err != nil {
  108. return
  109. }
  110. req.Header.Set("X-Node-Secret", env.Token)
  111. resp, err := client.Do(req)
  112. if err != nil {
  113. return
  114. }
  115. defer resp.Body.Close()
  116. respBody, err := io.ReadAll(resp.Body)
  117. if err != nil {
  118. return
  119. }
  120. notificationPayload := &SyncNotificationPayload{
  121. StatusCode: resp.StatusCode,
  122. ConfigName: c.Name,
  123. EnvName: env.Name,
  124. Response: string(respBody),
  125. }
  126. if resp.StatusCode != http.StatusOK {
  127. notification.Error("Sync Config Error", "Sync config %{config_name} to %{env_name} failed", notificationPayload)
  128. return
  129. }
  130. notification.Success("Sync Config Success", "Sync config %{config_name} to %{env_name} successfully", notificationPayload)
  131. return
  132. }
  133. type RenameConfigPayload struct {
  134. Filepath string `json:"filepath"`
  135. NewFilepath string `json:"new_filepath"`
  136. }
  137. type SyncRenameNotificationPayload struct {
  138. StatusCode int `json:"status_code"`
  139. OrigPath string `json:"orig_path"`
  140. NewPath string `json:"new_path"`
  141. EnvName string `json:"env_name"`
  142. Response string `json:"response"`
  143. }
  144. func (p *RenameConfigPayload) rename(env *model.Environment) (err error) {
  145. // handle rename
  146. if p.NewFilepath == "" || p.Filepath == p.NewFilepath {
  147. return
  148. }
  149. client := http.Client{
  150. Transport: &http.Transport{
  151. TLSClientConfig: &tls.Config{InsecureSkipVerify: settings.HTTPSettings.InsecureSkipVerify},
  152. },
  153. }
  154. payloadBytes, err := json.Marshal(gin.H{
  155. "base_path": strings.ReplaceAll(filepath.Dir(p.Filepath), nginx.GetConfPath(), ""),
  156. "orig_name": filepath.Base(p.Filepath),
  157. "new_name": filepath.Base(p.NewFilepath),
  158. })
  159. if err != nil {
  160. return
  161. }
  162. url, err := env.GetUrl("/api/config_rename")
  163. if err != nil {
  164. return
  165. }
  166. req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(payloadBytes))
  167. if err != nil {
  168. return
  169. }
  170. req.Header.Set("X-Node-Secret", env.Token)
  171. resp, err := client.Do(req)
  172. if err != nil {
  173. return
  174. }
  175. defer resp.Body.Close()
  176. respBody, err := io.ReadAll(resp.Body)
  177. if err != nil {
  178. return
  179. }
  180. notificationPayload := &SyncRenameNotificationPayload{
  181. StatusCode: resp.StatusCode,
  182. OrigPath: p.Filepath,
  183. NewPath: p.NewFilepath,
  184. EnvName: env.Name,
  185. Response: string(respBody),
  186. }
  187. if resp.StatusCode != http.StatusOK {
  188. notification.Error("Rename Remote Config Error", "Rename %{orig_path} to %{new_path} on %{env_name} failed", notificationPayload)
  189. return
  190. }
  191. notification.Success("Rename Remote Config Success", "Rename %{orig_path} to %{new_path} on %{env_name} successfully", notificationPayload)
  192. return
  193. }