progress_tracker.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. package nginx_log
  2. import (
  3. "sync"
  4. "time"
  5. "github.com/0xJacky/Nginx-UI/internal/event"
  6. "github.com/uozi-tech/cosy/logger"
  7. )
  8. // ProgressTracker manages progress tracking for log group indexing
  9. type ProgressTracker struct {
  10. mu sync.RWMutex
  11. logGroupPath string
  12. startTime time.Time
  13. files map[string]*FileProgress
  14. totalEstimate int64 // Total estimated lines across all files
  15. totalActual int64 // Total actual lines processed
  16. isCompleted bool
  17. completionNotified bool // Flag to prevent duplicate completion notifications
  18. lastNotify time.Time
  19. }
  20. // FileProgress tracks progress for individual files
  21. type FileProgress struct {
  22. FilePath string
  23. State FileState
  24. EstimatedLines int64 // Estimated total lines in this file
  25. ProcessedLines int64 // Actually processed lines
  26. FileSize int64 // Total file size in bytes (compressed size for .gz files)
  27. CurrentPos int64 // Current reading position in bytes (for uncompressed files only)
  28. AvgLineSize int64 // Dynamic average line size in bytes (for compressed files)
  29. SampleCount int64 // Number of lines sampled for average calculation
  30. IsCompressed bool
  31. StartTime *time.Time
  32. CompletedTime *time.Time
  33. }
  34. // FileState represents the current state of file processing
  35. type FileState int
  36. const (
  37. FileStatePending FileState = iota
  38. FileStateProcessing
  39. FileStateCompleted
  40. )
  41. func (fs FileState) String() string {
  42. switch fs {
  43. case FileStatePending:
  44. return "pending"
  45. case FileStateProcessing:
  46. return "processing"
  47. case FileStateCompleted:
  48. return "completed"
  49. default:
  50. return "unknown"
  51. }
  52. }
  53. // NewProgressTracker creates a new progress tracker for a log group
  54. func NewProgressTracker(logGroupPath string) *ProgressTracker {
  55. return &ProgressTracker{
  56. logGroupPath: logGroupPath,
  57. startTime: time.Now(),
  58. files: make(map[string]*FileProgress),
  59. completionNotified: false,
  60. }
  61. }
  62. // AddFile adds a file to the progress tracker
  63. func (pt *ProgressTracker) AddFile(filePath string, isCompressed bool) {
  64. pt.mu.Lock()
  65. defer pt.mu.Unlock()
  66. pt.files[filePath] = &FileProgress{
  67. FilePath: filePath,
  68. State: FileStatePending,
  69. IsCompressed: isCompressed,
  70. AvgLineSize: 120, // Initial estimate: 120 bytes per line
  71. SampleCount: 0,
  72. }
  73. logger.Debugf("Added file to progress tracker: %s (compressed: %v)", filePath, isCompressed)
  74. }
  75. // SetFileEstimate sets the estimated line count for a file
  76. func (pt *ProgressTracker) SetFileEstimate(filePath string, estimatedLines int64) {
  77. pt.mu.Lock()
  78. defer pt.mu.Unlock()
  79. if progress, exists := pt.files[filePath]; exists {
  80. oldEstimate := progress.EstimatedLines
  81. progress.EstimatedLines = estimatedLines
  82. // Update total estimate
  83. pt.totalEstimate = pt.totalEstimate - oldEstimate + estimatedLines
  84. logger.Debugf("Updated file estimate for %s: %d lines (total estimate: %d)",
  85. filePath, estimatedLines, pt.totalEstimate)
  86. }
  87. }
  88. // SetFileSize sets the file size for a file
  89. func (pt *ProgressTracker) SetFileSize(filePath string, fileSize int64) {
  90. pt.mu.Lock()
  91. defer pt.mu.Unlock()
  92. if progress, exists := pt.files[filePath]; exists {
  93. progress.FileSize = fileSize
  94. logger.Debugf("Set file size for %s: %d bytes", filePath, fileSize)
  95. }
  96. }
  97. // UpdateFilePosition updates the current reading position for files
  98. func (pt *ProgressTracker) UpdateFilePosition(filePath string, currentPos int64, linesProcessed int64) {
  99. pt.mu.Lock()
  100. defer pt.mu.Unlock()
  101. if progress, exists := pt.files[filePath]; exists {
  102. progress.ProcessedLines = linesProcessed
  103. if progress.IsCompressed {
  104. // For compressed files, update average line size dynamically
  105. if linesProcessed > 0 {
  106. // Use the first 1000 lines to establish a good average, then update less frequently
  107. if progress.SampleCount < 1000 || progress.SampleCount%100 == 0 {
  108. // Calculate current average line size based on processed data
  109. // For compressed files, we estimate based on processed lines and compression ratio
  110. estimatedUncompressedBytes := progress.FileSize * 3 // Assume 3:1 compression ratio
  111. newAvgLineSize := estimatedUncompressedBytes / linesProcessed
  112. if newAvgLineSize > 50 && newAvgLineSize < 5000 { // Sanity check: 50-5000 bytes per line
  113. // Smooth the average to avoid sudden jumps
  114. if progress.SampleCount > 0 {
  115. progress.AvgLineSize = (progress.AvgLineSize + newAvgLineSize) / 2
  116. } else {
  117. progress.AvgLineSize = newAvgLineSize
  118. }
  119. }
  120. }
  121. progress.SampleCount = linesProcessed
  122. }
  123. } else {
  124. // For uncompressed files, update current position
  125. progress.CurrentPos = currentPos
  126. }
  127. }
  128. }
  129. // StartFile marks a file as started processing
  130. func (pt *ProgressTracker) StartFile(filePath string) {
  131. pt.mu.Lock()
  132. defer pt.mu.Unlock()
  133. if progress, exists := pt.files[filePath]; exists {
  134. progress.State = FileStateProcessing
  135. now := time.Now()
  136. progress.StartTime = &now
  137. logger.Debugf("Started processing file: %s", filePath)
  138. pt.notifyProgressLocked()
  139. }
  140. }
  141. // UpdateFileProgress updates the processed line count for a file
  142. func (pt *ProgressTracker) UpdateFileProgress(filePath string, processedLines int64) {
  143. pt.mu.Lock()
  144. defer pt.mu.Unlock()
  145. if progress, exists := pt.files[filePath]; exists {
  146. oldProcessed := progress.ProcessedLines
  147. progress.ProcessedLines = processedLines
  148. // Update total actual processed
  149. pt.totalActual = pt.totalActual - oldProcessed + processedLines
  150. // Notify progress if enough time has passed
  151. pt.notifyProgressLocked()
  152. }
  153. }
  154. // CompleteFile marks a file as completed
  155. func (pt *ProgressTracker) CompleteFile(filePath string, finalProcessedLines int64) {
  156. pt.mu.Lock()
  157. defer pt.mu.Unlock()
  158. if progress, exists := pt.files[filePath]; exists {
  159. oldProcessed := progress.ProcessedLines
  160. progress.ProcessedLines = finalProcessedLines
  161. progress.State = FileStateCompleted
  162. now := time.Now()
  163. progress.CompletedTime = &now
  164. // Update total actual processed
  165. pt.totalActual = pt.totalActual - oldProcessed + finalProcessedLines
  166. logger.Debugf("Completed processing file: %s (%d lines)", filePath, finalProcessedLines)
  167. // Check if all files are completed and we haven't notified yet
  168. if !pt.completionNotified {
  169. allCompleted := true
  170. for _, fp := range pt.files {
  171. if fp.State != FileStateCompleted {
  172. allCompleted = false
  173. break
  174. }
  175. }
  176. if allCompleted {
  177. pt.isCompleted = true
  178. pt.completionNotified = true // Mark as notified to prevent duplicates
  179. pt.notifyCompletionLocked()
  180. } else {
  181. pt.notifyProgressLocked()
  182. }
  183. }
  184. }
  185. }
  186. // GetProgress returns the current progress percentage and stats
  187. func (pt *ProgressTracker) GetProgress() (percentage float64, stats ProgressStats) {
  188. pt.mu.RLock()
  189. defer pt.mu.RUnlock()
  190. stats = ProgressStats{
  191. LogGroupPath: pt.logGroupPath,
  192. TotalFiles: len(pt.files),
  193. ProcessedLines: pt.totalActual,
  194. EstimatedLines: pt.totalEstimate,
  195. StartTime: pt.startTime,
  196. IsCompleted: pt.isCompleted,
  197. }
  198. // Count completed files
  199. for _, fp := range pt.files {
  200. switch fp.State {
  201. case FileStateCompleted:
  202. stats.CompletedFiles++
  203. case FileStateProcessing:
  204. stats.ProcessingFiles++
  205. }
  206. }
  207. // Calculate progress percentage
  208. if pt.totalEstimate > 0 {
  209. percentage = float64(pt.totalActual) / float64(pt.totalEstimate) * 100
  210. } else if stats.TotalFiles > 0 {
  211. // Fallback to file-based progress if no line estimates
  212. percentage = float64(stats.CompletedFiles) / float64(stats.TotalFiles) * 100
  213. }
  214. // Cap at 100%
  215. if percentage > 100 {
  216. percentage = 100
  217. }
  218. return percentage, stats
  219. }
  220. // ProgressStats contains progress statistics
  221. type ProgressStats struct {
  222. LogGroupPath string
  223. TotalFiles int
  224. CompletedFiles int
  225. ProcessingFiles int
  226. ProcessedLines int64
  227. EstimatedLines int64
  228. StartTime time.Time
  229. IsCompleted bool
  230. }
  231. // notifyProgressLocked sends progress notification (must be called with lock held)
  232. func (pt *ProgressTracker) notifyProgressLocked() {
  233. // Throttle notifications to avoid spam
  234. now := time.Now()
  235. if now.Sub(pt.lastNotify) < 2*time.Second {
  236. return
  237. }
  238. pt.lastNotify = now
  239. percentage, stats := pt.getProgressLocked()
  240. elapsed := time.Since(pt.startTime).Milliseconds()
  241. var estimatedRemain int64
  242. if percentage > 0 && percentage < 100 {
  243. avgTimePerPercent := float64(elapsed) / percentage
  244. remainingPercent := 100.0 - percentage
  245. estimatedRemain = int64(avgTimePerPercent * remainingPercent)
  246. }
  247. eventData := event.NginxLogIndexProgressData{
  248. LogPath: pt.logGroupPath,
  249. Progress: percentage,
  250. Stage: "indexing",
  251. Status: "running",
  252. ElapsedTime: elapsed,
  253. EstimatedRemain: estimatedRemain,
  254. }
  255. logger.Debugf("Progress update for %s: %.1f%% (%d/%d files, %d/%d lines)",
  256. pt.logGroupPath, percentage, stats.CompletedFiles, stats.TotalFiles,
  257. stats.ProcessedLines, stats.EstimatedLines)
  258. event.Publish(event.Event{
  259. Type: event.EventTypeNginxLogIndexProgress,
  260. Data: eventData,
  261. })
  262. }
  263. // notifyCompletionLocked sends completion notification (must be called with lock held)
  264. func (pt *ProgressTracker) notifyCompletionLocked() {
  265. elapsed := time.Since(pt.startTime).Milliseconds()
  266. // Calculate total size processed using improved estimation
  267. var totalSize int64
  268. for _, fp := range pt.files {
  269. if fp.IsCompressed {
  270. // For compressed files, use dynamic average line size
  271. totalSize += fp.ProcessedLines * fp.AvgLineSize
  272. } else {
  273. // For uncompressed files, use actual bytes processed if available, otherwise estimate
  274. if fp.CurrentPos > 0 {
  275. totalSize += fp.CurrentPos
  276. } else {
  277. // Fallback to line-based estimation with improved calculation
  278. totalSize += fp.ProcessedLines * 150
  279. }
  280. }
  281. }
  282. completeEventData := event.NginxLogIndexCompleteData{
  283. LogPath: pt.logGroupPath,
  284. Success: true,
  285. Duration: elapsed,
  286. TotalLines: pt.totalActual,
  287. IndexedSize: totalSize,
  288. Error: "",
  289. }
  290. event.Publish(event.Event{
  291. Type: event.EventTypeNginxLogIndexComplete,
  292. Data: completeEventData,
  293. })
  294. // Also publish index ready event for table refresh
  295. event.Publish(event.Event{
  296. Type: event.EventTypeNginxLogIndexReady,
  297. Data: map[string]interface{}{
  298. "log_path": pt.logGroupPath,
  299. "success": true,
  300. },
  301. })
  302. logger.Infof("Log group indexing completed for %s: %d files, %d lines processed in %dms (SINGLE NOTIFICATION)",
  303. pt.logGroupPath, len(pt.files), pt.totalActual, elapsed)
  304. }
  305. // getProgressLocked returns progress without notification (must be called with lock held)
  306. func (pt *ProgressTracker) getProgressLocked() (float64, ProgressStats) {
  307. stats := ProgressStats{
  308. LogGroupPath: pt.logGroupPath,
  309. TotalFiles: len(pt.files),
  310. ProcessedLines: pt.totalActual,
  311. EstimatedLines: pt.totalEstimate,
  312. StartTime: pt.startTime,
  313. IsCompleted: pt.isCompleted,
  314. }
  315. // Count completed files
  316. for _, fp := range pt.files {
  317. switch fp.State {
  318. case FileStateCompleted:
  319. stats.CompletedFiles++
  320. case FileStateProcessing:
  321. stats.ProcessingFiles++
  322. }
  323. }
  324. // Calculate progress percentage
  325. var percentage float64
  326. if pt.totalEstimate > 0 {
  327. percentage = float64(pt.totalActual) / float64(pt.totalEstimate) * 100
  328. } else if stats.TotalFiles > 0 {
  329. // Fallback to file-based progress if no line estimates
  330. percentage = float64(stats.CompletedFiles) / float64(stats.TotalFiles) * 100
  331. }
  332. // Cap at 100%
  333. if percentage > 100 {
  334. percentage = 100
  335. }
  336. return percentage, stats
  337. }
  338. // GlobalProgressManager manages all progress trackers
  339. type GlobalProgressManager struct {
  340. mu sync.RWMutex
  341. trackers map[string]*ProgressTracker
  342. }
  343. var globalProgressManager = &GlobalProgressManager{
  344. trackers: make(map[string]*ProgressTracker),
  345. }
  346. // GetProgressTracker gets or creates a progress tracker for a log group
  347. func GetProgressTracker(logGroupPath string) *ProgressTracker {
  348. globalProgressManager.mu.Lock()
  349. defer globalProgressManager.mu.Unlock()
  350. if tracker, exists := globalProgressManager.trackers[logGroupPath]; exists {
  351. return tracker
  352. }
  353. tracker := NewProgressTracker(logGroupPath)
  354. globalProgressManager.trackers[logGroupPath] = tracker
  355. return tracker
  356. }
  357. // RemoveProgressTracker removes a progress tracker (called when indexing is complete)
  358. func RemoveProgressTracker(logGroupPath string) {
  359. globalProgressManager.mu.Lock()
  360. defer globalProgressManager.mu.Unlock()
  361. delete(globalProgressManager.trackers, logGroupPath)
  362. logger.Debugf("Removed progress tracker for log group: %s", logGroupPath)
  363. }
  364. // EstimateFileLines estimates the number of lines in a file based on sampling
  365. func EstimateFileLines(filePath string, fileSize int64, isCompressed bool) int64 {
  366. if isCompressed {
  367. // For compressed files, estimate based on compression ratio and average line size
  368. // Assume 3:1 compression ratio and 100 bytes average per line
  369. estimatedUncompressedSize := fileSize * 3
  370. return estimatedUncompressedSize / 100
  371. }
  372. // For uncompressed files, assume average 100 bytes per line
  373. if fileSize == 0 {
  374. return 0
  375. }
  376. return fileSize / 100 // Rough estimate
  377. }