-
Notifications
You must be signed in to change notification settings - Fork 1
/
rotate.go
633 lines (479 loc) · 13.3 KB
/
rotate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/**
* @Author: lidonglin
* @Description:
* @File: rotate.go
* @Version: 1.0.0
* @Date: 2022/10/12 17:47
*/
package tlog
import (
"compress/gzip"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/choveylee/tcfg"
"go.uber.org/atomic"
)
const (
BackupTimeFormat = "2006_01_02T15_04_05"
CompressSuffix = ".gz"
DefaultMaxSize = 100
)
var (
// MegaByte is the conversion factor between fileSize and bytes.
MegaByte = 1024 * 1024
)
// ensure we always implement io.WriteCloser
var _ io.WriteCloser = (*RotateWriter)(nil)
func chown(_ string, _ os.FileInfo) error {
return nil
}
func getRotateTime(rotateTime time.Time, rotateDuration time.Duration) time.Time {
if rotateDuration%(24*time.Hour) == 0 {
currentRotateTime := time.Date(rotateTime.Year(), rotateTime.Month(), rotateTime.Day(), 0, 0, 0, 0, time.Local)
return currentRotateTime
}
return rotateTime.Truncate(rotateDuration)
}
// RotateWriter is an io.WriteCloser that writes to the specified getCurrentFilePath.
// If fileCount and fileExpired are both 0, no old log files will be deleted.
type RotateWriter struct {
// filePath is the file to write logs to
filePath string
// the max size of log file (MB)
fileSize int
fileRotate time.Duration
// max day to retain history log files
fileExpired int
// max count to retain history log files
fileCount int
// determine if the rotated log files be compressed
isCompress bool
file *os.File
size int64
rotateTime time.Time
cursor *atomic.Int32
millChan chan bool
sync.Mutex
}
func newRotateWriter(filePath string, fileSize int, fileRotate, fileExpired, fileCount int, isCompress bool) *RotateWriter {
rotateWriter := &RotateWriter{
filePath: filePath,
fileSize: fileSize,
fileRotate: time.Duration(fileRotate) * time.Hour,
fileExpired: fileExpired,
fileCount: fileCount,
isCompress: isCompress,
cursor: atomic.NewInt32(-1),
millChan: make(chan bool, 1),
}
go rotateWriter.runMill()
return rotateWriter
}
// Write implements io.Writer. If a write would cause the log file to be larger
// than fileSize, the file is closed, renamed to include a modifyTime of the
// current time, and a new log file is created using the original log file name.
// If the length of the write is greater than fileSize, an error is returned.
func (p *RotateWriter) Write(data []byte) (int, error) {
p.Lock()
defer p.Unlock()
if p.file == nil {
err := p.openLogFile()
if err != nil {
return 0, err
}
}
rotateTime := p.rotateTime
nextRotateTime := rotateTime.Add(p.fileRotate)
curTime := time.Now()
if curTime.Unix() >= nextRotateTime.Unix() {
err := p.rotate()
if err != nil {
return 0, err
}
p.rotateTime = getRotateTime(curTime, p.fileRotate)
p.cursor.Store(1)
}
writeLen := int64(len(data))
// over the getMaxSize size about this log file
if p.size+writeLen > p.getMaxSize() {
err := p.rotate()
if err != nil {
return 0, err
}
p.cursor.Add(1)
}
n, err := p.file.Write(data)
if err != nil {
return 0, err
}
p.size += int64(n)
return n, nil
}
// Close implements io.Closer, and closes the current confFile.
func (p *RotateWriter) Close() error {
p.Lock()
defer p.Unlock()
return p.close()
}
// close closes the file if it is open.
func (p *RotateWriter) close() error {
if p.file == nil {
return nil
}
err := p.file.Close()
p.file = nil
return err
}
// rotate closes the current file, moves it aside with a modifyTime in the name,
// (if it exists), opens a new file with the original getCurrentFilePath, and then runs
// post-rotation processing and removal.
func (p *RotateWriter) rotate() error {
err := p.close()
if err != nil {
return err
}
err = p.newLogFile()
if err != nil {
return err
}
select {
case p.millChan <- true:
default:
}
return nil
}
// newLogFile opens a new log file for writing, moving any old log file out of the
// way. This methods assumes the file has already been closed.
func (p *RotateWriter) newLogFile() error {
err := os.MkdirAll(p.getFileDir(), 0744)
if err != nil {
return err
}
filePath := p.getFilePath()
mode := os.FileMode(0644)
fileInfo, err := os.Stat(filePath)
if err == nil {
// copy the mode off the old log file.
mode = fileInfo.Mode()
rotateFilePath := p.getRotateFilePath()
err := os.Rename(filePath, rotateFilePath)
if err != nil {
return err
}
// this is a no-op anywhere but linux
if err := chown(filePath, fileInfo); err != nil {
return err
}
}
// we use truncate here because this should only get called when we've moved
// the file ourselves. if someone else creates the file in the meantime,
// just wipe out the contents.
file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
if err != nil {
return err
}
p.file = file
p.size = 0
return nil
}
func (p *RotateWriter) getFilePath() string {
if p.filePath != "" {
return p.filePath
}
appName := tcfg.DefaultString(AppName, "rcrai")
p.filePath = fmt.Sprintf("%s.log", appName)
return p.filePath
}
// getRotateFilePath generates the name of the confFile from the current time.
func (p *RotateWriter) getRotateFilePath() string {
filePath := p.filePath
dir := filepath.Dir(filePath)
filename := filepath.Base(filePath)
ext := filepath.Ext(filename)
prefix := filename[:len(filename)-len(ext)]
destFilename := ""
timeStr := p.rotateTime.Format(BackupTimeFormat)
destFilename = fmt.Sprintf("%s.%s.%d%s", prefix, timeStr, p.cursor.Load(), ext)
return filepath.Join(dir, destFilename)
}
// openLogFile opens the confFile if it exists and if the current write
// would not put it over fileSize. If there is no such file or the write would
// put it over the fileSize, a new file is created.
func (p *RotateWriter) openLogFile() error {
// init file path
filePath := p.getFilePath()
fileInfo, err := os.Stat(filePath)
if err != nil {
if os.IsNotExist(err) == false {
return err
}
err := p.newLogFile()
if err != nil {
return err
}
fileInfo, err = os.Stat(filePath)
if err != nil {
return err
}
} else {
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
// if we fail to open the old log file for some reason, just ignore
// it and open a new log file.
err := p.newLogFile()
if err != nil {
return err
}
} else {
p.file = file
p.size = fileInfo.Size()
}
}
p.rotateTime = getRotateTime(fileInfo.ModTime(), p.fileRotate)
cursor := getLogFileCursor(filePath, p.fileRotate)
p.cursor.Store(cursor)
return nil
}
// runMill runs in a goroutine to manage post-rotation compression and removal
// of old log files.
func (p *RotateWriter) runMill() {
for range p.millChan {
if p.fileCount == 0 && p.fileExpired == 0 && p.isCompress == false {
continue
}
historyLogFiles, err := p.getHistoryLogFiles()
if err != nil {
continue
}
var removeLogFiles []*logFile
if p.fileCount > 0 && p.fileCount < len(historyLogFiles) {
preservedLogFiles := make(map[string]bool)
var remainLogFiles []*logFile
for _, historyLogFile := range historyLogFiles {
// only count the uncompressed log file or the compressed log file, not both.
filename := historyLogFile.Name()
filename = strings.TrimSuffix(filename, CompressSuffix)
preservedLogFiles[filename] = true
if len(preservedLogFiles) > p.fileCount {
removeLogFiles = append(removeLogFiles, historyLogFile)
} else {
remainLogFiles = append(remainLogFiles, historyLogFile)
}
}
historyLogFiles = remainLogFiles
}
if p.fileExpired > 0 {
expiredDuration := time.Duration(int64(24*time.Hour) * int64(p.fileExpired))
expiredTime := time.Now().Add(-1 * expiredDuration)
var remainLogFiles []*logFile
for _, historyLogFile := range historyLogFiles {
if historyLogFile.modifyTime.Before(expiredTime) {
removeLogFiles = append(removeLogFiles, historyLogFile)
} else {
remainLogFiles = append(remainLogFiles, historyLogFile)
}
}
historyLogFiles = remainLogFiles
}
for _, removeLogFile := range removeLogFiles {
err := os.Remove(filepath.Join(p.getFileDir(), removeLogFile.Name()))
if err != nil {
// TODO
}
}
if p.isCompress == true {
for _, f := range historyLogFiles {
fn := filepath.Join(p.getFileDir(), f.Name())
if strings.HasSuffix(fn, CompressSuffix) {
continue
}
err := compressLogFile(fn, fn+CompressSuffix)
if err != nil {
// TODO
}
}
}
}
}
// getHistoryLogFiles returns the list of backup log files stored in the same
// directory as the current log file, sorted by ModTime
func (p *RotateWriter) getHistoryLogFiles() ([]*logFile, error) {
dirEntries, err := os.ReadDir(p.getFileDir())
if err != nil {
return nil, err
}
var historyLogFiles []*logFile
prefix, ext := p.getPrefixExt()
for _, dirEntry := range dirEntries {
if dirEntry.IsDir() {
continue
}
// file name equals to p.filePath, ignore it
if filepath.Base(p.filePath) == dirEntry.Name() {
continue
}
fileInfo, err := dirEntry.Info()
if err != nil {
continue
}
modifyTime := parseTimeByFilename(dirEntry.Name(), prefix, ext)
if modifyTime != nil {
historyLogFile := &logFile{fileInfo.ModTime(), fileInfo}
historyLogFiles = append(historyLogFiles, historyLogFile)
continue
}
modifyTime = parseTimeByFilename(dirEntry.Name(), prefix, ext+CompressSuffix)
if modifyTime != nil {
historyLogFile := &logFile{fileInfo.ModTime(), fileInfo}
historyLogFiles = append(historyLogFiles, historyLogFile)
continue
}
}
sort.Sort(logFiles(historyLogFiles))
return historyLogFiles, nil
}
// parseTimeByFilename extracts the formatted time from the path by stripping off path's prefix and extension
func parseTimeByFilename(filename, prefix, ext string) *time.Time {
if strings.HasPrefix(filename, prefix) == false {
return nil
}
if strings.HasSuffix(filename, ext) == false {
return nil
}
ts := filename[len(prefix) : len(filename)-len(ext)]
if strings.Contains(ts, ".") {
index := strings.Index(ts, ".")
ts = ts[:index]
}
updateTime, err := time.ParseInLocation(BackupTimeFormat, ts, time.Local)
if err != nil {
return nil
}
return &updateTime
}
// getMaxSize returns the maximum size in bytes of log files before rolling.
func (p *RotateWriter) getMaxSize() int64 {
if p.fileSize <= 0 {
return int64(DefaultMaxSize * MegaByte)
}
return int64(p.fileSize) * int64(MegaByte)
}
// getFileDir returns the directory for the file path.
func (p *RotateWriter) getFileDir() string {
return filepath.Dir(p.filePath)
}
// getPrefixExt returns the getCurrentFilePath part and extension part from the RotateWriter's
// getCurrentFilePath.
func (p *RotateWriter) getPrefixExt() (prefix, ext string) {
filename := filepath.Base(p.filePath)
ext = filepath.Ext(filename)
prefix = filename[:len(filename)-len(ext)] + "."
return prefix, ext
}
// compressLogFile compresses the given log file, removing the
// uncompressed log file if successful.
func compressLogFile(src, dst string) (err error) {
file, err := os.Open(src)
if err != nil {
return err
}
defer file.Close()
fileInfo, err := os.Stat(src)
if err != nil {
return err
}
if err := chown(dst, fileInfo); err != nil {
return err
}
// if this file already exists, we presume it was created by a previous attempt to compress the log file.
gzFile, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, fileInfo.Mode())
if err != nil {
return err
}
defer gzFile.Close()
gzWriter := gzip.NewWriter(gzFile)
defer func() {
if err != nil {
os.Remove(dst)
}
}()
_, err = io.Copy(gzWriter, file)
if err != nil {
return err
}
err = gzWriter.Close()
if err != nil {
return err
}
err = gzFile.Close()
if err != nil {
return err
}
err = file.Close()
if err != nil {
return err
}
err = os.Remove(src)
if err != nil {
return err
}
return nil
}
func getLogFileCursor(filePath string, rotateDuration time.Duration) int32 {
fileInfo, err := os.Stat(filePath)
if err != nil {
if os.IsNotExist(err) {
return 1
}
return -1
}
modifyTime := fileInfo.ModTime()
filename := filepath.Base(filePath)
ext := filepath.Ext(filename)
prefix := filename[:len(filename)-len(ext)]
rotateTime := getRotateTime(modifyTime, rotateDuration).Format(BackupTimeFormat)
rotatePrefix := fmt.Sprintf("%s.%s", prefix, rotateTime)
var filenames []string
fileDir := filepath.Dir(filePath)
filepath.Walk(fileDir, func(path string, info os.FileInfo, err error) error {
if info != nil && strings.Contains(info.Name(), rotatePrefix) {
filenames = append(filenames, info.Name())
}
return nil
})
var maxCursor int64 = 0
for _, filename := range filenames {
subStr := filename[len(rotatePrefix)+1:]
index := strings.Index(subStr, ".")
if index != -1 {
cursor, err := strconv.ParseInt(subStr[:index], 10, 32)
if err == nil && cursor > maxCursor {
maxCursor = cursor
}
}
}
return int32(maxCursor) + 1
}
// logFile is a convenience struct to return the path and its embedded modify time.
type logFile struct {
modifyTime time.Time
os.FileInfo
}
// logFiles sorts by newest time formatted in the name.
type logFiles []*logFile
func (f logFiles) Less(i, j int) bool {
return f[i].modifyTime.After(f[j].modifyTime)
}
func (f logFiles) Swap(i, j int) {
f[i], f[j] = f[j], f[i]
}
func (f logFiles) Len() int {
return len(f)
}