forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotator.go
247 lines (209 loc) · 5.67 KB
/
rotator.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
package file
import (
"os"
"path/filepath"
"strconv"
"sync"
"github.com/pkg/errors"
)
// MaxBackupsLimit is the upper bound on the number of backup files. Any values
// greater will result in an error.
const MaxBackupsLimit = 1024
// Rotator is a io.WriteCloser that automatically rotates the file it is
// writing to when it reaches a maximum size. It also purges the oldest rotated
// files when the maximum number of backups is reached.
type Rotator struct {
filename string
maxSizeBytes uint
maxBackups uint
permissions os.FileMode
file *os.File
size uint
mutex sync.Mutex
}
// RotatorOption is a configuration option for Rotator.
type RotatorOption func(r *Rotator)
// MaxSizeBytes configures the maximum number of bytes that a file should
// contain before being rotated. The default is 10 MiB.
func MaxSizeBytes(n uint) RotatorOption {
return func(r *Rotator) {
r.maxSizeBytes = n
}
}
// MaxBackups configures the maximum number of backup files to save (not
// counting the active file). The upper limit is 1024 on this value is.
// The default is 7.
func MaxBackups(n uint) RotatorOption {
return func(r *Rotator) {
r.maxBackups = n
}
}
// Permissions configures the file permissions to use for the file that
// the Rotator creates. The default is 0600.
func Permissions(m os.FileMode) RotatorOption {
return func(r *Rotator) {
r.permissions = m
}
}
// NewFileRotator returns a new Rotator.
func NewFileRotator(filename string, options ...RotatorOption) (*Rotator, error) {
r := &Rotator{
filename: filename,
maxSizeBytes: 10 * 1024 * 1024, // 10 MiB
maxBackups: 7,
permissions: 0600,
}
for _, opt := range options {
opt(r)
}
if r.maxSizeBytes == 0 {
return nil, errors.New("file rotator max file size must be greater than 0")
}
if r.maxBackups > MaxBackupsLimit {
return nil, errors.Errorf("file rotator max backups %d is greater than the limit of %v", r.maxBackups, MaxBackupsLimit)
}
if r.permissions > os.ModePerm {
return nil, errors.Errorf("file rotator permissions mask of %o is invalid", r.permissions)
}
return r, nil
}
// Write writes the given bytes to the file. This implements io.Writer. If
// the write would trigger a rotation the rotation is done before writing to
// avoid going over the max size. Write is safe for concurrent use.
func (r *Rotator) Write(data []byte) (int, error) {
r.mutex.Lock()
defer r.mutex.Unlock()
dataLen := uint(len(data))
if dataLen > r.maxSizeBytes {
return 0, errors.Errorf("data size (%d bytes) is greater than "+
"the max file size (%d bytes)", dataLen, r.maxSizeBytes)
}
if r.file == nil {
if err := r.openNew(); err != nil {
return 0, err
}
} else if r.size+dataLen > r.maxSizeBytes {
if err := r.rotate(); err != nil {
return 0, err
}
if err := r.openFile(); err != nil {
return 0, err
}
}
n, err := r.file.Write(data)
r.size += uint(n)
return n, errors.Wrap(err, "failed to write to file")
}
// Sync commits the current contents of the file to stable storage. Typically,
// this means flushing the file system's in-memory copy of recently written data
// to disk.
func (r *Rotator) Sync() error {
r.mutex.Lock()
defer r.mutex.Unlock()
if r.file == nil {
return nil
}
return r.file.Sync()
}
// Rotate triggers a file rotation.
func (r *Rotator) Rotate() error {
r.mutex.Lock()
defer r.mutex.Unlock()
return r.rotate()
}
// Close closes the currently open file.
func (r *Rotator) Close() error {
r.mutex.Lock()
defer r.mutex.Unlock()
return r.closeFile()
}
func (r *Rotator) backupName(n uint) string {
if n == 0 {
return r.filename
}
return r.filename + "." + strconv.Itoa(int(n))
}
func (r *Rotator) dir() string {
return filepath.Dir(r.filename)
}
func (r *Rotator) dirMode() os.FileMode {
mode := 0700
if r.permissions&0070 > 0 {
mode |= 0050
}
if r.permissions&0007 > 0 {
mode |= 0005
}
return os.FileMode(mode)
}
func (r *Rotator) openNew() error {
err := os.MkdirAll(r.dir(), r.dirMode())
if err != nil {
return errors.Wrap(err, "failed to make directories for new file")
}
_, err = os.Stat(r.filename)
if err == nil {
if err = r.rotate(); err != nil {
return err
}
}
return r.openFile()
}
func (r *Rotator) openFile() error {
err := os.MkdirAll(r.dir(), r.dirMode())
if err != nil {
return errors.Wrap(err, "failed to make directories for new file")
}
r.file, err = os.OpenFile(r.filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, r.permissions)
if err != nil {
return errors.Wrap(err, "failed to open new file")
}
return nil
}
func (r *Rotator) closeFile() error {
if r.file == nil {
return nil
}
err := r.file.Close()
r.file = nil
r.size = 0
return err
}
func (r *Rotator) purgeOldBackups() error {
for i := r.maxBackups; i < MaxBackupsLimit; i++ {
name := r.backupName(i + 1)
_, err := os.Stat(name)
switch {
case err == nil:
if err = os.Remove(name); err != nil {
return errors.Wrapf(err, "failed to delete %v during rotation", name)
}
case os.IsNotExist(err):
return nil
default:
return errors.Wrapf(err, "failed on %v during rotation", name)
}
}
return nil
}
func (r *Rotator) rotate() error {
if err := r.closeFile(); err != nil {
return errors.Wrap(err, "error file closing current file")
}
for i := r.maxBackups + 1; i > 0; i-- {
old := r.backupName(i - 1)
older := r.backupName(i)
if _, err := os.Stat(old); os.IsNotExist(err) {
continue
} else if err != nil {
return errors.Wrap(err, "failed to rotate backups")
}
if err := os.Remove(older); err != nil && !os.IsNotExist(err) {
return errors.Wrap(err, "failed to rotate backups")
}
if err := os.Rename(old, older); err != nil {
return errors.Wrap(err, "failed to rotate backups")
}
}
return r.purgeOldBackups()
}