sync.go 5.4 KB

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