Skip to content

Commit ff6d43e

Browse files
committed
fix rotation
1 parent 1daf270 commit ff6d43e

File tree

1 file changed

+29
-15
lines changed

1 file changed

+29
-15
lines changed

internal/app/machined/pkg/controllers/runtime/log_persistence.go

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -68,22 +68,36 @@ func (ctrl *LogPersistenceController) filenameForId(id string) string {
6868
return filepath.Join(constants.LogMountPoint, id+".log")
6969
}
7070

71+
func (ctrl *LogPersistenceController) getLogFile(id string, overwrite bool) (*os.File, error) {
72+
var err error
73+
74+
f, ok := ctrl.files[id]
75+
76+
if ok && !overwrite {
77+
return f, nil
78+
}
79+
80+
f, err = os.OpenFile(ctrl.filenameForId(id), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
81+
if err != nil {
82+
return nil, fmt.Errorf("error opening log file for %q: %w", id, err)
83+
}
84+
85+
ctrl.filesMutex.Lock()
86+
ctrl.files[id] = f
87+
ctrl.filesMutex.Unlock()
88+
89+
return f, nil
90+
}
91+
7192
func (ctrl *LogPersistenceController) WriteLog(id string, line []byte) error {
7293
var err error
7394

7495
ctrl.canLog.RLock()
7596
defer ctrl.canLog.RUnlock()
7697

77-
f, ok := ctrl.files[id]
78-
if !ok {
79-
f, err = os.OpenFile(ctrl.filenameForId(id), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
80-
if err != nil {
81-
return fmt.Errorf("error opening log file for %q: %w", id, err)
82-
}
83-
84-
ctrl.filesMutex.Lock()
85-
ctrl.files[id] = f
86-
ctrl.filesMutex.Unlock()
98+
f, err := ctrl.getLogFile(id, false)
99+
if err != nil {
100+
return err
87101
}
88102

89103
if _, err = f.Write(append(line, '\n')); err != nil {
@@ -118,8 +132,6 @@ func (ctrl *LogPersistenceController) stopLogging() error {
118132
func (ctrl *LogPersistenceController) rotate(id string) error {
119133
ctrl.canLog.Lock()
120134
defer ctrl.canLog.Unlock()
121-
ctrl.filesMutex.Lock()
122-
defer ctrl.filesMutex.Unlock()
123135

124136
_, ok := ctrl.files[id]
125137
if !ok {
@@ -130,14 +142,17 @@ func (ctrl *LogPersistenceController) rotate(id string) error {
130142
return fmt.Errorf("error closing log file for %q: %w", id, err)
131143
}
132144

133-
delete(ctrl.files, id)
134-
135145
filename := ctrl.filenameForId(id)
136146
err := os.Rename(filename, filename+".1")
137147
if err != nil {
138148
return fmt.Errorf("rename: %w", err)
139149
}
140150

151+
_, err = ctrl.getLogFile(id, true)
152+
if err != nil {
153+
return fmt.Errorf("create: %w", err)
154+
}
155+
141156
return nil
142157
}
143158

@@ -165,7 +180,6 @@ func (ctrl *LogPersistenceController) Run(ctx context.Context, r controller.Runt
165180
return fmt.Errorf("error stat logfile %s: %w", id, err)
166181
}
167182
if st.Size() >= 512*1024 {
168-
fmt.Println("LOGGING rotating", id)
169183
err = ctrl.rotate(id)
170184
if err != nil {
171185
return fmt.Errorf("error rotating logfile %s: %w", id, err)

0 commit comments

Comments
 (0)