modules.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. package nginx
  2. import (
  3. "os"
  4. "regexp"
  5. "strings"
  6. "sync"
  7. "time"
  8. "github.com/elliotchance/orderedmap/v3"
  9. )
  10. const (
  11. ModuleStream = "stream"
  12. )
  13. type Module struct {
  14. Name string `json:"name"`
  15. Params string `json:"params,omitempty"`
  16. Dynamic bool `json:"dynamic"`
  17. Loaded bool `json:"loaded"`
  18. }
  19. // modulesCache stores the cached modules list and related metadata
  20. var (
  21. modulesCache = orderedmap.NewOrderedMap[string, *Module]()
  22. modulesCacheLock sync.RWMutex
  23. lastPIDPath string
  24. lastPIDModTime time.Time
  25. lastPIDSize int64
  26. )
  27. // clearModulesCache clears the modules cache
  28. func clearModulesCache() {
  29. modulesCacheLock.Lock()
  30. defer modulesCacheLock.Unlock()
  31. modulesCache = orderedmap.NewOrderedMap[string, *Module]()
  32. lastPIDPath = ""
  33. lastPIDModTime = time.Time{}
  34. lastPIDSize = 0
  35. }
  36. // isPIDFileChanged checks if the PID file has changed since the last check
  37. func isPIDFileChanged() bool {
  38. pidPath := GetPIDPath()
  39. // If PID path has changed, consider it changed
  40. if pidPath != lastPIDPath {
  41. return true
  42. }
  43. // If Nginx is not running, consider PID changed
  44. if !IsRunning() {
  45. return true
  46. }
  47. // Check if PID file has changed (modification time or size)
  48. fileInfo, err := os.Stat(pidPath)
  49. if err != nil {
  50. return true
  51. }
  52. modTime := fileInfo.ModTime()
  53. size := fileInfo.Size()
  54. return modTime != lastPIDModTime || size != lastPIDSize
  55. }
  56. // updatePIDFileInfo updates the stored PID file information
  57. func updatePIDFileInfo() {
  58. pidPath := GetPIDPath()
  59. if fileInfo, err := os.Stat(pidPath); err == nil {
  60. modulesCacheLock.Lock()
  61. defer modulesCacheLock.Unlock()
  62. lastPIDPath = pidPath
  63. lastPIDModTime = fileInfo.ModTime()
  64. lastPIDSize = fileInfo.Size()
  65. }
  66. }
  67. // updateDynamicModulesStatus checks which dynamic modules are actually loaded in the running Nginx
  68. func updateDynamicModulesStatus() {
  69. modulesCacheLock.Lock()
  70. defer modulesCacheLock.Unlock()
  71. // If cache is empty, there's nothing to update
  72. if modulesCache.Len() == 0 {
  73. return
  74. }
  75. // Get nginx -T output to check for loaded modules
  76. out := getNginxT()
  77. if out == "" {
  78. return
  79. }
  80. // Regular expression to find loaded dynamic modules in nginx -T output
  81. // Look for lines like "load_module modules/ngx_http_image_filter_module.so;"
  82. loadModuleRe := regexp.MustCompile(`load_module\s+(?:modules/|/.*/)([a-zA-Z0-9_-]+)\.so;`)
  83. matches := loadModuleRe.FindAllStringSubmatch(out, -1)
  84. for _, match := range matches {
  85. if len(match) > 1 {
  86. // Extract the module name without path and suffix
  87. moduleName := match[1]
  88. // Some normalization to match format in GetModules
  89. moduleName = strings.TrimPrefix(moduleName, "ngx_")
  90. moduleName = strings.TrimSuffix(moduleName, "_module")
  91. module, ok := modulesCache.Get(moduleName)
  92. if ok {
  93. module.Loaded = true
  94. }
  95. }
  96. }
  97. }
  98. func GetModules() *orderedmap.OrderedMap[string, *Module] {
  99. modulesCacheLock.RLock()
  100. cachedModules := modulesCache
  101. modulesCacheLock.RUnlock()
  102. // If we have cached modules and PID file hasn't changed, return cached modules
  103. if cachedModules.Len() > 0 && !isPIDFileChanged() {
  104. return cachedModules
  105. }
  106. // If PID has changed or we don't have cached modules, get fresh modules
  107. out := getNginxV()
  108. // Regular expression to find module parameters with values
  109. paramRe := regexp.MustCompile(`--with-([a-zA-Z0-9_-]+)(?:_module)?(?:=([^"'\s]+|"[^"]*"|'[^']*'))?`)
  110. paramMatches := paramRe.FindAllStringSubmatch(out, -1)
  111. // Update cache
  112. modulesCacheLock.Lock()
  113. modulesCache = orderedmap.NewOrderedMap[string, *Module]()
  114. // Extract module names and parameters from matches
  115. for _, match := range paramMatches {
  116. if len(match) > 1 {
  117. module := match[1]
  118. var params string
  119. // Check if there's a parameter value
  120. if len(match) > 2 && match[2] != "" {
  121. params = match[2]
  122. // Remove surrounding quotes if present
  123. params = strings.TrimPrefix(params, "'")
  124. params = strings.TrimPrefix(params, "\"")
  125. params = strings.TrimSuffix(params, "'")
  126. params = strings.TrimSuffix(params, "\"")
  127. }
  128. // Special handling for configuration options like cc-opt, not actual modules
  129. if module == "cc-opt" || module == "ld-opt" || module == "prefix" {
  130. modulesCache.Set(module, &Module{
  131. Name: module,
  132. Params: params,
  133. Dynamic: false,
  134. Loaded: true,
  135. })
  136. continue
  137. }
  138. // Determine if the module is dynamic
  139. isDynamic := false
  140. if strings.Contains(out, "--with-"+module+"=dynamic") ||
  141. strings.Contains(out, "--with-"+module+"_module=dynamic") {
  142. isDynamic = true
  143. }
  144. if params == "dynamic" {
  145. params = ""
  146. }
  147. modulesCache.Set(module, &Module{
  148. Name: module,
  149. Params: params,
  150. Dynamic: isDynamic,
  151. Loaded: !isDynamic, // Static modules are always loaded
  152. })
  153. }
  154. }
  155. modulesCacheLock.Unlock()
  156. // Update dynamic modules status by checking if they're actually loaded
  157. updateDynamicModulesStatus()
  158. // Update PID file info
  159. updatePIDFileInfo()
  160. return modulesCache
  161. }
  162. // IsModuleLoaded checks if a module is loaded in Nginx
  163. func IsModuleLoaded(module string) bool {
  164. // Ensure modules are in the cache
  165. if modulesCache.Len() == 0 {
  166. GetModules()
  167. }
  168. modulesCacheLock.RLock()
  169. defer modulesCacheLock.RUnlock()
  170. status, exists := modulesCache.Get(module)
  171. if !exists {
  172. return false
  173. }
  174. return status.Loaded
  175. }