Debian Codegraph @

internal/logrotate/logrotate.go

raw symbols SCIP
1 // Copyright © SAS Institute Inc.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package logrotate
15
16 import (
17 "os"
18 "sync"
19 )
20
21 type Writer struct {
22 path string
23 f *os.File
24 fi os.FileInfo
25 mu sync.Mutex
26 }
27
28 func NewWriter(path string) (*Writer, error) {
29 w := &Writer{path: path}
30 return w, w.openLocked()
31 }
32
33 func (w *Writer) openLocked() error {
34 // open for appending
35 f, err := os.OpenFile(w.path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
36 if err != nil {
37 return err
38 }
39 // stat file to get inode to compare against later
40 fi, err := f.Stat()
41 if err != nil {
42 return err
43 }
44 if w.f != nil {
45 w.f.Close()
46 }
47 w.f = f
48 w.fi = fi
49 return nil
50 }
51
52 func (w *Writer) reopenLocked() error {
53 if w.f != nil {
54 fi, err := os.Stat(w.path)
55 if err != nil && !os.IsNotExist(err) {
56 return err
57 }
58 if os.SameFile(fi, w.fi) {
59 // file has not changed; do nothing
60 return nil
61 }
62 }
63 // file missing or changed, reopen
64 return w.openLocked()
65 }
66
67 func (w *Writer) Write(d []byte) (n int, err error) {
68 w.mu.Lock()
69 err = w.reopenLocked()
70 if err == nil {
71 n, err = w.f.Write(d)
72 }
73 w.mu.Unlock()
74 return
75 }
76
77 func (w *Writer) Close() (err error) {
78 w.mu.Lock()
79 if w.f != nil {
80 err = w.f.Close()
81 w.f = nil
82 }
83 w.mu.Unlock()
84 return
85 }