modern_services.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. package nginx_log
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "sync"
  8. "time"
  9. "github.com/0xJacky/Nginx-UI/internal/nginx_log/analytics"
  10. "github.com/0xJacky/Nginx-UI/internal/nginx_log/indexer"
  11. "github.com/0xJacky/Nginx-UI/internal/nginx_log/searcher"
  12. "github.com/blevesearch/bleve/v2"
  13. "github.com/uozi-tech/cosy/logger"
  14. cSettings "github.com/uozi-tech/cosy/settings"
  15. )
  16. // Global instances for new services
  17. var (
  18. globalSearcher searcher.Searcher
  19. globalAnalytics analytics.Service
  20. globalIndexer *indexer.ParallelIndexer
  21. globalLogFileManager *indexer.LogFileManager
  22. servicesInitialized bool
  23. servicesMutex sync.RWMutex
  24. )
  25. // InitializeModernServices initializes the new modular services
  26. func InitializeModernServices(ctx context.Context) {
  27. servicesMutex.Lock()
  28. defer servicesMutex.Unlock()
  29. if servicesInitialized {
  30. logger.Info("Modern nginx log services already initialized, skipping")
  31. return
  32. }
  33. logger.Info("Initializing modern nginx log services...")
  34. // Initialize with default configuration directly
  35. if err := initializeWithDefaults(ctx); err != nil {
  36. logger.Errorf("Failed to initialize modern services: %v", err)
  37. return
  38. }
  39. logger.Info("Modern nginx log services initialization completed")
  40. // Monitor context for shutdown
  41. go func() {
  42. logger.Info("Started nginx_log shutdown monitor goroutine")
  43. <-ctx.Done()
  44. logger.Info("Shutting down modern nginx log services...")
  45. servicesMutex.Lock()
  46. defer servicesMutex.Unlock()
  47. // Stop services
  48. if globalIndexer != nil {
  49. if err := globalIndexer.Stop(); err != nil {
  50. logger.Errorf("Failed to stop indexer: %v", err)
  51. }
  52. }
  53. // Stop searcher if it exists
  54. if globalSearcher != nil {
  55. if err := globalSearcher.Stop(); err != nil {
  56. logger.Errorf("Failed to stop searcher: %v", err)
  57. }
  58. }
  59. servicesInitialized = false
  60. logger.Info("Modern nginx log services shut down")
  61. logger.Info("Nginx_log shutdown monitor goroutine completed")
  62. }()
  63. }
  64. // initializeWithDefaults creates services with default configuration
  65. func initializeWithDefaults(ctx context.Context) error {
  66. logger.Info("Initializing services with default configuration")
  67. // Create empty searcher (will be populated when indexes are available)
  68. searcherConfig := searcher.DefaultSearcherConfig()
  69. globalSearcher = searcher.NewDistributedSearcher(searcherConfig, []bleve.Index{})
  70. // Initialize analytics with empty searcher
  71. globalAnalytics = analytics.NewService(globalSearcher)
  72. // Initialize parallel indexer with shard manager
  73. indexerConfig := indexer.DefaultIndexerConfig()
  74. // Use config directory for index path
  75. indexerConfig.IndexPath = getConfigDirIndexPath()
  76. shardManager := indexer.NewDefaultShardManager(indexerConfig)
  77. globalIndexer = indexer.NewParallelIndexer(indexerConfig, shardManager)
  78. // Start the indexer
  79. if err := globalIndexer.Start(ctx); err != nil {
  80. logger.Errorf("Failed to start parallel indexer: %v", err)
  81. return fmt.Errorf("failed to start parallel indexer: %w", err)
  82. }
  83. // Initialize log file manager
  84. globalLogFileManager = indexer.NewLogFileManager()
  85. servicesInitialized = true
  86. // After all services are initialized, update the searcher with any existing shards.
  87. // This is crucial for loading the index state on application startup.
  88. // We call the 'locked' version because we already hold the mutex here.
  89. updateSearcherShardsLocked()
  90. return nil
  91. }
  92. // getConfigDirIndexPath returns the index path relative to the config file directory
  93. func getConfigDirIndexPath() string {
  94. // Get the config file path from cosy settings
  95. if cSettings.ConfPath != "" {
  96. configDir := filepath.Dir(cSettings.ConfPath)
  97. indexPath := filepath.Join(configDir, "log-index")
  98. // Ensure the directory exists
  99. if err := os.MkdirAll(indexPath, 0755); err != nil {
  100. logger.Warnf("Failed to create index directory at %s: %v, using default", indexPath, err)
  101. return "./log-index"
  102. }
  103. return indexPath
  104. }
  105. // Fallback to default relative path
  106. logger.Warn("Config file path not available, using default index path")
  107. return "./log-index"
  108. }
  109. // GetModernSearcher returns the global searcher instance
  110. func GetModernSearcher() searcher.Searcher {
  111. servicesMutex.RLock()
  112. defer servicesMutex.RUnlock()
  113. if !servicesInitialized {
  114. logger.Warn("Modern services not initialized, returning nil")
  115. return nil
  116. }
  117. if globalSearcher == nil {
  118. logger.Warn("GetModernSearcher: globalSearcher is nil even though services are initialized")
  119. return nil
  120. }
  121. // Check searcher health status
  122. isHealthy := globalSearcher.IsHealthy()
  123. isRunning := globalSearcher.IsRunning()
  124. logger.Debugf("GetModernSearcher: returning searcher, isHealthy: %v, isRunning: %v", isHealthy, isRunning)
  125. return globalSearcher
  126. }
  127. // GetModernAnalytics returns the global analytics service instance
  128. func GetModernAnalytics() analytics.Service {
  129. servicesMutex.RLock()
  130. defer servicesMutex.RUnlock()
  131. if !servicesInitialized {
  132. logger.Warn("Modern services not initialized, returning nil")
  133. return nil
  134. }
  135. return globalAnalytics
  136. }
  137. // GetModernIndexer returns the global indexer instance
  138. func GetModernIndexer() *indexer.ParallelIndexer {
  139. servicesMutex.RLock()
  140. defer servicesMutex.RUnlock()
  141. if !servicesInitialized {
  142. logger.Warn("Modern services not initialized, returning nil")
  143. return nil
  144. }
  145. return globalIndexer
  146. }
  147. // GetLogFileManager returns the global log file manager instance
  148. func GetLogFileManager() *indexer.LogFileManager {
  149. servicesMutex.RLock()
  150. defer servicesMutex.RUnlock()
  151. if !servicesInitialized {
  152. // Only warn during actual operations, not during initialization
  153. return nil
  154. }
  155. if globalLogFileManager == nil {
  156. logger.Warnf("[nginx_log] GetLogFileManager: globalLogFileManager is nil even though servicesInitialized=true")
  157. return nil
  158. }
  159. return globalLogFileManager
  160. }
  161. // NginxLogCache Type aliases for backward compatibility
  162. type NginxLogCache = indexer.NginxLogCache
  163. type NginxLogWithIndex = indexer.NginxLogWithIndex
  164. // Constants for backward compatibility
  165. const (
  166. IndexStatusIndexed = string(indexer.IndexStatusIndexed)
  167. IndexStatusIndexing = string(indexer.IndexStatusIndexing)
  168. IndexStatusNotIndexed = string(indexer.IndexStatusNotIndexed)
  169. )
  170. // Legacy compatibility functions for log cache system
  171. // AddLogPath adds a log path to the log cache with the source config file
  172. func AddLogPath(path, logType, name, configFile string) {
  173. manager := GetLogFileManager()
  174. if manager != nil {
  175. manager.AddLogPath(path, logType, name, configFile)
  176. } else {
  177. // Only warn if during initialization (when it might be expected)
  178. // Skip warning during shutdown or restart phases
  179. }
  180. }
  181. // RemoveLogPathsFromConfig removes all log paths associated with a specific config file
  182. func RemoveLogPathsFromConfig(configFile string) {
  183. manager := GetLogFileManager()
  184. if manager != nil {
  185. manager.RemoveLogPathsFromConfig(configFile)
  186. } else {
  187. // Silently skip if manager not available - this is normal during shutdown/restart
  188. }
  189. }
  190. // GetAllLogPaths returns all cached log paths, optionally filtered
  191. func GetAllLogPaths(filters ...func(*NginxLogCache) bool) []*NginxLogCache {
  192. if manager := GetLogFileManager(); manager != nil {
  193. return manager.GetAllLogPaths(filters...)
  194. }
  195. return []*NginxLogCache{}
  196. }
  197. // GetAllLogsWithIndex returns all cached log paths with their index status
  198. func GetAllLogsWithIndex(filters ...func(*NginxLogWithIndex) bool) []*NginxLogWithIndex {
  199. if manager := GetLogFileManager(); manager != nil {
  200. return manager.GetAllLogsWithIndex(filters...)
  201. }
  202. return []*NginxLogWithIndex{}
  203. }
  204. // GetAllLogsWithIndexGrouped returns logs grouped by their base name
  205. func GetAllLogsWithIndexGrouped(filters ...func(*NginxLogWithIndex) bool) []*NginxLogWithIndex {
  206. if manager := GetLogFileManager(); manager != nil {
  207. return manager.GetAllLogsWithIndexGrouped(filters...)
  208. }
  209. return []*NginxLogWithIndex{}
  210. }
  211. // SetIndexingStatus sets the indexing status for a specific file path
  212. func SetIndexingStatus(path string, isIndexing bool) {
  213. if manager := GetLogFileManager(); manager != nil {
  214. manager.SetIndexingStatus(path, isIndexing)
  215. }
  216. }
  217. // GetIndexingFiles returns a list of files currently being indexed
  218. func GetIndexingFiles() []string {
  219. if manager := GetLogFileManager(); manager != nil {
  220. return manager.GetIndexingFiles()
  221. }
  222. return []string{}
  223. }
  224. // UpdateSearcherShards fetches all shards from the indexer and performs zero-downtime shard updates.
  225. // Uses Bleve IndexAlias.Swap() for atomic shard replacement without recreating the searcher.
  226. // This function is safe for concurrent use and maintains service availability during index rebuilds.
  227. func UpdateSearcherShards() {
  228. // Schedule async update to avoid blocking indexing operations
  229. logger.Debugf("UpdateSearcherShards: Scheduling async shard update")
  230. go updateSearcherShardsAsync()
  231. }
  232. // updateSearcherShardsAsync performs the actual shard update asynchronously
  233. func updateSearcherShardsAsync() {
  234. // Small delay to let indexing operations complete
  235. time.Sleep(500 * time.Millisecond)
  236. logger.Debugf("updateSearcherShardsAsync: Attempting to acquire write lock...")
  237. servicesMutex.Lock()
  238. logger.Debugf("updateSearcherShardsAsync: Write lock acquired")
  239. defer func() {
  240. logger.Debugf("updateSearcherShardsAsync: Releasing write lock...")
  241. servicesMutex.Unlock()
  242. }()
  243. updateSearcherShardsLocked()
  244. }
  245. // updateSearcherShardsLocked performs the actual update logic assumes the caller holds the lock.
  246. // Uses Bleve IndexAlias.Swap() for zero-downtime shard updates following official best practices.
  247. func updateSearcherShardsLocked() {
  248. if !servicesInitialized || globalIndexer == nil {
  249. logger.Warn("Cannot update searcher shards, services not fully initialized.")
  250. return
  251. }
  252. // Check if indexer is healthy before getting shards
  253. if !globalIndexer.IsHealthy() {
  254. logger.Warn("Cannot update searcher shards, indexer is not healthy")
  255. return
  256. }
  257. newShards := globalIndexer.GetAllShards()
  258. logger.Infof("Retrieved %d new shards from indexer for hot-swap update", len(newShards))
  259. // If no searcher exists yet, create the initial one (first time setup)
  260. if globalSearcher == nil {
  261. logger.Info("Creating initial searcher with IndexAlias")
  262. searcherConfig := searcher.DefaultSearcherConfig()
  263. globalSearcher = searcher.NewDistributedSearcher(searcherConfig, newShards)
  264. if globalSearcher == nil {
  265. logger.Error("Failed to create initial searcher instance")
  266. return
  267. }
  268. // Create analytics service with the initial searcher
  269. globalAnalytics = analytics.NewService(globalSearcher)
  270. isHealthy := globalSearcher.IsHealthy()
  271. isRunning := globalSearcher.IsRunning()
  272. logger.Infof("Initial searcher created successfully, isHealthy: %v, isRunning: %v", isHealthy, isRunning)
  273. return
  274. }
  275. // For subsequent updates, use hot-swap through IndexAlias
  276. // This follows Bleve best practices for zero-downtime index updates
  277. if ds, ok := globalSearcher.(*searcher.DistributedSearcher); ok {
  278. oldShards := ds.GetShards()
  279. logger.Debugf("updateSearcherShardsLocked: About to call SwapShards...")
  280. // Perform atomic shard swap using IndexAlias
  281. if err := ds.SwapShards(newShards); err != nil {
  282. logger.Errorf("Failed to swap shards atomically: %v", err)
  283. return
  284. }
  285. logger.Debugf("updateSearcherShardsLocked: SwapShards completed successfully")
  286. logger.Infof("Successfully swapped %d old shards with %d new shards using IndexAlias",
  287. len(oldShards), len(newShards))
  288. // Verify searcher health after swap
  289. isHealthy := globalSearcher.IsHealthy()
  290. isRunning := globalSearcher.IsRunning()
  291. logger.Infof("Post-swap searcher status: isHealthy: %v, isRunning: %v", isHealthy, isRunning)
  292. // Note: We do NOT recreate the analytics service here since the searcher interface remains the same
  293. // The CardinalityCounter will automatically use the new shards through the same IndexAlias
  294. } else {
  295. logger.Warn("globalSearcher is not a DistributedSearcher, cannot perform hot-swap")
  296. }
  297. }
  298. // DestroyAllIndexes completely removes all indexed data from disk.
  299. func DestroyAllIndexes(ctx context.Context) error {
  300. servicesMutex.RLock()
  301. defer servicesMutex.RUnlock()
  302. if !servicesInitialized || globalIndexer == nil {
  303. logger.Warn("Cannot destroy indexes, services not initialized.")
  304. return fmt.Errorf("services not initialized")
  305. }
  306. return globalIndexer.DestroyAllIndexes(ctx)
  307. }