modern_services.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. package nginx_log
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "sync"
  8. "github.com/0xJacky/Nginx-UI/internal/nginx_log/analytics"
  9. "github.com/0xJacky/Nginx-UI/internal/nginx_log/indexer"
  10. "github.com/0xJacky/Nginx-UI/internal/nginx_log/searcher"
  11. "github.com/blevesearch/bleve/v2"
  12. "github.com/uozi-tech/cosy/logger"
  13. cSettings "github.com/uozi-tech/cosy/settings"
  14. )
  15. // Global instances for new services
  16. var (
  17. globalSearcher searcher.Searcher
  18. globalAnalytics analytics.Service
  19. globalIndexer *indexer.ParallelIndexer
  20. globalLogFileManager *indexer.LogFileManager
  21. servicesInitialized bool
  22. servicesMutex sync.RWMutex
  23. )
  24. // InitializeModernServices initializes the new modular services
  25. func InitializeModernServices(ctx context.Context) {
  26. servicesMutex.Lock()
  27. defer servicesMutex.Unlock()
  28. if servicesInitialized {
  29. logger.Info("Modern nginx log services already initialized, skipping")
  30. return
  31. }
  32. logger.Info("Initializing modern nginx log services...")
  33. // Initialize with default configuration directly
  34. if err := initializeWithDefaults(ctx); err != nil {
  35. logger.Errorf("Failed to initialize modern services: %v", err)
  36. return
  37. }
  38. logger.Info("Modern nginx log services initialization completed")
  39. // Monitor context for shutdown
  40. go func() {
  41. logger.Info("Started nginx_log shutdown monitor goroutine")
  42. <-ctx.Done()
  43. logger.Info("Shutting down modern nginx log services...")
  44. servicesMutex.Lock()
  45. defer servicesMutex.Unlock()
  46. // Stop services
  47. if globalIndexer != nil {
  48. if err := globalIndexer.Stop(); err != nil {
  49. logger.Errorf("Failed to stop indexer: %v", err)
  50. }
  51. }
  52. // Stop searcher if it exists
  53. if globalSearcher != nil {
  54. if err := globalSearcher.Stop(); err != nil {
  55. logger.Errorf("Failed to stop searcher: %v", err)
  56. }
  57. }
  58. servicesInitialized = false
  59. logger.Info("Modern nginx log services shut down")
  60. logger.Info("Nginx_log shutdown monitor goroutine completed")
  61. }()
  62. }
  63. // initializeWithDefaults creates services with default configuration
  64. func initializeWithDefaults(ctx context.Context) error {
  65. logger.Info("Initializing services with default configuration")
  66. // Create empty searcher (will be populated when indexes are available)
  67. searcherConfig := searcher.DefaultSearcherConfig()
  68. globalSearcher = searcher.NewDistributedSearcher(searcherConfig, []bleve.Index{})
  69. // Initialize analytics with empty searcher
  70. globalAnalytics = analytics.NewService(globalSearcher)
  71. // Initialize parallel indexer with shard manager
  72. indexerConfig := indexer.DefaultIndexerConfig()
  73. // Use config directory for index path
  74. indexerConfig.IndexPath = getConfigDirIndexPath()
  75. shardManager := indexer.NewDefaultShardManager(indexerConfig)
  76. globalIndexer = indexer.NewParallelIndexer(indexerConfig, shardManager)
  77. // Start the indexer
  78. if err := globalIndexer.Start(ctx); err != nil {
  79. logger.Errorf("Failed to start parallel indexer: %v", err)
  80. return fmt.Errorf("failed to start parallel indexer: %w", err)
  81. }
  82. // Initialize log file manager
  83. globalLogFileManager = indexer.NewLogFileManager()
  84. servicesInitialized = true
  85. // After all services are initialized, update the searcher with any existing shards.
  86. // This is crucial for loading the index state on application startup.
  87. // We call the 'locked' version because we already hold the mutex here.
  88. updateSearcherShardsLocked()
  89. return nil
  90. }
  91. // getConfigDirIndexPath returns the index path relative to the config file directory
  92. func getConfigDirIndexPath() string {
  93. // Get the config file path from cosy settings
  94. if cSettings.ConfPath != "" {
  95. configDir := filepath.Dir(cSettings.ConfPath)
  96. indexPath := filepath.Join(configDir, "log-index")
  97. // Ensure the directory exists
  98. if err := os.MkdirAll(indexPath, 0755); err != nil {
  99. logger.Warnf("Failed to create index directory at %s: %v, using default", indexPath, err)
  100. return "./log-index"
  101. }
  102. return indexPath
  103. }
  104. // Fallback to default relative path
  105. logger.Warn("Config file path not available, using default index path")
  106. return "./log-index"
  107. }
  108. // GetModernSearcher returns the global searcher instance
  109. func GetModernSearcher() searcher.Searcher {
  110. servicesMutex.RLock()
  111. defer servicesMutex.RUnlock()
  112. if !servicesInitialized {
  113. logger.Warn("Modern services not initialized, returning nil")
  114. return nil
  115. }
  116. return globalSearcher
  117. }
  118. // GetModernAnalytics returns the global analytics service instance
  119. func GetModernAnalytics() analytics.Service {
  120. servicesMutex.RLock()
  121. defer servicesMutex.RUnlock()
  122. if !servicesInitialized {
  123. logger.Warn("Modern services not initialized, returning nil")
  124. return nil
  125. }
  126. return globalAnalytics
  127. }
  128. // GetModernIndexer returns the global indexer instance
  129. func GetModernIndexer() *indexer.ParallelIndexer {
  130. servicesMutex.RLock()
  131. defer servicesMutex.RUnlock()
  132. if !servicesInitialized {
  133. logger.Warn("Modern services not initialized, returning nil")
  134. return nil
  135. }
  136. return globalIndexer
  137. }
  138. // GetLogFileManager returns the global log file manager instance
  139. func GetLogFileManager() *indexer.LogFileManager {
  140. servicesMutex.RLock()
  141. defer servicesMutex.RUnlock()
  142. if !servicesInitialized {
  143. // Only warn during actual operations, not during initialization
  144. return nil
  145. }
  146. if globalLogFileManager == nil {
  147. logger.Warnf("[nginx_log] GetLogFileManager: globalLogFileManager is nil even though servicesInitialized=true")
  148. return nil
  149. }
  150. return globalLogFileManager
  151. }
  152. // NginxLogCache Type aliases for backward compatibility
  153. type NginxLogCache = indexer.NginxLogCache
  154. type NginxLogWithIndex = indexer.NginxLogWithIndex
  155. // Constants for backward compatibility
  156. const (
  157. IndexStatusIndexed = indexer.IndexStatusIndexed
  158. IndexStatusIndexing = indexer.IndexStatusIndexing
  159. IndexStatusNotIndexed = indexer.IndexStatusNotIndexed
  160. )
  161. // Legacy compatibility functions for log cache system
  162. // AddLogPath adds a log path to the log cache with the source config file
  163. func AddLogPath(path, logType, name, configFile string) {
  164. manager := GetLogFileManager()
  165. if manager != nil {
  166. manager.AddLogPath(path, logType, name, configFile)
  167. } else {
  168. // Only warn if during initialization (when it might be expected)
  169. // Skip warning during shutdown or restart phases
  170. }
  171. }
  172. // RemoveLogPathsFromConfig removes all log paths associated with a specific config file
  173. func RemoveLogPathsFromConfig(configFile string) {
  174. manager := GetLogFileManager()
  175. if manager != nil {
  176. manager.RemoveLogPathsFromConfig(configFile)
  177. } else {
  178. // Silently skip if manager not available - this is normal during shutdown/restart
  179. }
  180. }
  181. // GetAllLogPaths returns all cached log paths, optionally filtered
  182. func GetAllLogPaths(filters ...func(*NginxLogCache) bool) []*NginxLogCache {
  183. if manager := GetLogFileManager(); manager != nil {
  184. return manager.GetAllLogPaths(filters...)
  185. }
  186. return []*NginxLogCache{}
  187. }
  188. // GetAllLogsWithIndex returns all cached log paths with their index status
  189. func GetAllLogsWithIndex(filters ...func(*NginxLogWithIndex) bool) []*NginxLogWithIndex {
  190. if manager := GetLogFileManager(); manager != nil {
  191. return manager.GetAllLogsWithIndex(filters...)
  192. }
  193. return []*NginxLogWithIndex{}
  194. }
  195. // GetAllLogsWithIndexGrouped returns logs grouped by their base name
  196. func GetAllLogsWithIndexGrouped(filters ...func(*NginxLogWithIndex) bool) []*NginxLogWithIndex {
  197. if manager := GetLogFileManager(); manager != nil {
  198. return manager.GetAllLogsWithIndexGrouped(filters...)
  199. }
  200. return []*NginxLogWithIndex{}
  201. }
  202. // SetIndexingStatus sets the indexing status for a specific file path
  203. func SetIndexingStatus(path string, isIndexing bool) {
  204. if manager := GetLogFileManager(); manager != nil {
  205. manager.SetIndexingStatus(path, isIndexing)
  206. }
  207. }
  208. // GetIndexingFiles returns a list of files currently being indexed
  209. func GetIndexingFiles() []string {
  210. if manager := GetLogFileManager(); manager != nil {
  211. return manager.GetIndexingFiles()
  212. }
  213. return []string{}
  214. }
  215. // UpdateSearcherShards fetches all shards from the indexer and re-creates the searcher.
  216. // This function is safe for concurrent use.
  217. func UpdateSearcherShards() {
  218. servicesMutex.Lock() // Use a write lock as we are modifying a global variable
  219. defer servicesMutex.Unlock()
  220. updateSearcherShardsLocked()
  221. }
  222. // updateSearcherShardsLocked performs the actual update logic assumes the caller holds the lock.
  223. func updateSearcherShardsLocked() {
  224. if !servicesInitialized || globalIndexer == nil {
  225. logger.Warn("Cannot update searcher shards, services not fully initialized.")
  226. return
  227. }
  228. allShards := globalIndexer.GetAllShards()
  229. // Re-create the searcher instance with the latest shards.
  230. // This ensures it reads the most up-to-date index state from disk.
  231. if globalSearcher != nil {
  232. // Stop the old searcher to release any resources
  233. if err := globalSearcher.Stop(); err != nil {
  234. logger.Warnf("Error stopping old searcher: %v", err)
  235. }
  236. }
  237. searcherConfig := searcher.DefaultSearcherConfig() // Or get from existing if config can change
  238. globalSearcher = searcher.NewDistributedSearcher(searcherConfig, allShards)
  239. // Also update the analytics service to use the new searcher instance
  240. globalAnalytics = analytics.NewService(globalSearcher)
  241. if len(allShards) > 0 {
  242. logger.Infof("Searcher re-created with %d shards.", len(allShards))
  243. } else {
  244. logger.Info("Searcher re-created with no shards.")
  245. }
  246. }
  247. // DestroyAllIndexes completely removes all indexed data from disk.
  248. func DestroyAllIndexes() error {
  249. servicesMutex.RLock()
  250. defer servicesMutex.RUnlock()
  251. if !servicesInitialized || globalIndexer == nil {
  252. logger.Warn("Cannot destroy indexes, services not initialized.")
  253. return fmt.Errorf("services not initialized")
  254. }
  255. return globalIndexer.DestroyAllIndexes()
  256. }