Source file src/cmd/go/internal/cache/log.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package cache
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  	"io/fs"
    11  	"os"
    12  	"path/filepath"
    13  	"time"
    14  )
    15  
    16  // With GOEXPERIMENT=trimbuildcache, GOCACHE/cache.log records each trim attempt. Sample lines:
    17  //
    18  //	<time> trim: size trigger: 9.000 GiB -> 6.000 GiB in 2.123s, removed 9 of 48 files, base=6.000 GiB next=9.000 GiB
    19  //	<time> trim: 24h trigger: 1.200 GiB -> 0.800 GiB in 1.52s, removed 12 of 56 files, base=0.800 GiB next=5.000 GiB
    20  //	<time> trim: low disk trigger: 4.100 GiB -> 1.300 GiB in 810ms, removed 30 of 90 files, base=1.000 GiB next=5.000 GiB free=0.400 GiB (consider providing more space)
    21  //
    22  // Once cache.log reaches logRollSize, it rotates through cache.1.log and cache.2.log as needed,
    23  // with an old cache.2.log being discarded. 'go clean -cache' does not delete the logs.
    24  
    25  const logRollSize int64 = 128 << 10 // 128 KiB per log file (3 files max)
    26  
    27  // appendLogLocked appends a timestamped line to cache.log, rotating the logs if needed.
    28  //
    29  // The caller must hold the trim.txt lock. Logging is best effort: errors are ignored
    30  // and repeated failure to roll the logs will cause an eventual logging halt. An intermittent
    31  // failure to roll might cause the active log to grow up to ~2x expected max size.
    32  func appendLogLocked(dir string, now time.Time, format string, args ...any) {
    33  	msg := fmt.Sprintf(format, args...)
    34  	line := fmt.Sprintf("%s %s\n", now.Format("2006/01/02 15:04:05"), msg)
    35  	if len(line) > 2048 {
    36  		line = line[:2048] + " [truncated]\n"
    37  	}
    38  
    39  	// First check if we need to roll our log files.
    40  	log0 := filepath.Join(dir, "cache.log")
    41  	info, err := os.Stat(log0)
    42  	if err == nil && info.Size() >= logRollSize {
    43  		// Past max size for the active log, so roll.
    44  		err := rollLogLocked(dir)
    45  		if err != nil && info.Size() >= 2*logRollSize {
    46  			// Rotation failed and cache.log is well past expected size.
    47  			// Something is wrong, don't log anything.
    48  			return
    49  		}
    50  	}
    51  
    52  	// Ready to log.
    53  	f, err := os.OpenFile(log0, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666)
    54  	if err != nil {
    55  		return
    56  	}
    57  	defer f.Close()
    58  	f.WriteString(line)
    59  }
    60  
    61  // rollLogLocked rotates cache.log -> cache.1.log -> cache.2.log.
    62  // The caller must hold the trim.txt lock.
    63  func rollLogLocked(dir string) error {
    64  	// We have one, two, or three log files and the goal is to preserve
    65  	// the two most recent with new names.
    66  	//
    67  	// A rare mid-rotation crash or rename failure such as from a virus scanner
    68  	// or similar still preserves the file contents, though can leave
    69  	// a gap in the numbering until the next rotation heals the gap.
    70  	log0 := filepath.Join(dir, "cache.log")
    71  	log1 := filepath.Join(dir, "cache.1.log")
    72  	log2 := filepath.Join(dir, "cache.2.log")
    73  
    74  	// First, 1 to 2 if 1 exists.
    75  	err := os.Rename(log1, log2)
    76  	if err != nil && !errors.Is(err, fs.ErrNotExist) {
    77  		// Not existing is fine, but some other error occurred.
    78  		return err
    79  	}
    80  	// Second, 0 to 1.
    81  	return os.Rename(log0, log1)
    82  }
    83  
    84  // formatBytes formats a byte count as GiB for cache.log, such as "1.500 GiB".
    85  func formatBytes(b int64) string {
    86  	return fmt.Sprintf("%.3f GiB", float64(b)/(1<<30))
    87  }
    88  
    89  // formatEstimateDelta returns a parenthetical note if est differs from actual
    90  // by more than 10% and 1 GiB, or "" otherwise.
    91  func formatEstimateDelta(est, actual int64) string {
    92  	delta := est - actual
    93  	if absDelta := max(delta, -delta); absDelta <= actual/10 || absDelta <= 1<<30 {
    94  		return ""
    95  	}
    96  	var pct string
    97  	if actual > 0 {
    98  		pct = fmt.Sprintf(" delta=%+.1f%%", 100*float64(delta)/float64(actual))
    99  	}
   100  	return fmt.Sprintf(" (prior estimate=%s actual=%s%s)", formatBytes(est), formatBytes(actual), pct)
   101  }
   102  

View as plain text