sync.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. package config
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "github.com/0xJacky/Nginx-UI/internal/helper"
  7. "github.com/0xJacky/Nginx-UI/internal/nginx"
  8. "github.com/0xJacky/Nginx-UI/internal/notification"
  9. "github.com/0xJacky/Nginx-UI/internal/transport"
  10. "github.com/0xJacky/Nginx-UI/model"
  11. "github.com/0xJacky/Nginx-UI/query"
  12. "github.com/0xJacky/Nginx-UI/settings"
  13. "github.com/gin-gonic/gin"
  14. "github.com/uozi-tech/cosy/logger"
  15. "io"
  16. "net/http"
  17. "os"
  18. "path/filepath"
  19. "strings"
  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...)).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. RespBody string `json:"resp_body"`
  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. RespBody: string(respBody),
  125. }
  126. notificationPayloadBytes, err := json.Marshal(notificationPayload)
  127. if err != nil {
  128. return
  129. }
  130. if resp.StatusCode != http.StatusOK {
  131. notification.Error("Sync Config Error", string(notificationPayloadBytes))
  132. return
  133. }
  134. notification.Success("Sync Config Success", string(notificationPayloadBytes))
  135. return
  136. }
  137. type RenameConfigPayload struct {
  138. Filepath string `json:"filepath"`
  139. NewFilepath string `json:"new_filepath"`
  140. }
  141. type SyncRenameNotificationPayload struct {
  142. StatusCode int `json:"status_code"`
  143. OrigPath string `json:"orig_path"`
  144. NewPath string `json:"new_path"`
  145. EnvName string `json:"env_name"`
  146. RespBody string `json:"resp_body"`
  147. }
  148. func (p *RenameConfigPayload) rename(env *model.Environment) (err error) {
  149. // handle rename
  150. if p.NewFilepath == "" || p.Filepath == p.NewFilepath {
  151. return
  152. }
  153. client := http.Client{
  154. Transport: &http.Transport{
  155. TLSClientConfig: &tls.Config{InsecureSkipVerify: settings.HTTPSettings.InsecureSkipVerify},
  156. },
  157. }
  158. payloadBytes, err := json.Marshal(gin.H{
  159. "base_path": strings.ReplaceAll(filepath.Dir(p.Filepath), nginx.GetConfPath(), ""),
  160. "orig_name": filepath.Base(p.Filepath),
  161. "new_name": filepath.Base(p.NewFilepath),
  162. })
  163. if err != nil {
  164. return
  165. }
  166. url, err := env.GetUrl("/api/config_rename")
  167. if err != nil {
  168. return
  169. }
  170. req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(payloadBytes))
  171. if err != nil {
  172. return
  173. }
  174. req.Header.Set("X-Node-Secret", env.Token)
  175. resp, err := client.Do(req)
  176. if err != nil {
  177. return
  178. }
  179. defer resp.Body.Close()
  180. respBody, err := io.ReadAll(resp.Body)
  181. if err != nil {
  182. return
  183. }
  184. notificationPayload := &SyncRenameNotificationPayload{
  185. StatusCode: resp.StatusCode,
  186. OrigPath: p.Filepath,
  187. NewPath: p.NewFilepath,
  188. EnvName: env.Name,
  189. RespBody: string(respBody),
  190. }
  191. notificationPayloadBytes, err := json.Marshal(notificationPayload)
  192. if err != nil {
  193. return
  194. }
  195. if resp.StatusCode != http.StatusOK {
  196. notification.Error("Rename Remote Config Error", string(notificationPayloadBytes))
  197. return
  198. }
  199. notification.Success("Rename Remote Config Success", string(notificationPayloadBytes))
  200. return
  201. }