modern_services.go 18 KB

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