modern_services.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. package nginx_log
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "regexp"
  8. "sort"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "github.com/0xJacky/Nginx-UI/internal/nginx_log/analytics"
  14. "github.com/0xJacky/Nginx-UI/internal/nginx_log/indexer"
  15. "github.com/0xJacky/Nginx-UI/internal/nginx_log/searcher"
  16. "github.com/0xJacky/Nginx-UI/settings"
  17. "github.com/blevesearch/bleve/v2"
  18. "github.com/uozi-tech/cosy/logger"
  19. cSettings "github.com/uozi-tech/cosy/settings"
  20. )
  21. // Global instances for new services
  22. var (
  23. globalSearcher *searcher.Searcher
  24. globalAnalytics analytics.Service
  25. globalIndexer *indexer.ParallelIndexer
  26. globalLogFileManager *indexer.LogFileManager
  27. servicesInitialized bool
  28. servicesMutex sync.RWMutex
  29. shutdownCancel context.CancelFunc
  30. isShuttingDown bool
  31. lastShardUpdateAttempt int64
  32. )
  33. // Fallback storage when IndexingEnabled is disabled
  34. var (
  35. fallbackCache = make(map[string]*NginxLogCache)
  36. fallbackCacheMutex sync.RWMutex
  37. )
  38. // InitializeServices initializes the new modular services
  39. func InitializeServices(ctx context.Context) {
  40. servicesMutex.Lock()
  41. defer servicesMutex.Unlock()
  42. // Check if indexing is enabled
  43. if !settings.NginxLogSettings.IndexingEnabled {
  44. logger.Info("Indexing is disabled, skipping nginx_log services initialization")
  45. return
  46. }
  47. if servicesInitialized {
  48. logger.Info("Modern nginx log services already initialized, skipping")
  49. return
  50. }
  51. logger.Info("Initializing modern nginx log services...")
  52. // Create a cancellable context for services
  53. serviceCtx, cancel := context.WithCancel(ctx)
  54. shutdownCancel = cancel
  55. // Initialize with default configuration directly
  56. if err := initializeWithDefaults(serviceCtx); err != nil {
  57. logger.Errorf("Failed to initialize modern services: %v", err)
  58. return
  59. }
  60. logger.Info("Modern nginx log services initialization completed")
  61. // Initialize task scheduler after services are ready
  62. go InitTaskScheduler(serviceCtx)
  63. // Monitor context for shutdown
  64. go func() {
  65. logger.Info("Started nginx_log shutdown monitor goroutine")
  66. <-serviceCtx.Done()
  67. logger.Info("Context cancelled, initiating shutdown...")
  68. // Use the same shutdown logic as manual stop
  69. StopServices()
  70. logger.Info("Nginx_log shutdown monitor goroutine completed")
  71. }()
  72. }
  73. // initializeWithDefaults creates services with default configuration
  74. func initializeWithDefaults(ctx context.Context) error {
  75. logger.Info("Initializing services with default configuration")
  76. // Initialize global log parser singleton before starting indexer/searcher
  77. indexer.InitLogParser()
  78. // Create empty searcher (will be populated when indexes are available)
  79. searcherConfig := searcher.DefaultSearcherConfig()
  80. globalSearcher = searcher.NewSearcher(searcherConfig, []bleve.Index{})
  81. // Initialize analytics with empty searcher
  82. globalAnalytics = analytics.NewService(globalSearcher)
  83. // Initialize parallel indexer with shard manager
  84. indexerConfig := indexer.DefaultIndexerConfig()
  85. // Use config directory for index path
  86. indexerConfig.IndexPath = getConfigDirIndexPath()
  87. shardManager := indexer.NewGroupedShardManager(indexerConfig)
  88. globalIndexer = indexer.NewParallelIndexer(indexerConfig, shardManager)
  89. // Start the indexer
  90. if err := globalIndexer.Start(ctx); err != nil {
  91. logger.Errorf("Failed to start parallel indexer: %v", err)
  92. return fmt.Errorf("failed to start parallel indexer: %w", err)
  93. }
  94. // Initialize log file manager
  95. globalLogFileManager = indexer.NewLogFileManager()
  96. // Inject indexer for precise doc counting before persisting
  97. globalLogFileManager.SetIndexer(globalIndexer)
  98. servicesInitialized = true
  99. // After all services are initialized, update the searcher with any existing shards.
  100. // This is crucial for loading the index state on application startup.
  101. // We call the 'locked' version because we already hold the mutex here.
  102. updateSearcherShardsLocked()
  103. return nil
  104. }
  105. // getConfigDirIndexPath returns the index path relative to the config file directory
  106. func getConfigDirIndexPath() string {
  107. // Use custom path if configured
  108. if settings.NginxLogSettings.IndexPath != "" {
  109. indexPath := settings.NginxLogSettings.IndexPath
  110. // Ensure the directory exists
  111. if err := os.MkdirAll(indexPath, 0755); err != nil {
  112. logger.Warnf("Failed to create custom index directory at %s: %v, using default", indexPath, err)
  113. } else {
  114. logger.Infof("Using custom index path: %s", indexPath)
  115. return indexPath
  116. }
  117. }
  118. // Get the config file path from cosy settings
  119. if cSettings.ConfPath != "" {
  120. configDir := filepath.Dir(cSettings.ConfPath)
  121. indexPath := filepath.Join(configDir, "log-index")
  122. // Ensure the directory exists
  123. if err := os.MkdirAll(indexPath, 0755); err != nil {
  124. logger.Warnf("Failed to create index directory at %s: %v, using default", indexPath, err)
  125. return "./log-index"
  126. }
  127. return indexPath
  128. }
  129. // Fallback to default relative path
  130. logger.Warn("Config file path not available, using default index path")
  131. return "./log-index"
  132. }
  133. // GetSearcher returns the global searcher instance
  134. func GetSearcher() *searcher.Searcher {
  135. servicesMutex.RLock()
  136. defer servicesMutex.RUnlock()
  137. if !servicesInitialized {
  138. logger.Warn("Modern services not initialized, returning nil")
  139. return nil
  140. }
  141. if globalSearcher == nil {
  142. logger.Warn("GetSearcher: globalSearcher is nil even though services are initialized")
  143. return nil
  144. }
  145. // Check searcher health status
  146. isHealthy := globalSearcher.IsHealthy()
  147. isRunning := globalSearcher.IsRunning()
  148. logger.Debugf("GetSearcher: returning searcher, isHealthy: %v, isRunning: %v", isHealthy, isRunning)
  149. // Auto-heal: if the searcher is running but unhealthy (likely zero shards),
  150. // and the indexer is initialized, trigger an async shard swap (throttled).
  151. if !isHealthy && isRunning && globalIndexer != nil {
  152. now := time.Now().UnixNano()
  153. prev := atomic.LoadInt64(&lastShardUpdateAttempt)
  154. if now-prev > int64(5*time.Second) {
  155. if atomic.CompareAndSwapInt64(&lastShardUpdateAttempt, prev, now) {
  156. logger.Debugf("GetSearcher: unhealthy detected, scheduling UpdateSearcherShards()")
  157. go UpdateSearcherShards()
  158. }
  159. }
  160. }
  161. return globalSearcher
  162. }
  163. // GetAnalytics returns the global analytics service instance
  164. func GetAnalytics() analytics.Service {
  165. servicesMutex.RLock()
  166. defer servicesMutex.RUnlock()
  167. if !servicesInitialized {
  168. logger.Warn("Modern services not initialized, returning nil")
  169. return nil
  170. }
  171. return globalAnalytics
  172. }
  173. // GetIndexer returns the global indexer instance
  174. func GetIndexer() *indexer.ParallelIndexer {
  175. servicesMutex.RLock()
  176. defer servicesMutex.RUnlock()
  177. if !servicesInitialized {
  178. return nil
  179. }
  180. return globalIndexer
  181. }
  182. // GetLogFileManager returns the global log file manager instance
  183. func GetLogFileManager() *indexer.LogFileManager {
  184. servicesMutex.RLock()
  185. defer servicesMutex.RUnlock()
  186. if !servicesInitialized {
  187. // Only warn during actual operations, not during initialization
  188. return nil
  189. }
  190. if globalLogFileManager == nil {
  191. logger.Warnf("[nginx_log] GetLogFileManager: globalLogFileManager is nil even though servicesInitialized=true")
  192. return nil
  193. }
  194. return globalLogFileManager
  195. }
  196. // NginxLogCache Type aliases for backward compatibility
  197. type NginxLogCache = indexer.NginxLogCache
  198. type NginxLogWithIndex = indexer.NginxLogWithIndex
  199. // Constants for backward compatibility
  200. const (
  201. IndexStatusIndexed = string(indexer.IndexStatusIndexed)
  202. IndexStatusIndexing = string(indexer.IndexStatusIndexing)
  203. IndexStatusNotIndexed = string(indexer.IndexStatusNotIndexed)
  204. )
  205. // Legacy compatibility functions for log cache system
  206. // AddLogPath adds a log path to the log cache with the source config file
  207. func AddLogPath(path, logType, name, configFile string) {
  208. if manager := GetLogFileManager(); manager != nil {
  209. manager.AddLogPath(path, logType, name, configFile)
  210. return
  211. }
  212. // Fallback storage
  213. fallbackCacheMutex.Lock()
  214. fallbackCache[path] = &NginxLogCache{
  215. Path: path,
  216. Type: logType,
  217. Name: name,
  218. ConfigFile: configFile,
  219. }
  220. fallbackCacheMutex.Unlock()
  221. }
  222. // RemoveLogPathsFromConfig removes all log paths associated with a specific config file
  223. func RemoveLogPathsFromConfig(configFile string) {
  224. if manager := GetLogFileManager(); manager != nil {
  225. manager.RemoveLogPathsFromConfig(configFile)
  226. return
  227. }
  228. // Fallback removal
  229. fallbackCacheMutex.Lock()
  230. for p, entry := range fallbackCache {
  231. if entry.ConfigFile == configFile {
  232. delete(fallbackCache, p)
  233. }
  234. }
  235. fallbackCacheMutex.Unlock()
  236. }
  237. // GetAllLogPaths returns all cached log paths, optionally filtered
  238. func GetAllLogPaths(filters ...func(*NginxLogCache) bool) []*NginxLogCache {
  239. if manager := GetLogFileManager(); manager != nil {
  240. return manager.GetAllLogPaths(filters...)
  241. }
  242. // Fallback list
  243. fallbackCacheMutex.RLock()
  244. defer fallbackCacheMutex.RUnlock()
  245. var logs []*NginxLogCache
  246. for _, entry := range fallbackCache {
  247. include := true
  248. for _, f := range filters {
  249. if !f(entry) {
  250. include = false
  251. break
  252. }
  253. }
  254. if include {
  255. // Create a copy to avoid external mutation
  256. e := *entry
  257. logs = append(logs, &e)
  258. }
  259. }
  260. return logs
  261. }
  262. // GetAllLogsWithIndex returns all cached log paths with their index status
  263. func GetAllLogsWithIndex(filters ...func(*NginxLogWithIndex) bool) []*NginxLogWithIndex {
  264. if manager := GetLogFileManager(); manager != nil {
  265. return manager.GetAllLogsWithIndex(filters...)
  266. }
  267. // Fallback: produce basic entries without indexing metadata
  268. fallbackCacheMutex.RLock()
  269. defer fallbackCacheMutex.RUnlock()
  270. result := make([]*NginxLogWithIndex, 0, len(fallbackCache))
  271. for _, c := range fallbackCache {
  272. lw := &NginxLogWithIndex{
  273. Path: c.Path,
  274. Type: c.Type,
  275. Name: c.Name,
  276. ConfigFile: c.ConfigFile,
  277. IndexStatus: IndexStatusNotIndexed,
  278. }
  279. include := true
  280. for _, f := range filters {
  281. if !f(lw) {
  282. include = false
  283. break
  284. }
  285. }
  286. if include {
  287. result = append(result, lw)
  288. }
  289. }
  290. return result
  291. }
  292. // GetAllLogsWithIndexGrouped returns logs grouped by their base name
  293. func GetAllLogsWithIndexGrouped(filters ...func(*NginxLogWithIndex) bool) []*NginxLogWithIndex {
  294. if manager := GetLogFileManager(); manager != nil {
  295. return manager.GetAllLogsWithIndexGrouped(filters...)
  296. }
  297. // Fallback grouping by base log name (handle simple rotation patterns)
  298. fallbackCacheMutex.RLock()
  299. defer fallbackCacheMutex.RUnlock()
  300. grouped := make(map[string]*NginxLogWithIndex)
  301. for _, c := range fallbackCache {
  302. base := getBaseLogNameBasic(c.Path)
  303. if existing, ok := grouped[base]; ok {
  304. // Preserve most recent non-indexed default; nothing to aggregate in basic mode
  305. _ = existing
  306. continue
  307. }
  308. grouped[base] = &NginxLogWithIndex{
  309. Path: base,
  310. Type: c.Type,
  311. Name: filepath.Base(base),
  312. ConfigFile: c.ConfigFile,
  313. IndexStatus: IndexStatusNotIndexed,
  314. }
  315. }
  316. // Build slice and apply filters
  317. keys := make([]string, 0, len(grouped))
  318. for k := range grouped {
  319. keys = append(keys, k)
  320. }
  321. sort.Strings(keys)
  322. result := make([]*NginxLogWithIndex, 0, len(keys))
  323. for _, k := range keys {
  324. v := grouped[k]
  325. include := true
  326. for _, f := range filters {
  327. if !f(v) {
  328. include = false
  329. break
  330. }
  331. }
  332. if include {
  333. result = append(result, v)
  334. }
  335. }
  336. return result
  337. }
  338. // --- Fallback helpers ---
  339. // getBaseLogNameBasic attempts to derive the base log file for a rotated file name.
  340. // Mirrors the logic used by the indexer, simplified for basic mode.
  341. func getBaseLogNameBasic(filePath string) string {
  342. dir := filepath.Dir(filePath)
  343. filename := filepath.Base(filePath)
  344. // Remove compression extensions
  345. for _, ext := range []string{".gz", ".bz2", ".xz", ".lz4"} {
  346. filename = strings.TrimSuffix(filename, ext)
  347. }
  348. // Check YYYY.MM.DD at end
  349. parts := strings.Split(filename, ".")
  350. if len(parts) >= 4 {
  351. lastThree := strings.Join(parts[len(parts)-3:], ".")
  352. if matched, _ := regexp.MatchString(`^\d{4}\.\d{2}\.\d{2}$`, lastThree); matched {
  353. base := strings.Join(parts[:len(parts)-3], ".")
  354. return filepath.Join(dir, base)
  355. }
  356. }
  357. // Single-part date suffix (YYYYMMDD / YYYY-MM-DD / YYMMDD)
  358. if len(parts) >= 2 {
  359. last := parts[len(parts)-1]
  360. if isFullDatePatternBasic(last) {
  361. base := strings.Join(parts[:len(parts)-1], ".")
  362. return filepath.Join(dir, base)
  363. }
  364. }
  365. // Numbered rotation: access.log.1
  366. if m := regexp.MustCompile(`^(.+)\.(\d{1,3})$`).FindStringSubmatch(filename); len(m) > 1 {
  367. base := m[1]
  368. return filepath.Join(dir, base)
  369. }
  370. // Middle-numbered rotation: access.1.log
  371. if m := regexp.MustCompile(`^(.+)\.(\d{1,3})\.log$`).FindStringSubmatch(filename); len(m) > 1 {
  372. base := m[1] + ".log"
  373. return filepath.Join(dir, base)
  374. }
  375. // Fallback: return original path
  376. return filePath
  377. }
  378. func isFullDatePatternBasic(s string) bool {
  379. patterns := []string{
  380. `^\d{8}$`, // YYYYMMDD
  381. `^\d{4}-\d{2}-\d{2}$`, // YYYY-MM-DD
  382. `^\d{6}$`, // YYMMDD
  383. }
  384. for _, p := range patterns {
  385. if matched, _ := regexp.MatchString(p, s); matched {
  386. return true
  387. }
  388. }
  389. return false
  390. }
  391. // SetIndexingStatus sets the indexing status for a specific file path
  392. func SetIndexingStatus(path string, isIndexing bool) {
  393. if manager := GetLogFileManager(); manager != nil {
  394. manager.SetIndexingStatus(path, isIndexing)
  395. }
  396. }
  397. // GetIndexingFiles returns a list of files currently being indexed
  398. func GetIndexingFiles() []string {
  399. if manager := GetLogFileManager(); manager != nil {
  400. return manager.GetIndexingFiles()
  401. }
  402. return []string{}
  403. }
  404. // UpdateSearcherShards fetches all shards from the indexer and performs zero-downtime shard updates.
  405. // Uses Bleve IndexAlias.Swap() for atomic shard replacement without recreating the searcher.
  406. // This function is safe for concurrent use and maintains service availability during index rebuilds.
  407. func UpdateSearcherShards() {
  408. // Schedule async update to avoid blocking indexing operations
  409. logger.Debugf("UpdateSearcherShards: Scheduling async shard update")
  410. go updateSearcherShardsAsync()
  411. }
  412. // updateSearcherShardsAsync performs the actual shard update asynchronously
  413. func updateSearcherShardsAsync() {
  414. // Small delay to let indexing operations complete
  415. time.Sleep(500 * time.Millisecond)
  416. logger.Debugf("updateSearcherShardsAsync: Attempting to acquire write lock...")
  417. servicesMutex.Lock()
  418. logger.Debugf("updateSearcherShardsAsync: Write lock acquired")
  419. defer func() {
  420. logger.Debugf("updateSearcherShardsAsync: Releasing write lock...")
  421. servicesMutex.Unlock()
  422. }()
  423. updateSearcherShardsLocked()
  424. }
  425. // updateSearcherShardsLocked performs the actual update logic assumes the caller holds the lock.
  426. // Uses Bleve IndexAlias.Swap() for zero-downtime shard updates following official best practices.
  427. func updateSearcherShardsLocked() {
  428. if !servicesInitialized || globalIndexer == nil {
  429. logger.Warn("Cannot update searcher shards, services not fully initialized.")
  430. return
  431. }
  432. // Check if indexer is healthy before getting shards
  433. if !globalIndexer.IsHealthy() {
  434. logger.Warn("Cannot update searcher shards, indexer is not healthy")
  435. return
  436. }
  437. newShards := globalIndexer.GetAllShards()
  438. logger.Infof("Retrieved %d new shards from indexer for hot-swap update", len(newShards))
  439. // If no searcher exists yet, create the initial one (first time setup)
  440. if globalSearcher == nil {
  441. logger.Info("Creating initial searcher with IndexAlias")
  442. searcherConfig := searcher.DefaultSearcherConfig()
  443. globalSearcher = searcher.NewSearcher(searcherConfig, newShards)
  444. if globalSearcher == nil {
  445. logger.Error("Failed to create initial searcher instance")
  446. return
  447. }
  448. // Create analytics service with the initial searcher
  449. globalAnalytics = analytics.NewService(globalSearcher)
  450. isHealthy := globalSearcher.IsHealthy()
  451. isRunning := globalSearcher.IsRunning()
  452. logger.Infof("Initial searcher created successfully, isHealthy: %v, isRunning: %v", isHealthy, isRunning)
  453. return
  454. }
  455. // For subsequent updates, use hot-swap through IndexAlias
  456. // This follows Bleve best practices for zero-downtime index updates
  457. if globalSearcher != nil {
  458. ds := globalSearcher
  459. oldShards := ds.GetShards()
  460. logger.Debugf("updateSearcherShardsLocked: About to call SwapShards...")
  461. // Perform atomic shard swap using IndexAlias
  462. if err := ds.SwapShards(newShards); err != nil {
  463. logger.Errorf("Failed to swap shards atomically: %v", err)
  464. return
  465. }
  466. logger.Debugf("updateSearcherShardsLocked: SwapShards completed successfully")
  467. logger.Infof("Successfully swapped %d old shards with %d new shards using IndexAlias",
  468. len(oldShards), len(newShards))
  469. // Verify searcher health after swap
  470. isHealthy := globalSearcher.IsHealthy()
  471. isRunning := globalSearcher.IsRunning()
  472. logger.Infof("Post-swap searcher status: isHealthy: %v, isRunning: %v", isHealthy, isRunning)
  473. // Note: We do NOT recreate the analytics service here since the searcher interface remains the same
  474. // The Counter will automatically use the new shards through the same IndexAlias
  475. } else {
  476. logger.Warn("globalSearcher is not a Searcher, cannot perform hot-swap")
  477. }
  478. }
  479. // StopServices stops all running modern services
  480. func StopServices() {
  481. servicesMutex.Lock()
  482. defer servicesMutex.Unlock()
  483. if !servicesInitialized {
  484. logger.Debug("Modern nginx log services not initialized, nothing to stop")
  485. return
  486. }
  487. if isShuttingDown {
  488. logger.Debug("Modern nginx log services already shutting down")
  489. return
  490. }
  491. logger.Debug("Stopping modern nginx log services...")
  492. isShuttingDown = true
  493. // Cancel the service context to trigger graceful shutdown
  494. if shutdownCancel != nil {
  495. shutdownCancel()
  496. // Wait a bit for graceful shutdown
  497. time.Sleep(500 * time.Millisecond)
  498. }
  499. // Stop all services
  500. if globalIndexer != nil {
  501. if err := globalIndexer.Stop(); err != nil {
  502. logger.Errorf("Failed to stop indexer: %v", err)
  503. }
  504. globalIndexer = nil
  505. }
  506. if globalAnalytics != nil {
  507. if err := globalAnalytics.Stop(); err != nil {
  508. logger.Errorf("Failed to stop analytics service: %v", err)
  509. }
  510. globalAnalytics = nil
  511. }
  512. if globalSearcher != nil {
  513. if err := globalSearcher.Stop(); err != nil {
  514. logger.Errorf("Failed to stop searcher: %v", err)
  515. }
  516. globalSearcher = nil
  517. }
  518. // Reset state
  519. globalLogFileManager = nil
  520. servicesInitialized = false
  521. shutdownCancel = nil
  522. isShuttingDown = false
  523. logger.Debug("Modern nginx log services stopped")
  524. }
  525. // DestroyAllIndexes completely removes all indexed data from disk.
  526. func DestroyAllIndexes(ctx context.Context) error {
  527. servicesMutex.RLock()
  528. defer servicesMutex.RUnlock()
  529. if !servicesInitialized || globalIndexer == nil {
  530. logger.Debug("Cannot destroy indexes, services not initialized.")
  531. return fmt.Errorf("services not initialized")
  532. }
  533. return globalIndexer.DestroyAllIndexes(ctx)
  534. }
  535. // MigrateFallbackCache migrates all entries from fallback cache to LogFileManager
  536. // This is used when enabling advanced indexing after the application has started
  537. func MigrateFallbackCache() {
  538. fallbackCacheMutex.RLock()
  539. entries := make([]*NginxLogCache, 0, len(fallbackCache))
  540. for _, entry := range fallbackCache {
  541. // Create a copy to avoid race conditions
  542. e := *entry
  543. entries = append(entries, &e)
  544. }
  545. fallbackCacheMutex.RUnlock()
  546. if len(entries) == 0 {
  547. logger.Debug("No fallback cache entries to migrate")
  548. return
  549. }
  550. manager := GetLogFileManager()
  551. if manager == nil {
  552. logger.Warn("Cannot migrate fallback cache: LogFileManager not initialized")
  553. return
  554. }
  555. logger.Infof("Migrating %d log paths from fallback cache to LogFileManager", len(entries))
  556. for _, entry := range entries {
  557. manager.AddLogPath(entry.Path, entry.Type, entry.Name, entry.ConfigFile)
  558. }
  559. // Clear fallback cache after successful migration
  560. fallbackCacheMutex.Lock()
  561. fallbackCache = make(map[string]*NginxLogCache)
  562. fallbackCacheMutex.Unlock()
  563. logger.Info("Fallback cache migration completed successfully")
  564. }