-
Notifications
You must be signed in to change notification settings - Fork 0
/
reopen.go
119 lines (107 loc) · 2.21 KB
/
reopen.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
//go:build !windows
// +build !windows
package log
import (
"fmt"
"io"
"os"
"os/signal"
"sync"
)
// Opener returns a new io.WriteCloser.
type Opener interface {
Open() (io.WriteCloser, error)
}
type reopenWriter struct {
lock sync.Mutex
lastErr error
writer io.WriteCloser
}
// NewReopenWriter constructs a io.Writer that reopens inner io.WriteCloser
// when signals are received.
func NewReopenWriter(opener Opener, sig ...os.Signal) (io.Writer, error) {
w, err := opener.Open()
if err != nil {
return nil, err
}
c := make(chan os.Signal, 1)
signal.Notify(c, sig...)
r := &reopenWriter{
writer: w,
}
reopen := func() {
r.lock.Lock()
defer r.lock.Unlock()
if r.writer != nil {
err := r.writer.Close()
// io.Closer does not guarantee that it is safe to call it twice.
r.writer = nil
if err != nil {
r.lastErr = err
return
}
}
w, err := opener.Open()
if err != nil {
r.lastErr = err
return
}
r.writer = w
r.lastErr = nil
}
go func() {
for range c {
reopen()
}
}()
return r, nil
}
// Write calles inner writes.
// If some error has happened when re-opening, this reports the error.
func (r *reopenWriter) Write(p []byte) (n int, err error) {
r.lock.Lock()
defer r.lock.Unlock()
if r.lastErr != nil {
err = fmt.Errorf("unusable due to %v", r.lastErr)
return
}
return r.writer.Write(p)
}
type fileOpener string
func (o fileOpener) Open() (io.WriteCloser, error) {
f, err := os.OpenFile(string(o), os.O_RDWR|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
return nil, err
}
fi, err := f.Stat()
if err != nil {
f.Close()
return nil, err
}
// correct the tail of the file if the file is not empty and
// does not ends with a newline.
size := fi.Size()
if size > 0 {
var buf [1]byte
_, err = f.ReadAt(buf[:], size-1)
if err != nil {
goto OUT
}
if buf[0] == byte('\n') {
goto OUT
}
buf[0] = byte('\n')
_, err = f.Write(buf[:])
}
OUT:
if err != nil {
f.Close()
return nil, err
}
return f, nil
}
// NewFileReopener returns io.Writer that will reopen the named file
// when signals are received.
func NewFileReopener(filename string, sig ...os.Signal) (io.Writer, error) {
return NewReopenWriter(fileOpener(filename), sig...)
}