Debian Codegraph @

modules/logging/filewriter.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package logging
16
17 import (
18 "encoding/json"
19 "fmt"
20 "io"
21 "math"
22 "os"
23 "path/filepath"
24 "strconv"
25 "strings"
26 "time"
27
28 "github.com/DeRuina/timberjack"
29 "github.com/dustin/go-humanize"
30
31 "github.com/caddyserver/caddy/v2"
32 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
33 )
34
35 func init() {
36 caddy.RegisterModule(FileWriter{})
37 }
38
39 // fileMode is a string made of 1 to 4 octal digits representing
40 // a numeric mode as specified with the `chmod` unix command.
41 // `"0777"` and `"777"` are thus equivalent values.
42 type fileMode os.FileMode
43
44 // UnmarshalJSON satisfies json.Unmarshaler.
45 func (m *fileMode) UnmarshalJSON(b []byte) error {
46 if len(b) == 0 {
47 return io.EOF
48 }
49
50 var s string
51 if err := json.Unmarshal(b, &s); err != nil {
52 return err
53 }
54
55 mode, err := parseFileMode(s)
56 if err != nil {
57 return err
58 }
59
60 *m = fileMode(mode)
61 return err
62 }
63
64 // MarshalJSON satisfies json.Marshaler.
65 func (m *fileMode) MarshalJSON() ([]byte, error) {
66 return fmt.Appendf(nil, "\"%04o\"", *m), nil
67 }
68
69 // parseFileMode parses a file mode string,
70 // adding support for `chmod` unix command like
71 // 1 to 4 digital octal values.
72 func parseFileMode(s string) (os.FileMode, error) {
73 modeStr := fmt.Sprintf("%04s", s)
74 mode, err := strconv.ParseUint(modeStr, 8, 32)
75 if err != nil {
76 return 0, err
77 }
78 return os.FileMode(mode), nil
79 }
80
81 // FileWriter can write logs to files. By default, log files
82 // are rotated ("rolled") when they get large, and old log
83 // files get deleted, to ensure that the process does not
84 // exhaust disk space.
85 type FileWriter struct {
86 // Filename is the name of the file to write.
87 Filename string `json:"filename,omitempty"`
88
89 // The file permissions mode.
90 // 0600 by default.
91 Mode fileMode `json:"mode,omitempty"`
92
93 // DirMode controls permissions for any directories created to reach Filename.
94 // Default: 0700 (current behavior).
95 //
96 // Special values:
97 // - "inherit" → copy the nearest existing parent directory's perms (with r→x normalization)
98 // - "from_file" → derive from the file Mode (with r→x), e.g. 0644 → 0755, 0600 → 0700
99 // Numeric octal strings (e.g. "0755") are also accepted. Subject to process umask.
100 DirMode string `json:"dir_mode,omitempty"`
101
102 // Roll toggles log rolling or rotation, which is
103 // enabled by default.
104 Roll *bool `json:"roll,omitempty"`
105
106 // When a log file reaches approximately this size,
107 // it will be rotated.
108 RollSizeMB int `json:"roll_size_mb,omitempty"`
109
110 // Roll log file after some time
111 RollInterval time.Duration `json:"roll_interval,omitempty"`
112
113 // Roll log file at fix minutes
114 // For example []int{0, 30} will roll file at xx:00 and xx:30 each hour
115 // Invalid value are ignored with a warning on stderr
116 // See https://github.com/DeRuina/timberjack#%EF%B8%8F-rotation-notes--warnings for caveats
117 RollAtMinutes []int `json:"roll_minutes,omitempty"`
118
119 // Roll log file at fix time
120 // For example []string{"00:00", "12:00"} will roll file at 00:00 and 12:00 each day
121 // Invalid value are ignored with a warning on stderr
122 // See https://github.com/DeRuina/timberjack#%EF%B8%8F-rotation-notes--warnings for caveats
123 RollAt []string `json:"roll_at,omitempty"`
124
125 // Whether to compress rolled files.
126 // Default: true.
127 // Deprecated: Use RollCompression instead, setting it to "none".
128 RollCompress *bool `json:"roll_gzip,omitempty"`
129
130 // RollCompression selects the compression algorithm for rolled files.
131 // Accepted values: "none", "gzip", "zstd".
132 // Default: gzip
133 RollCompression string `json:"roll_compression,omitempty"`
134
135 // Whether to use local timestamps in rolled filenames.
136 // Default: false
137 RollLocalTime bool `json:"roll_local_time,omitempty"`
138
139 // The maximum number of rolled log files to keep.
140 // Default: 10
141 RollKeep int `json:"roll_keep,omitempty"`
142
143 // How many days to keep rolled log files. Default: 90
144 RollKeepDays int `json:"roll_keep_days,omitempty"`
145
146 // Rotated file will have format <logfilename>-<format>-<criterion>.log
147 // Optional. If unset or invalid, defaults to 2006-01-02T15-04-05.000 (with fallback warning)
148 // <format> must be a Go time compatible format, see https://pkg.go.dev/time#pkg-constants
149 BackupTimeFormat string `json:"backup_time_format,omitempty"`
150 }
151
152 // CaddyModule returns the Caddy module information.
153 func (FileWriter) CaddyModule() caddy.ModuleInfo {
154 return caddy.ModuleInfo{
155 ID: "caddy.logging.writers.file",
156 New: func() caddy.Module { return new(FileWriter) },
157 }
158 }
159
160 // Provision sets up the module
161 func (fw *FileWriter) Provision(ctx caddy.Context) error {
162 // Replace placeholder in filename
163 repl := caddy.NewReplacer()
164 filename, err := repl.ReplaceOrErr(fw.Filename, true, true)
165 if err != nil {
166 return fmt.Errorf("invalid filename for log file: %v", err)
167 }
168
169 fw.Filename = filename
170 return nil
171 }
172
173 func (fw FileWriter) String() string {
174 fpath, err := caddy.FastAbs(fw.Filename)
175 if err == nil {
176 return fpath
177 }
178 return fw.Filename
179 }
180
181 // WriterKey returns a unique key representing this fw.
182 func (fw FileWriter) WriterKey() string {
183 return "file:" + fw.Filename
184 }
185
186 // OpenWriter opens a new file writer.
187 func (fw FileWriter) OpenWriter() (io.WriteCloser, error) {
188 modeIfCreating := os.FileMode(fw.Mode)
189 if modeIfCreating == 0 {
190 modeIfCreating = 0o600
191 }
192
193 // roll log files as a sensible default to avoid disk space exhaustion
194 roll := fw.Roll == nil || *fw.Roll
195
196 // Ensure directory exists before opening the file.
197 dirPath := filepath.Dir(fw.Filename)
198 switch strings.ToLower(strings.TrimSpace(fw.DirMode)) {
199 case "", "0":
200 // Preserve current behavior: locked-down directories by default.
201 if err := os.MkdirAll(dirPath, 0o700); err != nil {
202 return nil, err
203 }
204 case "inherit":
205 if err := mkdirAllInherit(dirPath); err != nil {
206 return nil, err
207 }
208 case "from_file":
209 if err := mkdirAllFromFile(dirPath, os.FileMode(fw.Mode)); err != nil {
210 return nil, err
211 }
212 default:
213 dm, err := parseFileMode(fw.DirMode)
214 if err != nil {
215 return nil, fmt.Errorf("dir_mode: %w", err)
216 }
217 if err := os.MkdirAll(dirPath, dm); err != nil {
218 return nil, err
219 }
220 }
221
222 // create/open the file
223 file, err := os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, modeIfCreating)
224 if err != nil {
225 return nil, err
226 }
227 info, err := file.Stat()
228 if roll {
229 file.Close() // timberjack will reopen it on its own
230 }
231
232 // Ensure already existing files have the right mode, since OpenFile will not set the mode in such case.
233 if configuredMode := os.FileMode(fw.Mode); configuredMode != 0 {
234 if err != nil {
235 return nil, fmt.Errorf("unable to stat log file to see if we need to set permissions: %v", err)
236 }
237 // only chmod if the configured mode is different
238 if info.Mode()&os.ModePerm != configuredMode&os.ModePerm {
239 if err = os.Chmod(fw.Filename, configuredMode); err != nil {
240 return nil, err
241 }
242 }
243 }
244
245 // if not rolling, then the plain file handle is all we need
246 if !roll {
247 return file, nil
248 }
249
250 // otherwise, return a rolling log
251 if fw.RollSizeMB == 0 {
252 fw.RollSizeMB = 100
253 }
254 if fw.RollCompress == nil {
255 compress := true
256 fw.RollCompress = &compress
257 }
258 if fw.RollKeep == 0 {
259 fw.RollKeep = 10
260 }
261 if fw.RollKeepDays == 0 {
262 fw.RollKeepDays = 90
263 }
264
265 // Determine compression algorithm to use. Priority:
266 // 1) explicit RollCompression (none|gzip|zstd)
267 // 2) if RollCompress is unset or true -> gzip
268 // 3) if RollCompress is false -> none
269 var compression string
270 if fw.RollCompression != "" {
271 compression = strings.ToLower(strings.TrimSpace(fw.RollCompression))
272 if compression != "none" && compression != "gzip" && compression != "zstd" {
273 return nil, fmt.Errorf("invalid roll_compression: %s", fw.RollCompression)
274 }
275 } else {
276 if fw.RollCompress == nil || *fw.RollCompress {
277 compression = "gzip"
278 } else {
279 compression = "none"
280 }
281 }
282
283 return &timberjack.Logger{
284 Filename: fw.Filename,
285 MaxSize: fw.RollSizeMB,
286 MaxAge: fw.RollKeepDays,
287 MaxBackups: fw.RollKeep,
288 LocalTime: fw.RollLocalTime,
289 Compression: compression,
290 RotationInterval: fw.RollInterval,
291 RotateAtMinutes: fw.RollAtMinutes,
292 RotateAt: fw.RollAt,
293 BackupTimeFormat: fw.BackupTimeFormat,
294 FileMode: os.FileMode(fw.Mode),
295 }, nil
296 }
297
298 // normalizeDirPerm ensures that read bits also have execute bits set.
299 func normalizeDirPerm(p os.FileMode) os.FileMode {
300 if p&0o400 != 0 {
301 p |= 0o100
302 }
303 if p&0o040 != 0 {
304 p |= 0o010
305 }
306 if p&0o004 != 0 {
307 p |= 0o001
308 }
309 return p
310 }
311
312 // mkdirAllInherit creates missing dirs using the nearest existing parent's
313 // permissions, normalized with r→x.
314 func mkdirAllInherit(dir string) error {
315 if fi, err := os.Stat(dir); err == nil && fi.IsDir() {
316 return nil
317 }
318 cur := dir
319 var parent string
320 for {
321 next := filepath.Dir(cur)
322 if next == cur {
323 parent = next
324 break
325 }
326 if fi, err := os.Stat(next); err == nil {
327 if !fi.IsDir() {
328 return fmt.Errorf("path component %s exists and is not a directory", next)
329 }
330 parent = next
331 break
332 }
333 cur = next
334 }
335 perm := os.FileMode(0o700)
336 if fi, err := os.Stat(parent); err == nil && fi.IsDir() {
337 perm = fi.Mode().Perm()
338 }
339 perm = normalizeDirPerm(perm)
340 return os.MkdirAll(dir, perm)
341 }
342
343 // mkdirAllFromFile creates missing dirs using the file's mode (with r→x) so
344 // 0644 → 0755, 0600 → 0700, etc.
345 func mkdirAllFromFile(dir string, fileMode os.FileMode) error {
346 if fi, err := os.Stat(dir); err == nil && fi.IsDir() {
347 return nil
348 }
349 perm := normalizeDirPerm(fileMode.Perm()) | 0o200 // ensure owner write on dir so files can be created
350 return os.MkdirAll(dir, perm)
351 }
352
353 // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax:
354 //
355 // file <filename> {
356 // mode <mode>
357 // dir_mode <mode|inherit|from_file>
358 // roll_disabled
359 // roll_size <size>
360 // roll_uncompressed
361 // roll_compression <none|gzip|zstd>
362 // roll_local_time
363 // roll_keep <num>
364 // roll_keep_for <days>
365 // }
366 //
367 // The roll_size value has megabyte resolution.
368 // Fractional values are rounded up to the next whole megabyte (MiB).
369 //
370 // By default, compression is enabled, but can be turned off by setting
371 // the roll_uncompressed option.
372 //
373 // The roll_keep_for duration has day resolution.
374 // Fractional values are rounded up to the next whole number of days.
375 //
376 // If any of the mode, roll_size, roll_keep, or roll_keep_for subdirectives are
377 // omitted or set to a zero value, then Caddy's default value for that
378 // subdirective is used.
379 func (fw *FileWriter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
380 d.Next() // consume writer name
381 if !d.NextArg() {
382 return d.ArgErr()
383 }
384 fw.Filename = d.Val()
385 if d.NextArg() {
386 return d.ArgErr()
387 }
388
389 for d.NextBlock(0) {
390 switch d.Val() {
391 case "mode":
392 var modeStr string
393 if !d.AllArgs(&modeStr) {
394 return d.ArgErr()
395 }
396 mode, err := parseFileMode(modeStr)
397 if err != nil {
398 return d.Errf("parsing mode: %v", err)
399 }
400 fw.Mode = fileMode(mode)
401
402 case "dir_mode":
403 var val string
404 if !d.AllArgs(&val) {
405 return d.ArgErr()
406 }
407 val = strings.TrimSpace(val)
408 switch strings.ToLower(val) {
409 case "inherit", "from_file":
410 fw.DirMode = val
411 default:
412 if _, err := parseFileMode(val); err != nil {
413 return d.Errf("parsing dir_mode: %v", err)
414 }
415 fw.DirMode = val
416 }
417
418 case "roll_disabled":
419 var f bool
420 fw.Roll = &f
421 if d.NextArg() {
422 return d.ArgErr()
423 }
424
425 case "roll_size":
426 var sizeStr string
427 if !d.AllArgs(&sizeStr) {
428 return d.ArgErr()
429 }
430 size, err := humanize.ParseBytes(sizeStr)
431 if err != nil {
432 return d.Errf("parsing size: %v", err)
433 }
434 fw.RollSizeMB = int(math.Ceil(float64(size) / humanize.MiByte))
435
436 case "roll_uncompressed":
437 var f bool
438 fw.RollCompress = &f
439 if d.NextArg() {
440 return d.ArgErr()
441 }
442
443 case "roll_compression":
444 var comp string
445 if !d.AllArgs(&comp) {
446 return d.ArgErr()
447 }
448 comp = strings.ToLower(strings.TrimSpace(comp))
449 switch comp {
450 case "none", "gzip", "zstd":
451 fw.RollCompression = comp
452 default:
453 return d.Errf("parsing roll_compression: must be 'none', 'gzip' or 'zstd'")
454 }
455
456 case "roll_local_time":
457 fw.RollLocalTime = true
458 if d.NextArg() {
459 return d.ArgErr()
460 }
461
462 case "roll_keep":
463 var keepStr string
464 if !d.AllArgs(&keepStr) {
465 return d.ArgErr()
466 }
467 keep, err := strconv.Atoi(keepStr)
468 if err != nil {
469 return d.Errf("parsing roll_keep number: %v", err)
470 }
471 fw.RollKeep = keep
472
473 case "roll_keep_for":
474 var keepForStr string
475 if !d.AllArgs(&keepForStr) {
476 return d.ArgErr()
477 }
478 keepFor, err := caddy.ParseDuration(keepForStr)
479 if err != nil {
480 return d.Errf("parsing roll_keep_for duration: %v", err)
481 }
482 if keepFor < 0 {
483 return d.Errf("negative roll_keep_for duration: %v", keepFor)
484 }
485 fw.RollKeepDays = int(math.Ceil(keepFor.Hours() / 24))
486
487 case "roll_interval":
488 var durationStr string
489 if !d.AllArgs(&durationStr) {
490 return d.ArgErr()
491 }
492 duration, err := time.ParseDuration(durationStr)
493 if err != nil {
494 return d.Errf("parsing roll_interval duration: %v", err)
495 }
496 fw.RollInterval = duration
497
498 case "roll_minutes":
499 // Accept either a single comma-separated argument or
500 // multiple space-separated arguments. Collect all
501 // remaining args on the line and split on commas.
502 args := d.RemainingArgs()
503 if len(args) == 0 {
504 return d.ArgErr()
505 }
506 var minutes []int
507 for _, arg := range args {
508 parts := strings.SplitSeq(arg, ",")
509 for p := range parts {
510 ms := strings.TrimSpace(p)
511 if ms == "" {
512 return d.Errf("parsing roll_minutes: empty value")
513 }
514 m, err := strconv.Atoi(ms)
515 if err != nil {
516 return d.Errf("parsing roll_minutes number: %v", err)
517 }
518 minutes = append(minutes, m)
519 }
520 }
521 fw.RollAtMinutes = minutes
522
523 case "roll_at":
524 // Accept either a single comma-separated argument or
525 // multiple space-separated arguments. Collect all
526 // remaining args on the line and split on commas.
527 args := d.RemainingArgs()
528 if len(args) == 0 {
529 return d.ArgErr()
530 }
531 var times []string
532 for _, arg := range args {
533 parts := strings.SplitSeq(arg, ",")
534 for p := range parts {
535 ts := strings.TrimSpace(p)
536 if ts == "" {
537 return d.Errf("parsing roll_at: empty value")
538 }
539 times = append(times, ts)
540 }
541 }
542 fw.RollAt = times
543
544 case "backup_time_format":
545 var format string
546 if !d.AllArgs(&format) {
547 return d.ArgErr()
548 }
549 fw.BackupTimeFormat = format
550
551 default:
552 return d.Errf("unrecognized subdirective '%s'", d.Val())
553 }
554 }
555 return nil
556 }
557
558 // Interface guards
559 var (
560 _ caddy.Provisioner = (*FileWriter)(nil)
561 _ caddy.WriterOpener = (*FileWriter)(nil)
562 _ caddyfile.Unmarshaler = (*FileWriter)(nil)
563 )