perf_opt.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. package performance
  2. import (
  3. "os"
  4. "sort"
  5. ngxConfig "github.com/0xJacky/Nginx-UI/internal/config"
  6. "github.com/0xJacky/Nginx-UI/internal/nginx"
  7. "github.com/pkg/errors"
  8. "github.com/tufanbarisyildirim/gonginx/config"
  9. "github.com/tufanbarisyildirim/gonginx/dumper"
  10. "github.com/tufanbarisyildirim/gonginx/parser"
  11. )
  12. type ProxyCacheConfig struct {
  13. Enabled bool `json:"enabled"`
  14. Path string `json:"path"` // Cache file path
  15. Levels string `json:"levels"` // Cache directory levels
  16. UseTempPath string `json:"use_temp_path"` // Use temporary path (on/off)
  17. KeysZone string `json:"keys_zone"` // Shared memory zone name and size
  18. Inactive string `json:"inactive"` // Time after which inactive cache is removed
  19. MaxSize string `json:"max_size"` // Maximum size of cache
  20. MinFree string `json:"min_free"` // Minimum free space
  21. ManagerFiles string `json:"manager_files"` // Number of files processed by manager
  22. ManagerSleep string `json:"manager_sleep"` // Manager check interval
  23. ManagerThreshold string `json:"manager_threshold"` // Manager processing threshold
  24. LoaderFiles string `json:"loader_files"` // Number of files loaded at once
  25. LoaderSleep string `json:"loader_sleep"` // Loader check interval
  26. LoaderThreshold string `json:"loader_threshold"` // Loader processing threshold
  27. // Additionally, the following parameters are available as part of nginx commercial subscription:
  28. // Purger string `json:"purger"` // Enable cache purger (on/off)
  29. // PurgerFiles string `json:"purger_files"` // Number of files processed by purger
  30. // PurgerSleep string `json:"purger_sleep"` // Purger check interval
  31. // PurgerThreshold string `json:"purger_threshold"` // Purger processing threshold
  32. }
  33. // PerfOpt represents Nginx performance optimization settings
  34. type PerfOpt struct {
  35. WorkerProcesses string `json:"worker_processes"` // auto or number
  36. WorkerConnections string `json:"worker_connections"` // max connections
  37. KeepaliveTimeout string `json:"keepalive_timeout"` // timeout in seconds
  38. Gzip string `json:"gzip"` // on or off
  39. GzipMinLength string `json:"gzip_min_length"` // min length to compress
  40. GzipCompLevel string `json:"gzip_comp_level"` // compression level
  41. ClientMaxBodySize string `json:"client_max_body_size"` // max body size (with unit: k, m, g)
  42. ServerNamesHashBucketSize string `json:"server_names_hash_bucket_size"` // hash bucket size
  43. ClientHeaderBufferSize string `json:"client_header_buffer_size"` // header buffer size (with unit: k, m, g)
  44. ClientBodyBufferSize string `json:"client_body_buffer_size"` // body buffer size (with unit: k, m, g)
  45. ProxyCache ProxyCacheConfig `json:"proxy_cache,omitzero"` // proxy cache settings
  46. }
  47. // UpdatePerfOpt updates the Nginx performance optimization settings
  48. func UpdatePerfOpt(opt *PerfOpt) error {
  49. confPath := nginx.GetConfPath("nginx.conf")
  50. if confPath == "" {
  51. return errors.New("failed to get nginx.conf path")
  52. }
  53. // Read the current configuration
  54. content, err := os.ReadFile(confPath)
  55. if err != nil {
  56. return errors.Wrap(err, "failed to read nginx.conf")
  57. }
  58. // Parse the configuration
  59. p := parser.NewStringParser(string(content), parser.WithSkipValidDirectivesErr())
  60. conf, err := p.Parse()
  61. if err != nil {
  62. return errors.Wrap(err, "failed to parse nginx.conf")
  63. }
  64. // Process the configuration and update performance settings
  65. updateNginxConfig(conf.Block, opt)
  66. // Dump the updated configuration
  67. updatedConf := dumper.DumpBlock(conf.Block, dumper.IndentedStyle)
  68. return ngxConfig.Save(confPath, updatedConf, nil)
  69. }
  70. // updateNginxConfig updates the performance settings in the Nginx configuration
  71. func updateNginxConfig(block config.IBlock, opt *PerfOpt) {
  72. if block == nil {
  73. return
  74. }
  75. directives := block.GetDirectives()
  76. // Update main context directives
  77. updateOrAddDirective(block, directives, "worker_processes", opt.WorkerProcesses)
  78. // Look for events, http, and other blocks
  79. for _, directive := range directives {
  80. if directive.GetName() == "events" && directive.GetBlock() != nil {
  81. // Update events block directives
  82. eventsBlock := directive.GetBlock()
  83. eventsDirectives := eventsBlock.GetDirectives()
  84. updateOrAddDirective(eventsBlock, eventsDirectives, "worker_connections", opt.WorkerConnections)
  85. } else if directive.GetName() == "http" && directive.GetBlock() != nil {
  86. // Update http block directives
  87. httpBlock := directive.GetBlock()
  88. httpDirectives := httpBlock.GetDirectives()
  89. updateOrAddDirective(httpBlock, httpDirectives, "keepalive_timeout", opt.KeepaliveTimeout)
  90. updateOrAddDirective(httpBlock, httpDirectives, "gzip", opt.Gzip)
  91. updateOrAddDirective(httpBlock, httpDirectives, "gzip_min_length", opt.GzipMinLength)
  92. updateOrAddDirective(httpBlock, httpDirectives, "gzip_comp_level", opt.GzipCompLevel)
  93. updateOrAddDirective(httpBlock, httpDirectives, "client_max_body_size", opt.ClientMaxBodySize)
  94. updateOrAddDirective(httpBlock, httpDirectives, "server_names_hash_bucket_size", opt.ServerNamesHashBucketSize)
  95. updateOrAddDirective(httpBlock, httpDirectives, "client_header_buffer_size", opt.ClientHeaderBufferSize)
  96. updateOrAddDirective(httpBlock, httpDirectives, "client_body_buffer_size", opt.ClientBodyBufferSize)
  97. // Handle proxy_cache_path directive
  98. updateOrRemoveProxyCachePath(httpBlock, httpDirectives, &opt.ProxyCache)
  99. sortDirectives(httpDirectives)
  100. }
  101. }
  102. }
  103. // updateOrAddDirective updates a directive if it exists, or adds it to the block if it doesn't
  104. func updateOrAddDirective(block config.IBlock, directives []config.IDirective, name string, value string) {
  105. if value == "" {
  106. return
  107. }
  108. // Search for existing directive
  109. for _, directive := range directives {
  110. if directive.GetName() == name {
  111. // Update existing directive
  112. if len(directive.GetParameters()) > 0 {
  113. directive.GetParameters()[0].Value = value
  114. }
  115. return
  116. }
  117. }
  118. // If we get here, we need to add a new directive
  119. // Create a new directive and add it to the block
  120. // This requires knowledge of the underlying implementation
  121. // For now, we'll use the Directive type from gonginx/config
  122. newDirective := &config.Directive{
  123. Name: name,
  124. Parameters: []config.Parameter{{Value: value}},
  125. }
  126. // Add the new directive to the block
  127. // This is specific to the gonginx library implementation
  128. switch block := block.(type) {
  129. case *config.Config:
  130. block.Block.Directives = append(block.Block.Directives, newDirective)
  131. case *config.Block:
  132. block.Directives = append(block.Directives, newDirective)
  133. case *config.HTTP:
  134. block.Directives = append(block.Directives, newDirective)
  135. }
  136. }
  137. // sortDirectives sorts directives alphabetically by name
  138. func sortDirectives(directives []config.IDirective) {
  139. sort.SliceStable(directives, func(i, j int) bool {
  140. // Ensure both i and j can return valid names
  141. return directives[i].GetName() < directives[j].GetName()
  142. })
  143. }
  144. // updateOrRemoveProxyCachePath adds or removes the proxy_cache_path directive based on whether it's enabled
  145. func updateOrRemoveProxyCachePath(block config.IBlock, directives []config.IDirective, proxyCache *ProxyCacheConfig) {
  146. // If not enabled, remove the directive if it exists
  147. if !proxyCache.Enabled {
  148. for i, directive := range directives {
  149. if directive.GetName() == "proxy_cache_path" {
  150. // Remove the directive
  151. switch block := block.(type) {
  152. case *config.Block:
  153. block.Directives = append(block.Directives[:i], block.Directives[i+1:]...)
  154. case *config.HTTP:
  155. block.Directives = append(block.Directives[:i], block.Directives[i+1:]...)
  156. }
  157. return
  158. }
  159. }
  160. return
  161. }
  162. // If enabled, build the proxy_cache_path directive with all parameters
  163. params := []config.Parameter{}
  164. // First parameter is the path (required)
  165. if proxyCache.Path != "" {
  166. params = append(params, config.Parameter{Value: proxyCache.Path})
  167. _ = os.MkdirAll(proxyCache.Path, 0755)
  168. } else {
  169. // No path specified, can't add the directive
  170. return
  171. }
  172. // Add optional parameters
  173. if proxyCache.Levels != "" {
  174. params = append(params, config.Parameter{Value: "levels=" + proxyCache.Levels})
  175. }
  176. if proxyCache.UseTempPath != "" {
  177. params = append(params, config.Parameter{Value: "use_temp_path=" + proxyCache.UseTempPath})
  178. }
  179. if proxyCache.KeysZone != "" {
  180. params = append(params, config.Parameter{Value: "keys_zone=" + proxyCache.KeysZone})
  181. } else {
  182. // keys_zone is required, can't add the directive without it
  183. return
  184. }
  185. if proxyCache.Inactive != "" {
  186. params = append(params, config.Parameter{Value: "inactive=" + proxyCache.Inactive})
  187. }
  188. if proxyCache.MaxSize != "" {
  189. params = append(params, config.Parameter{Value: "max_size=" + proxyCache.MaxSize})
  190. }
  191. if proxyCache.MinFree != "" {
  192. params = append(params, config.Parameter{Value: "min_free=" + proxyCache.MinFree})
  193. }
  194. if proxyCache.ManagerFiles != "" {
  195. params = append(params, config.Parameter{Value: "manager_files=" + proxyCache.ManagerFiles})
  196. }
  197. if proxyCache.ManagerSleep != "" {
  198. params = append(params, config.Parameter{Value: "manager_sleep=" + proxyCache.ManagerSleep})
  199. }
  200. if proxyCache.ManagerThreshold != "" {
  201. params = append(params, config.Parameter{Value: "manager_threshold=" + proxyCache.ManagerThreshold})
  202. }
  203. if proxyCache.LoaderFiles != "" {
  204. params = append(params, config.Parameter{Value: "loader_files=" + proxyCache.LoaderFiles})
  205. }
  206. if proxyCache.LoaderSleep != "" {
  207. params = append(params, config.Parameter{Value: "loader_sleep=" + proxyCache.LoaderSleep})
  208. }
  209. if proxyCache.LoaderThreshold != "" {
  210. params = append(params, config.Parameter{Value: "loader_threshold=" + proxyCache.LoaderThreshold})
  211. }
  212. // if proxyCache.Purger != "" {
  213. // params = append(params, config.Parameter{Value: "purger=" + proxyCache.Purger})
  214. // }
  215. // if proxyCache.PurgerFiles != "" {
  216. // params = append(params, config.Parameter{Value: "purger_files=" + proxyCache.PurgerFiles})
  217. // }
  218. // if proxyCache.PurgerSleep != "" {
  219. // params = append(params, config.Parameter{Value: "purger_sleep=" + proxyCache.PurgerSleep})
  220. // }
  221. // if proxyCache.PurgerThreshold != "" {
  222. // params = append(params, config.Parameter{Value: "purger_threshold=" + proxyCache.PurgerThreshold})
  223. // }
  224. // Check if directive already exists
  225. for i, directive := range directives {
  226. if directive.GetName() == "proxy_cache_path" {
  227. // Remove the old directive
  228. switch block := block.(type) {
  229. case *config.HTTP:
  230. block.Directives = append(block.Directives[:i], block.Directives[i+1:]...)
  231. }
  232. break
  233. }
  234. }
  235. // Create new directive
  236. newDirective := &config.Directive{
  237. Name: "proxy_cache_path",
  238. Parameters: params,
  239. }
  240. // Add the directive to the block
  241. switch block := block.(type) {
  242. case *config.HTTP:
  243. block.Directives = append(block.Directives, newDirective)
  244. }
  245. }