modern_services.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. if globalSearcher == nil {
  117. logger.Warn("GetModernSearcher: globalSearcher is nil even though services are initialized")
  118. return nil
  119. }
  120. // Check searcher health status
  121. isHealthy := globalSearcher.IsHealthy()
  122. isRunning := globalSearcher.IsRunning()
  123. logger.Debugf("GetModernSearcher: returning searcher, isHealthy: %v, isRunning: %v", isHealthy, isRunning)
  124. return globalSearcher
  125. }
  126. // GetModernAnalytics returns the global analytics service instance
  127. func GetModernAnalytics() analytics.Service {
  128. servicesMutex.RLock()
  129. defer servicesMutex.RUnlock()
  130. if !servicesInitialized {
  131. logger.Warn("Modern services not initialized, returning nil")
  132. return nil
  133. }
  134. return globalAnalytics
  135. }
  136. // GetModernIndexer returns the global indexer instance
  137. func GetModernIndexer() *indexer.ParallelIndexer {
  138. servicesMutex.RLock()
  139. defer servicesMutex.RUnlock()
  140. if !servicesInitialized {
  141. logger.Warn("Modern services not initialized, returning nil")
  142. return nil
  143. }
  144. return globalIndexer
  145. }
  146. // GetLogFileManager returns the global log file manager instance
  147. func GetLogFileManager() *indexer.LogFileManager {
  148. servicesMutex.RLock()
  149. defer servicesMutex.RUnlock()
  150. if !servicesInitialized {
  151. // Only warn during actual operations, not during initialization
  152. return nil
  153. }
  154. if globalLogFileManager == nil {
  155. logger.Warnf("[nginx_log] GetLogFileManager: globalLogFileManager is nil even though servicesInitialized=true")
  156. return nil
  157. }
  158. return globalLogFileManager
  159. }
  160. // NginxLogCache Type aliases for backward compatibility
  161. type NginxLogCache = indexer.NginxLogCache
  162. type NginxLogWithIndex = indexer.NginxLogWithIndex
  163. // Constants for backward compatibility
  164. const (
  165. IndexStatusIndexed = indexer.IndexStatusIndexed
  166. IndexStatusIndexing = indexer.IndexStatusIndexing
  167. IndexStatusNotIndexed = indexer.IndexStatusNotIndexed
  168. )
  169. // Legacy compatibility functions for log cache system
  170. // AddLogPath adds a log path to the log cache with the source config file
  171. func AddLogPath(path, logType, name, configFile string) {
  172. manager := GetLogFileManager()
  173. if manager != nil {
  174. manager.AddLogPath(path, logType, name, configFile)
  175. } else {
  176. // Only warn if during initialization (when it might be expected)
  177. // Skip warning during shutdown or restart phases
  178. }
  179. }
  180. // RemoveLogPathsFromConfig removes all log paths associated with a specific config file
  181. func RemoveLogPathsFromConfig(configFile string) {
  182. manager := GetLogFileManager()
  183. if manager != nil {
  184. manager.RemoveLogPathsFromConfig(configFile)
  185. } else {
  186. // Silently skip if manager not available - this is normal during shutdown/restart
  187. }
  188. }
  189. // GetAllLogPaths returns all cached log paths, optionally filtered
  190. func GetAllLogPaths(filters ...func(*NginxLogCache) bool) []*NginxLogCache {
  191. if manager := GetLogFileManager(); manager != nil {
  192. return manager.GetAllLogPaths(filters...)
  193. }
  194. return []*NginxLogCache{}
  195. }
  196. // GetAllLogsWithIndex returns all cached log paths with their index status
  197. func GetAllLogsWithIndex(filters ...func(*NginxLogWithIndex) bool) []*NginxLogWithIndex {
  198. if manager := GetLogFileManager(); manager != nil {
  199. return manager.GetAllLogsWithIndex(filters...)
  200. }
  201. return []*NginxLogWithIndex{}
  202. }
  203. // GetAllLogsWithIndexGrouped returns logs grouped by their base name
  204. func GetAllLogsWithIndexGrouped(filters ...func(*NginxLogWithIndex) bool) []*NginxLogWithIndex {
  205. if manager := GetLogFileManager(); manager != nil {
  206. return manager.GetAllLogsWithIndexGrouped(filters...)
  207. }
  208. return []*NginxLogWithIndex{}
  209. }
  210. // SetIndexingStatus sets the indexing status for a specific file path
  211. func SetIndexingStatus(path string, isIndexing bool) {
  212. if manager := GetLogFileManager(); manager != nil {
  213. manager.SetIndexingStatus(path, isIndexing)
  214. }
  215. }
  216. // GetIndexingFiles returns a list of files currently being indexed
  217. func GetIndexingFiles() []string {
  218. if manager := GetLogFileManager(); manager != nil {
  219. return manager.GetIndexingFiles()
  220. }
  221. return []string{}
  222. }
  223. // UpdateSearcherShards fetches all shards from the indexer and performs zero-downtime shard updates.
  224. // Uses Bleve IndexAlias.Swap() for atomic shard replacement without recreating the searcher.
  225. // This function is safe for concurrent use and maintains service availability during index rebuilds.
  226. func UpdateSearcherShards() {
  227. servicesMutex.Lock() // Use a write lock as we are modifying a global variable
  228. defer servicesMutex.Unlock()
  229. updateSearcherShardsLocked()
  230. }
  231. // updateSearcherShardsLocked performs the actual update logic assumes the caller holds the lock.
  232. // Uses Bleve IndexAlias.Swap() for zero-downtime shard updates following official best practices.
  233. func updateSearcherShardsLocked() {
  234. if !servicesInitialized || globalIndexer == nil {
  235. logger.Warn("Cannot update searcher shards, services not fully initialized.")
  236. return
  237. }
  238. // Check if indexer is healthy before getting shards
  239. if !globalIndexer.IsHealthy() {
  240. logger.Warn("Cannot update searcher shards, indexer is not healthy")
  241. return
  242. }
  243. newShards := globalIndexer.GetAllShards()
  244. logger.Infof("Retrieved %d new shards from indexer for hot-swap update", len(newShards))
  245. // If no searcher exists yet, create the initial one (first time setup)
  246. if globalSearcher == nil {
  247. logger.Info("Creating initial searcher with IndexAlias")
  248. searcherConfig := searcher.DefaultSearcherConfig()
  249. globalSearcher = searcher.NewDistributedSearcher(searcherConfig, newShards)
  250. if globalSearcher == nil {
  251. logger.Error("Failed to create initial searcher instance")
  252. return
  253. }
  254. // Create analytics service with the initial searcher
  255. globalAnalytics = analytics.NewService(globalSearcher)
  256. isHealthy := globalSearcher.IsHealthy()
  257. isRunning := globalSearcher.IsRunning()
  258. logger.Infof("Initial searcher created successfully, isHealthy: %v, isRunning: %v", isHealthy, isRunning)
  259. return
  260. }
  261. // For subsequent updates, use hot-swap through IndexAlias
  262. // This follows Bleve best practices for zero-downtime index updates
  263. if ds, ok := globalSearcher.(*searcher.DistributedSearcher); ok {
  264. oldShards := ds.GetShards()
  265. // Perform atomic shard swap using IndexAlias
  266. if err := ds.SwapShards(newShards); err != nil {
  267. logger.Errorf("Failed to swap shards atomically: %v", err)
  268. return
  269. }
  270. logger.Infof("Successfully swapped %d old shards with %d new shards using IndexAlias",
  271. len(oldShards), len(newShards))
  272. // Verify searcher health after swap
  273. isHealthy := globalSearcher.IsHealthy()
  274. isRunning := globalSearcher.IsRunning()
  275. logger.Infof("Post-swap searcher status: isHealthy: %v, isRunning: %v", isHealthy, isRunning)
  276. // Note: We do NOT recreate the analytics service here since the searcher interface remains the same
  277. // The CardinalityCounter will automatically use the new shards through the same IndexAlias
  278. } else {
  279. logger.Warn("globalSearcher is not a DistributedSearcher, cannot perform hot-swap")
  280. }
  281. }
  282. // DestroyAllIndexes completely removes all indexed data from disk.
  283. func DestroyAllIndexes(ctx context.Context) error {
  284. servicesMutex.RLock()
  285. defer servicesMutex.RUnlock()
  286. if !servicesInitialized || globalIndexer == nil {
  287. logger.Warn("Cannot destroy indexes, services not initialized.")
  288. return fmt.Errorf("services not initialized")
  289. }
  290. return globalIndexer.DestroyAllIndexes(ctx)
  291. }