modern_services.go 8.7 KB

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