modules.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 !IsNginxRunning() {
  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. // Create a map of loaded dynamic modules
  85. loadedDynamicModules := make(map[string]bool)
  86. for _, match := range matches {
  87. if len(match) > 1 {
  88. // Extract the module name without path and suffix
  89. moduleName := match[1]
  90. // Some normalization to match format in GetModules
  91. moduleName = strings.TrimPrefix(moduleName, "ngx_")
  92. moduleName = strings.TrimSuffix(moduleName, "_module")
  93. loadedDynamicModules[moduleName] = true
  94. }
  95. }
  96. // Update the status for each module in the cache
  97. for key := range modulesCache.Keys() {
  98. // If the module is already marked as dynamic, check if it's actually loaded
  99. if loadedDynamicModules[key] {
  100. modulesCache.Set(key, Module{
  101. Name: key,
  102. Dynamic: true,
  103. Loaded: true,
  104. })
  105. }
  106. }
  107. }
  108. func GetModules() *orderedmap.OrderedMap[string, Module] {
  109. modulesCacheLock.RLock()
  110. cachedModules := modulesCache
  111. modulesCacheLock.RUnlock()
  112. // If we have cached modules and PID file hasn't changed, return cached modules
  113. if cachedModules.Len() > 0 && !isPIDFileChanged() {
  114. return cachedModules
  115. }
  116. // If PID has changed or we don't have cached modules, get fresh modules
  117. out := getNginxV()
  118. // Regular expression to find built-in modules in nginx -V output
  119. builtinRe := regexp.MustCompile(`--with-([a-zA-Z0-9_-]+)(_module)?`)
  120. builtinMatches := builtinRe.FindAllStringSubmatch(out, -1)
  121. // Extract built-in module names from matches and put in map for quick lookup
  122. moduleMap := make(map[string]bool)
  123. for _, match := range builtinMatches {
  124. if len(match) > 1 {
  125. module := match[1]
  126. moduleMap[module] = true
  127. }
  128. }
  129. // Regular expression to find dynamic modules in nginx -V output
  130. dynamicRe := regexp.MustCompile(`--with-([a-zA-Z0-9_-]+)(_module)?=dynamic`)
  131. dynamicMatches := dynamicRe.FindAllStringSubmatch(out, -1)
  132. // Extract dynamic module names from matches
  133. for _, match := range dynamicMatches {
  134. if len(match) > 1 {
  135. module := match[1]
  136. // Only add if not already in list (to avoid duplicates)
  137. if !moduleMap[module] {
  138. moduleMap[module] = true
  139. }
  140. }
  141. }
  142. // Update cache
  143. modulesCacheLock.Lock()
  144. modulesCache = orderedmap.NewOrderedMap[string, Module]()
  145. for module := range moduleMap {
  146. // Mark modules as built-in (loaded) or dynamic (potentially not loaded)
  147. if strings.Contains(out, "--with-"+module+"=dynamic") {
  148. modulesCache.Set(module, Module{
  149. Name: module,
  150. Dynamic: true,
  151. Loaded: true,
  152. })
  153. } else {
  154. modulesCache.Set(module, Module{
  155. Name: module,
  156. Dynamic: true,
  157. })
  158. }
  159. }
  160. modulesCacheLock.Unlock()
  161. // Update dynamic modules status by checking if they're actually loaded
  162. updateDynamicModulesStatus()
  163. // Update PID file info
  164. updatePIDFileInfo()
  165. return modulesCache
  166. }
  167. // IsModuleLoaded checks if a module is loaded in Nginx
  168. func IsModuleLoaded(module string) bool {
  169. // Ensure modules are in the cache
  170. if modulesCache.Len() == 0 {
  171. GetModules()
  172. }
  173. modulesCacheLock.RLock()
  174. defer modulesCacheLock.RUnlock()
  175. status, exists := modulesCache.Get(module)
  176. if !exists {
  177. return false
  178. }
  179. return status.Loaded
  180. }