sync.go 6.8 KB

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