This repository has been archived by the owner on Jun 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logro.go
290 lines (229 loc) · 5.25 KB
/
logro.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
/*
* Copyright (c) 2019. Temple3x (temple3x@gmail.com)
* Copyright (c) 2014 Nate Finch
*
* Use of this source code is governed by the MIT License
* that can be found in the LICENSE file.
*/
package logro
import (
"container/heap"
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/templexxx/go-diodes"
"github.com/templexxx/fnc"
)
// Rotation is implement io.WriteCloser interface with func Sync() (err error).
type Rotation struct {
cfg *Config
isRunning int64
backups *Backups
f *os.File
buf *diodes.ManyToOne
syncJob chan struct{}
flushJobs chan flushJob
ctx context.Context
loopCtx context.Context
loopCancel func()
loopWg sync.WaitGroup
}
// New creates a Rotation.
func New(cfg *Config) (r *Rotation, err error) {
r, err = prepare(cfg)
if err != nil {
return
}
r.run()
return
}
func prepare(cfg *Config) (r *Rotation, err error) {
if cfg.OutputPath == "" {
return nil, errors.New("empty log file path")
}
cfg.adjust()
r = &Rotation{cfg: cfg}
bs, err := listBackups(cfg.OutputPath, cfg.MaxBackups)
if err != nil {
return
}
r.backups = bs
err = r.open()
if err != nil {
return
}
r.buf = diodes.NewManyToOne(cfg.BufItem, nil)
r.syncJob = make(chan struct{}, 1)
r.flushJobs = make(chan flushJob, 16)
return
}
// open opens a new log file.
// If log file existed, move it to backups.
func (r *Rotation) open() (err error) {
fp := r.cfg.OutputPath
if r.f != nil { // File exist may happen in rotation process.
backupFP, t := makeBackupFP(fp, r.cfg.LocalTime, time.Now())
err = os.Rename(fp, backupFP)
if err != nil {
return fmt.Errorf("failed to rename log file, output: %s backup: %s", fp, backupFP)
}
heap.Push(r.backups, Backup{t, backupFP})
if r.backups.Len() > r.cfg.MaxBackups {
v := heap.Pop(r.backups)
os.Remove(v.(Backup).fp)
}
}
// Create a new log file.
dir := filepath.Dir(fp)
err = os.MkdirAll(dir, 0755) // ensure we have created the right dir.
if err != nil {
return fmt.Errorf("failed to make dirs for log file: %s", err.Error())
}
// Truncate here to clean up file content if someone else creates
// the file between exist checking and create file.
// Can't use os.O_EXCL here, because it may break rotation process.
//
// Most of log shippers monitor file size, and APPEND only can avoid Read-Modify-Write.
flag := os.O_WRONLY | os.O_CREATE | os.O_TRUNC | os.O_APPEND
f, err := fnc.OpenFile(fp, flag, 0644)
if err != nil {
return fmt.Errorf("failed to create log file: %s", err.Error())
}
r.f = f
return
}
func (r *Rotation) run() {
r.startLoop()
atomic.StoreInt64(&r.isRunning, 1)
}
func (r *Rotation) startLoop() {
r.loopCtx, r.loopCancel = context.WithCancel(context.Background())
r.loopWg.Add(2)
go r.writeLoop()
go r.syncLoop()
}
// Write writes data to buffer then notify file write.
func (r *Rotation) Write(p []byte) (written int, err error) {
if r.isClosed() {
return
}
r.buf.Set(unsafe.Pointer(&p))
return len(p), nil
}
// Sync syncs all dirty data.
func (r *Rotation) Sync() (err error) {
if r.isClosed() {
return
}
r.syncJob <- struct{}{}
return
}
// Close closes logro and release all resources.
func (r *Rotation) Close() (err error) {
if !atomic.CompareAndSwapInt64(&r.isRunning, 1, 0) {
return
}
r.stopLoop()
close(r.flushJobs)
r.buf = nil
if r.f != nil { // Just in case.
return r.f.Close()
}
return
}
func (r *Rotation) stopLoop() {
r.loopCancel()
r.loopWg.Wait()
}
func (r *Rotation) isClosed() bool {
return atomic.LoadInt64(&r.isRunning) == 0
}
type flushJob struct {
f *os.File
size int64
isOld bool
}
func (r *Rotation) writeLoop() {
defer r.loopWg.Done()
ctx, cancel := context.WithCancel(r.loopCtx)
defer cancel()
bufw := newBufIO(r.f, int(r.cfg.PerWriteSize))
dirty := 0
written := 0
for {
select {
case <-ctx.Done():
return
case <-r.syncJob:
for i := 0; i < r.cfg.BufItem; i++ { // There is a limit, avoiding blocking.
p, ok := r.buf.TryNext()
if !ok {
break
}
_, fw, _ := bufw.write(*(*[]byte)(p))
dirty += fw
written += fw
}
fw, _ := bufw.flush()
dirty += fw
written += fw
default:
p, ok := r.buf.TryNext()
if !ok {
time.Sleep(2 * time.Millisecond)
continue
}
_, fw, _ := bufw.write(*(*[]byte)(p))
dirty += fw
written += fw
if int64(dirty) >= r.cfg.PerSyncSize {
r.flushJobs <- flushJob{r.f, int64(dirty), false}
dirty = 0
}
if int64(written) >= r.cfg.MaxSize {
written = 0 // Avoiding keeping renew file if we can't create new file.
oldF := r.f
err := r.open()
if err == nil {
r.flushJobs <- flushJob{oldF, 0, true}
bufw.reset(r.f)
}
}
}
}
}
func (r *Rotation) syncLoop() {
defer r.loopWg.Done()
ctx, cancel := context.WithCancel(r.loopCtx)
defer cancel()
n := int64(0)
offset := int64(0)
for {
select {
case job := <-r.flushJobs:
if !job.isOld {
n += job.size
if n >= r.cfg.PerSyncSize {
fnc.FlushHint(job.f, offset, n)
offset += n
n = 0
}
} else {
fnc.FlushHint(job.f, 0, r.cfg.MaxSize)
fnc.DropCache(job.f, 0, r.cfg.MaxSize)
job.f.Close()
// Will have a new file in the next round.
offset = 0
n = 0
}
case <-ctx.Done():
return
}
}
}