-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
writer.go
270 lines (242 loc) · 5.15 KB
/
writer.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
package log
import (
"log"
"os"
"path"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/1Panel-dev/1Panel/backend/global"
"github.com/1Panel-dev/1Panel/backend/utils/files"
)
type Writer struct {
m Manager
file *os.File
absPath string
fire chan string
cf *Config
rollingfilech chan string
}
type AsynchronousWriter struct {
Writer
ctx chan int
queue chan []byte
errChan chan error
closed int32
wg sync.WaitGroup
}
func (w *AsynchronousWriter) Close() error {
if atomic.CompareAndSwapInt32(&w.closed, 0, 1) {
close(w.ctx)
w.onClose()
func() {
defer func() {
if r := recover(); r != nil {
global.LOG.Error(r)
}
}()
w.m.Close()
}()
return w.file.Close()
}
return ErrClosed
}
func (w *AsynchronousWriter) onClose() {
var err error
for {
select {
case b := <-w.queue:
if _, err = w.file.Write(b); err != nil {
select {
case w.errChan <- err:
default:
_asyncBufferPool.Put(&b)
return
}
}
_asyncBufferPool.Put(&b)
default:
return
}
}
}
var _asyncBufferPool = sync.Pool{
New: func() interface{} {
return make([]byte, BufferSize)
},
}
func NewWriterFromConfig(c *Config) (RollingWriter, error) {
if c.LogPath == "" || c.FileName == "" {
return nil, ErrInvalidArgument
}
if err := os.MkdirAll(c.LogPath, 0700); err != nil {
return nil, err
}
filepath := FilePath(c)
file, err := os.OpenFile(filepath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return nil, err
}
if err := dupWrite(file); err != nil {
return nil, err
}
mng, err := NewManager(c)
if err != nil {
return nil, err
}
var rollingWriter RollingWriter
writer := Writer{
m: mng,
file: file,
absPath: filepath,
fire: mng.Fire(),
cf: c,
}
if c.MaxRemain > 0 {
writer.rollingfilech = make(chan string, c.MaxRemain)
dir, err := os.ReadDir(c.LogPath)
if err != nil {
mng.Close()
return nil, err
}
files := make([]string, 0, 10)
for _, fi := range dir {
if fi.IsDir() {
continue
}
fileName := c.FileName
if strings.Contains(fi.Name(), fileName) && strings.Contains(fi.Name(), c.LogSuffix+".gz") {
start := strings.Index(fi.Name(), "-")
end := strings.Index(fi.Name(), c.LogSuffix)
name := fi.Name()
if start > 0 && end > 0 {
_, err := time.Parse(c.TimeTagFormat, name[start+1:end])
if err == nil {
files = append(files, fi.Name())
}
}
}
}
sort.Slice(files, func(i, j int) bool {
t1Start := strings.Index(files[i], "-")
t1End := strings.Index(files[i], c.LogSuffix)
t2Start := strings.Index(files[i], "-")
t2End := strings.Index(files[i], c.LogSuffix)
t1, _ := time.Parse(c.TimeTagFormat, files[i][t1Start+1:t1End])
t2, _ := time.Parse(c.TimeTagFormat, files[j][t2Start+1:t2End])
return t1.Before(t2)
})
for _, file := range files {
retry:
select {
case writer.rollingfilech <- path.Join(c.LogPath, file):
default:
writer.DoRemove()
goto retry
}
}
}
wr := &AsynchronousWriter{
ctx: make(chan int),
queue: make(chan []byte, QueueSize),
errChan: make(chan error, QueueSize),
wg: sync.WaitGroup{},
closed: 0,
Writer: writer,
}
wr.wg.Add(1)
go wr.writer()
wr.wg.Wait()
rollingWriter = wr
return rollingWriter, nil
}
func (w *AsynchronousWriter) writer() {
var err error
w.wg.Done()
for {
select {
case filename := <-w.fire:
if err = w.Reopen(filename); err != nil && len(w.errChan) < cap(w.errChan) {
w.errChan <- err
}
case b := <-w.queue:
if _, err = w.file.Write(b); err != nil && len(w.errChan) < cap(w.errChan) {
w.errChan <- err
}
_asyncBufferPool.Put(&b)
case <-w.ctx:
return
}
}
}
func (w *Writer) DoRemove() {
file := <-w.rollingfilech
if err := os.Remove(file); err != nil {
log.Println("error in remove log file", file, err)
}
}
func (w *Writer) Write(b []byte) (int, error) {
var ok = false
for !ok {
select {
case filename := <-w.fire:
if err := w.Reopen(filename); err != nil {
return 0, err
}
default:
ok = true
}
}
fp := atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&w.file)))
file := (*os.File)(fp)
return file.Write(b)
}
func (w *Writer) Reopen(file string) error {
fileInfo, err := w.file.Stat()
if err != nil {
return err
}
if fileInfo.Size() == 0 {
return nil
}
w.file.Close()
if err := os.Rename(w.absPath, file); err != nil {
return err
}
newFile, err := os.OpenFile(w.absPath, DefaultFileFlag, DefaultFileMode)
if err != nil {
return err
}
w.file = newFile
go func() {
if err := w.CompressFile(file); err != nil {
log.Println("error in compress log file", err)
return
}
if w.cf.MaxRemain > 0 {
retry:
select {
case w.rollingfilech <- file:
default:
w.DoRemove()
goto retry
}
}
}()
return nil
}
func (w *Writer) CompressFile(logFile string) error {
op := files.NewFileOp()
comFileName := path.Base(logFile) + ".gz"
filePath := path.Dir(logFile)
if err := op.Compress([]string{logFile}, filePath, comFileName, files.Gz); err != nil {
return err
}
if errR := os.Remove(logFile); errR != nil {
return errR
}
return nil
}