sync.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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/logger"
  9. "github.com/0xJacky/Nginx-UI/internal/nginx"
  10. "github.com/0xJacky/Nginx-UI/internal/notification"
  11. "github.com/0xJacky/Nginx-UI/model"
  12. "github.com/0xJacky/Nginx-UI/query"
  13. "github.com/gin-gonic/gin"
  14. "io"
  15. "net/http"
  16. "os"
  17. "path/filepath"
  18. "strings"
  19. )
  20. type SyncConfigPayload struct {
  21. Name string `json:"name"`
  22. Filepath string `json:"filepath"`
  23. NewFilepath string `json:"new_filepath"`
  24. Content string `json:"content"`
  25. Overwrite bool `json:"overwrite"`
  26. }
  27. func SyncToRemoteServer(c *model.Config, newFilepath string) (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 fmt.Errorf("config: %s is not under the nginx conf path: %s",
  34. c.Filepath, nginxConfPath)
  35. }
  36. if newFilepath != "" && !helper.IsUnderDirectory(newFilepath, nginxConfPath) {
  37. return fmt.Errorf("config: %s is not under the nginx conf path: %s",
  38. c.Filepath, nginxConfPath)
  39. }
  40. currentPath := c.Filepath
  41. if newFilepath != "" {
  42. currentPath = newFilepath
  43. }
  44. configBytes, err := os.ReadFile(currentPath)
  45. if err != nil {
  46. return
  47. }
  48. payload := &SyncConfigPayload{
  49. Name: c.Name,
  50. Filepath: c.Filepath,
  51. NewFilepath: newFilepath,
  52. Content: string(configBytes),
  53. Overwrite: c.SyncOverwrite,
  54. }
  55. payloadBytes, err := json.Marshal(payload)
  56. if err != nil {
  57. return
  58. }
  59. q := query.Environment
  60. envs, _ := q.Where(q.ID.In(c.SyncNodeIds...)).Find()
  61. for _, env := range envs {
  62. go func() {
  63. err := payload.deploy(env, c, payloadBytes)
  64. if err != nil {
  65. logger.Error(err)
  66. }
  67. }()
  68. }
  69. return
  70. }
  71. func SyncRenameOnRemoteServer(origPath, newPath string, syncNodeIds []int) (err error) {
  72. if origPath == "" || newPath == "" || len(syncNodeIds) == 0 {
  73. return
  74. }
  75. nginxConfPath := nginx.GetConfPath()
  76. if !helper.IsUnderDirectory(origPath, nginxConfPath) {
  77. return fmt.Errorf("config: %s is not under the nginx conf path: %s",
  78. origPath, nginxConfPath)
  79. }
  80. if !helper.IsUnderDirectory(newPath, nginxConfPath) {
  81. return fmt.Errorf("config: %s is not under the nginx conf path: %s",
  82. newPath, nginxConfPath)
  83. }
  84. payload := &SyncConfigPayload{
  85. Filepath: origPath,
  86. NewFilepath: newPath,
  87. }
  88. q := query.Environment
  89. envs, _ := q.Where(q.ID.In(syncNodeIds...)).Find()
  90. for _, env := range envs {
  91. go func() {
  92. err := payload.rename(env)
  93. if err != nil {
  94. logger.Error(err)
  95. }
  96. }()
  97. }
  98. return
  99. }
  100. type SyncNotificationPayload struct {
  101. StatusCode int `json:"status_code"`
  102. ConfigName string `json:"config_name"`
  103. EnvName string `json:"env_name"`
  104. RespBody string `json:"resp_body"`
  105. }
  106. func (p *SyncConfigPayload) deploy(env *model.Environment, c *model.Config, payloadBytes []byte) (err error) {
  107. client := http.Client{
  108. Transport: &http.Transport{
  109. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  110. },
  111. }
  112. url, err := env.GetUrl("/api/config")
  113. if err != nil {
  114. return
  115. }
  116. req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(payloadBytes))
  117. if err != nil {
  118. return
  119. }
  120. req.Header.Set("X-Node-Secret", env.Token)
  121. resp, err := client.Do(req)
  122. if err != nil {
  123. return
  124. }
  125. defer resp.Body.Close()
  126. respBody, err := io.ReadAll(resp.Body)
  127. if err != nil {
  128. return
  129. }
  130. notificationPayload := &SyncNotificationPayload{
  131. StatusCode: resp.StatusCode,
  132. ConfigName: c.Name,
  133. EnvName: env.Name,
  134. RespBody: string(respBody),
  135. }
  136. notificationPayloadBytes, err := json.Marshal(notificationPayload)
  137. if err != nil {
  138. return
  139. }
  140. if resp.StatusCode != http.StatusOK {
  141. notification.Error("Sync Configuration Error", string(notificationPayloadBytes))
  142. return
  143. }
  144. notification.Success("Sync Configuration Success", string(notificationPayloadBytes))
  145. // handle rename
  146. if p.NewFilepath == "" || p.Filepath == p.NewFilepath {
  147. return
  148. }
  149. payloadBytes, err = json.Marshal(gin.H{
  150. "base_path": filepath.Dir(p.Filepath),
  151. "old_filepath": filepath.Base(p.Filepath),
  152. "new_filepath": filepath.Base(p.NewFilepath),
  153. })
  154. if err != nil {
  155. return
  156. }
  157. url, err = env.GetUrl("/api/config_rename")
  158. if err != nil {
  159. return
  160. }
  161. req, err = http.NewRequest(http.MethodPost, url, bytes.NewBuffer(payloadBytes))
  162. if err != nil {
  163. return
  164. }
  165. req.Header.Set("X-Node-Secret", env.Token)
  166. resp, err = client.Do(req)
  167. if err != nil {
  168. return
  169. }
  170. defer resp.Body.Close()
  171. respBody, err = io.ReadAll(resp.Body)
  172. if err != nil {
  173. return
  174. }
  175. notificationPayload = &SyncNotificationPayload{
  176. StatusCode: resp.StatusCode,
  177. ConfigName: c.Name,
  178. EnvName: env.Name,
  179. RespBody: string(respBody),
  180. }
  181. notificationPayloadBytes, err = json.Marshal(notificationPayload)
  182. if err != nil {
  183. return
  184. }
  185. if resp.StatusCode != http.StatusOK {
  186. notification.Error("Sync Rename Configuration Error", string(notificationPayloadBytes))
  187. return
  188. }
  189. notification.Success("Sync Rename Configuration Success", string(notificationPayloadBytes))
  190. return
  191. }
  192. type SyncRenameNotificationPayload struct {
  193. StatusCode int `json:"status_code"`
  194. OrigPath string `json:"orig_path"`
  195. NewPath string `json:"new_path"`
  196. EnvName string `json:"env_name"`
  197. RespBody string `json:"resp_body"`
  198. }
  199. func (p *SyncConfigPayload) rename(env *model.Environment) (err error) {
  200. // handle rename
  201. if p.NewFilepath == "" || p.Filepath == p.NewFilepath {
  202. return
  203. }
  204. client := http.Client{
  205. Transport: &http.Transport{
  206. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  207. },
  208. }
  209. payloadBytes, err := json.Marshal(gin.H{
  210. "base_path": strings.ReplaceAll(filepath.Dir(p.Filepath), nginx.GetConfPath(), ""),
  211. "orig_name": filepath.Base(p.Filepath),
  212. "new_name": filepath.Base(p.NewFilepath),
  213. })
  214. if err != nil {
  215. return
  216. }
  217. url, err := env.GetUrl("/api/config_rename")
  218. if err != nil {
  219. return
  220. }
  221. req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(payloadBytes))
  222. if err != nil {
  223. return
  224. }
  225. req.Header.Set("X-Node-Secret", env.Token)
  226. resp, err := client.Do(req)
  227. if err != nil {
  228. return
  229. }
  230. defer resp.Body.Close()
  231. respBody, err := io.ReadAll(resp.Body)
  232. if err != nil {
  233. return
  234. }
  235. notificationPayload := &SyncRenameNotificationPayload{
  236. StatusCode: resp.StatusCode,
  237. OrigPath: p.Filepath,
  238. NewPath: p.NewFilepath,
  239. EnvName: env.Name,
  240. RespBody: string(respBody),
  241. }
  242. notificationPayloadBytes, err := json.Marshal(notificationPayload)
  243. if err != nil {
  244. return
  245. }
  246. if resp.StatusCode != http.StatusOK {
  247. notification.Error("Sync Rename Configuration Error", string(notificationPayloadBytes))
  248. return
  249. }
  250. notification.Success("Sync Rename Configuration Success", string(notificationPayloadBytes))
  251. return
  252. }