| 1 | // Copyright 2022 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 | // The filecache package provides a file-based shared durable blob cache. |
| 6 | // |
| 7 | // The cache is a machine-global mapping from (kind string, key |
| 8 | // [32]byte) to []byte, where kind is an identifier describing the |
| 9 | // namespace or purpose (e.g. "analysis"), and key is a SHA-256 digest |
| 10 | // of the recipe of the value. (It need not be the digest of the value |
| 11 | // itself, so you can query the cache without knowing what value the |
| 12 | // recipe would produce.) |
| 13 | // |
| 14 | // The space budget of the cache can be controlled by [SetBudget]. |
| 15 | // Cache entries may be evicted at any time or in any order. |
| 16 | // Note that "du -sh $GOPLSCACHE" may report a disk usage |
| 17 | // figure that is rather larger (e.g. 50%) than the budget because |
| 18 | // it rounds up partial disk blocks. |
| 19 | // |
| 20 | // The Get and Set operations are concurrency-safe. |
| 21 | package filecache |
| 22 | |
| 23 | import ( |
| 24 | "bytes" |
| 25 | "crypto/sha256" |
| 26 | "encoding/hex" |
| 27 | "encoding/json" |
| 28 | "errors" |
| 29 | "fmt" |
| 30 | "io" |
| 31 | "io/fs" |
| 32 | "log" |
| 33 | "os" |
| 34 | "path/filepath" |
| 35 | "sort" |
| 36 | "strings" |
| 37 | "sync" |
| 38 | "sync/atomic" |
| 39 | "time" |
| 40 | |
| 41 | "golang.org/x/tools/gopls/internal/util/bug" |
| 42 | "golang.org/x/tools/gopls/internal/util/lru" |
| 43 | ) |
| 44 | |
| 45 | // Start causes the filecache to initialize and start garbage gollection. |
| 46 | // |
| 47 | // Start is automatically called by the first call to Get, but may be called |
| 48 | // explicitly to pre-initialize the cache. |
| 49 | func Start() { |
| 50 | go getCacheDir() // ignore error |
| 51 | } |
| 52 | |
| 53 | // memCache is a 100MB in-memory LRU cache in front of filecache |
| 54 | // operations. It holds either raw bytes (written by [Set]) or decoded |
| 55 | // objects (written by [Get]). This avoids both repeated I/O and |
| 56 | // repeated deserialization for operations such as references or |
| 57 | // implementations that access the same entries many times. |
| 58 | var memCache = lru.New[memKey, any](100 * 1e6) |
| 59 | |
| 60 | type memKey struct { |
| 61 | kind string |
| 62 | key [32]byte |
| 63 | } |
| 64 | |
| 65 | // ErrNotFound is the distinguished error |
| 66 | // returned by Get when the key is not found. |
| 67 | var ErrNotFound = fmt.Errorf("not found") |
| 68 | |
| 69 | // ErrNoCache is the type of errors returned by Get when the cache |
| 70 | // cannot be created at all (e.g. due to disk space, lack of |
| 71 | // permission, deletion of the gopls executable, or hardware fault). |
| 72 | // |
| 73 | // The appropriate action in this case is typically to log.Fatal since |
| 74 | // there is little the application can do and performance will |
| 75 | // inevitably be terrible; See [GetOrFatal]. |
| 76 | type ErrNoCache struct{ error } |
| 77 | |
| 78 | // Bytes is the identity decoder, for use with [Get] when the caller |
| 79 | // wants the raw bytes. |
| 80 | func Bytes(data []byte) []byte { return data } |
| 81 | |
| 82 | // Get retrieves from the cache the value most recently supplied to |
| 83 | // Set(kind, key), possibly by another process, and passes it through |
| 84 | // decode. The decoded result is cached in memory so that repeated |
| 85 | // reads avoid both I/O and deserialization. On a memory-cache hit |
| 86 | // holding raw bytes (from a recent [Set]), the entry is decoded once |
| 87 | // and upgraded in place from raw bytes to the decoded value. |
| 88 | // |
| 89 | // Get returns [ErrNotFound] if the value was not found. |
| 90 | // |
| 91 | // Get returns [ErrNoCache] if the cache did not exist and could not |
| 92 | // be created. This may be due to ENOSPC, deletion of the process's |
| 93 | // executable, deletion or corruption of the cache by external |
| 94 | // meddling while gopls is running, or by faulty hardware (see issue |
| 95 | // #67433). In this case, terminating the application is likely the |
| 96 | // best course; see [GetOrFatal]. |
| 97 | // |
| 98 | // Each kind must be used with exactly one decoded type T; mixing types |
| 99 | // for the same kind is a programming error and will panic. |
| 100 | // The returned value may be shared with other callers and must not be |
| 101 | // mutated. |
| 102 | func Get[T any](kind string, key [32]byte, decode func([]byte) T) (T, error) { |
| 103 | var zero T |
| 104 | mk := memKey{kind, key} |
| 105 | |
| 106 | // First consult the read-through memory cache. |
| 107 | // Note that memory cache hits do not update the times |
| 108 | // used for LRU eviction of the file-based cache. |
| 109 | var data []byte |
| 110 | if v, ok := memCache.Get(mk); ok { |
| 111 | if t, ok := v.(T); ok { |
| 112 | return t, nil |
| 113 | } |
| 114 | // Set stores the encoded bytes, so a hit may hold []byte rather |
| 115 | // than T until the first Get decodes and upgrades the entry. |
| 116 | // Alternatively, we could pass an encoder to Set, but the |
| 117 | // asymmetry here ensures that we don't rely on the intrinsic |
| 118 | // identity of our encoded values. |
| 119 | if data, ok = v.([]byte); !ok { |
| 120 | // Entry holds a decoded value of a different type; each |
| 121 | // kind must be used with exactly one accessor. |
| 122 | panic(fmt.Sprintf("filecache: kind %q used with multiple decoded types (got %T, want %T)", kind, v, zero)) |
| 123 | } |
| 124 | } else { |
| 125 | var err error |
| 126 | if data, err = get(kind, key); err != nil { |
| 127 | return zero, err |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | result := decode(data) |
| 132 | memCache.Set(mk, result, len(data)) |
| 133 | return result, nil |
| 134 | } |
| 135 | |
| 136 | // GetOrFatal retrieves from the cache like [Get], but if it |
| 137 | // encounters an unrecoverable [ErrNoCache] error, it calls log.Fatal. |
| 138 | // Any unexpected error (not [ErrNotFound]) is logged. |
| 139 | func GetOrFatal[T any](kind string, key [32]byte, decode func([]byte) T) (T, bool) { |
| 140 | val, err := Get(kind, key, decode) |
| 141 | if err == nil { |
| 142 | return val, true // hit |
| 143 | } |
| 144 | if errNoCache, ok := errors.AsType[ErrNoCache](err); ok { |
| 145 | log.Fatal(errNoCache) // unrecoverable |
| 146 | } |
| 147 | if err != ErrNotFound { |
| 148 | log.Printf("unexpected error reading %s from filecache: %v", kind, err) |
| 149 | } |
| 150 | return *new(T), false // miss |
| 151 | } |
| 152 | |
| 153 | // get reads the value for (kind, key) from the file system, bypassing |
| 154 | // the in-memory cache. |
| 155 | func get(kind string, key [32]byte) ([]byte, error) { |
| 156 | iolimit <- struct{}{} // acquire a token |
| 157 | defer func() { <-iolimit }() // release a token |
| 158 | |
| 159 | // Read the index file, which provides the name of the CAS file. |
| 160 | indexName, err := filename(kind, key) |
| 161 | if err != nil { |
| 162 | return nil, err // (ErrNoCache) |
| 163 | } |
| 164 | indexData, err := os.ReadFile(indexName) |
| 165 | if err != nil { |
| 166 | if errors.Is(err, os.ErrNotExist) { |
| 167 | return nil, ErrNotFound |
| 168 | } |
| 169 | return nil, err |
| 170 | } |
| 171 | var valueHash [32]byte |
| 172 | if copy(valueHash[:], indexData) != len(valueHash) { |
| 173 | return nil, ErrNotFound // index entry has wrong length |
| 174 | } |
| 175 | |
| 176 | // Read the CAS file and check its contents match. |
| 177 | // |
| 178 | // This ensures integrity in all cases (corrupt or truncated |
| 179 | // file, short read, I/O error, wrong length, etc) except an |
| 180 | // engineered hash collision, which is infeasible. |
| 181 | casName, err := filename(casKind, valueHash) |
| 182 | if err != nil { |
| 183 | return nil, err // (ErrNoCache) |
| 184 | } |
| 185 | value, _ := os.ReadFile(casName) // ignore error |
| 186 | if sha256.Sum256(value) != valueHash { |
| 187 | return nil, ErrNotFound // CAS file is missing or has wrong contents |
| 188 | } |
| 189 | |
| 190 | // Update file times used by LRU eviction. |
| 191 | // |
| 192 | // Because this turns a read into a write operation, |
| 193 | // we follow the approach used in the go command's |
| 194 | // cache and update the access time only if the |
| 195 | // existing timestamp is older than one hour. |
| 196 | // |
| 197 | // (Traditionally the access time would be updated |
| 198 | // automatically, but for efficiency most POSIX systems have |
| 199 | // for many years set the noatime mount option to avoid every |
| 200 | // open or read operation entailing a metadata write.) |
| 201 | touch(indexName, casName) |
| 202 | |
| 203 | return value, nil |
| 204 | } |
| 205 | |
| 206 | // Set updates the value in the cache. |
| 207 | // |
| 208 | // Set may fail due to: |
| 209 | // - failure to access/create the cache (first call only); |
| 210 | // - out of space (ENOSPC); |
| 211 | // - deletion of the cache concurrent with a call to Set; |
| 212 | // - faulty hardware. |
| 213 | // See issue #67433. |
| 214 | func Set(kind string, key [32]byte, value []byte) error { |
| 215 | memCache.Set(memKey{kind, key}, value, len(value)) |
| 216 | |
| 217 | // Set the active event to wake up the GC. |
| 218 | select { |
| 219 | case active <- struct{}{}: |
| 220 | default: |
| 221 | } |
| 222 | |
| 223 | iolimit <- struct{}{} // acquire a token |
| 224 | defer func() { <-iolimit }() // release a token |
| 225 | |
| 226 | // First, add the value to the content- |
| 227 | // addressable store (CAS), if not present. |
| 228 | hash := sha256.Sum256(value) |
| 229 | casName, err := filename(casKind, hash) |
| 230 | if err != nil { |
| 231 | return err // (ErrNoCache) |
| 232 | } |
| 233 | // Does CAS file exist and have correct (complete) content? |
| 234 | // TODO(adonovan): opt: use mmap for this check. |
| 235 | if prev, _ := os.ReadFile(casName); !bytes.Equal(prev, value) { |
| 236 | if err := os.MkdirAll(filepath.Dir(casName), 0700); err != nil { |
| 237 | return err |
| 238 | } |
| 239 | // Avoiding O_TRUNC here is merely an optimization to avoid |
| 240 | // cache misses when two threads race to write the same file. |
| 241 | if err := writeFileNoTrunc(casName, value, 0600); err != nil { |
| 242 | os.Remove(casName) // ignore error |
| 243 | return err // e.g. disk full |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | // Now write an index entry that refers to the CAS file. |
| 248 | indexName, err := filename(kind, key) |
| 249 | if err != nil { |
| 250 | return err // (ErrNoCache) |
| 251 | } |
| 252 | if err := os.MkdirAll(filepath.Dir(indexName), 0700); err != nil { |
| 253 | return err // e.g. disk full |
| 254 | } |
| 255 | if err := writeFileNoTrunc(indexName, hash[:], 0600); err != nil { |
| 256 | os.Remove(indexName) // ignore error |
| 257 | return err // e.g. disk full |
| 258 | } |
| 259 | |
| 260 | // Update the CAS file's timestamp to prevent premature LRU eviction. |
| 261 | touch(casName) |
| 262 | |
| 263 | return nil |
| 264 | } |
| 265 | |
| 266 | func touch(filenames ...string) { |
| 267 | now := time.Now() |
| 268 | for _, filename := range filenames { |
| 269 | st, err := os.Stat(filename) |
| 270 | if err == nil && now.Sub(st.ModTime()) > time.Hour { |
| 271 | os.Chtimes(filename, now, now) // ignore error |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | // The active 1-channel is a selectable resettable event |
| 277 | // indicating recent cache activity. |
| 278 | var active = make(chan struct{}, 1) |
| 279 | |
| 280 | // writeFileNoTrunc is like os.WriteFile but doesn't truncate until |
| 281 | // after the write, so that racing writes of the same data are idempotent. |
| 282 | func writeFileNoTrunc(filename string, data []byte, perm os.FileMode) error { |
| 283 | f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, perm) |
| 284 | if err != nil { |
| 285 | return err |
| 286 | } |
| 287 | _, err = f.Write(data) |
| 288 | if err == nil { |
| 289 | err = f.Truncate(int64(len(data))) |
| 290 | } |
| 291 | if closeErr := f.Close(); err == nil { |
| 292 | err = closeErr |
| 293 | } |
| 294 | return err |
| 295 | } |
| 296 | |
| 297 | // reserved kind strings |
| 298 | const ( |
| 299 | casKind = "cas" // content-addressable store files |
| 300 | bugKind = "bug" // gopls bug reports |
| 301 | ) |
| 302 | |
| 303 | var iolimit = make(chan struct{}, 128) // counting semaphore to limit I/O concurrency in Set. |
| 304 | |
| 305 | var budget int64 = 1e9 // 1GB |
| 306 | |
| 307 | // SetBudget sets a soft limit on disk usage of regular files in the |
| 308 | // cache (in bytes) and returns the previous value. Supplying a |
| 309 | // negative value queries the current value without changing it. |
| 310 | // |
| 311 | // If two gopls processes have different budgets, the one with the |
| 312 | // lower budget will collect garbage more actively, but both will |
| 313 | // observe the effect. |
| 314 | // |
| 315 | // Even in the steady state, the storage usage reported by the 'du' |
| 316 | // command may exceed the budget by as much as a factor of 3 due to |
| 317 | // the overheads of directories and the effects of block quantization, |
| 318 | // which are especially pronounced for the small index files. |
| 319 | func SetBudget(new int64) (old int64) { |
| 320 | if new < 0 { |
| 321 | return atomic.LoadInt64(&budget) |
| 322 | } |
| 323 | return atomic.SwapInt64(&budget, new) |
| 324 | } |
| 325 | |
| 326 | // --- implementation ---- |
| 327 | |
| 328 | // filename returns the name of the cache file of the specified kind and key. |
| 329 | // |
| 330 | // A typical cache file has a name such as: |
| 331 | // |
| 332 | // $HOME/Library/Caches / gopls / VVVVVVVV / KK / KKKK...KKKK - kind |
| 333 | // |
| 334 | // The portions separated by spaces are as follows: |
| 335 | // - The user's preferred cache directory; the default value varies by OS. |
| 336 | // - The constant "gopls". |
| 337 | // - The "version", 32 bits of the digest of the gopls executable. |
| 338 | // - The first 8 bits of the key, to avoid huge directories. |
| 339 | // - The full 256 bits of the key. |
| 340 | // - The kind or purpose of this cache file (e.g. "analysis"). |
| 341 | // |
| 342 | // The kind establishes a namespace for the keys. It is represented as |
| 343 | // a suffix, not a segment, as this significantly reduces the number |
| 344 | // of directories created, and thus the storage overhead. |
| 345 | // |
| 346 | // Previous iterations of the design aimed for the invariant that once |
| 347 | // a file is written, its contents are never modified, though it may |
| 348 | // be atomically replaced or removed. However, not all platforms have |
| 349 | // an atomic rename operation (our first approach), and file locking |
| 350 | // (our second) is a notoriously fickle mechanism. |
| 351 | // |
| 352 | // The current design instead exploits a trick from the cache |
| 353 | // implementation used by the go command: writes of small files are in |
| 354 | // practice atomic (all or nothing) on all platforms. |
| 355 | // (See GOROOT/src/cmd/go/internal/cache/cache.go.) |
| 356 | // |
| 357 | // Russ Cox notes: "all file systems use an rwlock around every file |
| 358 | // system block, including data blocks, so any writes or reads within |
| 359 | // the same block are going to be handled atomically by the FS |
| 360 | // implementation without any need to request file locking explicitly. |
| 361 | // And since the files are so small, there's only one block. (A block |
| 362 | // is at minimum 512 bytes, usually much more.)" And: "all modern file |
| 363 | // systems protect against [partial writes due to power loss] with |
| 364 | // journals." |
| 365 | // |
| 366 | // We use a two-level scheme consisting of an index and a |
| 367 | // content-addressable store (CAS). A single cache entry consists of |
| 368 | // two files. The value of a cache entry is written into the file at |
| 369 | // filename("cas", sha256(value)). Since the value may be arbitrarily |
| 370 | // large, this write is not atomic. That means we must check the |
| 371 | // integrity of the contents read back from the CAS to make sure they |
| 372 | // hash to the expected key. If the CAS file is incomplete or |
| 373 | // inconsistent, we proceed as if it were missing. |
| 374 | // |
| 375 | // Once the CAS file has been written, we write a small fixed-size |
| 376 | // index file at filename(kind, key), using the values supplied by the |
| 377 | // caller. The index file contains the hash that identifies the value |
| 378 | // file in the CAS. (We could add extra metadata to this file, up to |
| 379 | // 512B, the minimum size of a disk block, if later desired, so long |
| 380 | // as the total size remains fixed.) Because the index file is small, |
| 381 | // concurrent writes to it are atomic in practice, even though this is |
| 382 | // not guaranteed by any OS. The fixed size ensures that readers can't |
| 383 | // see a palimpsest when a short new file overwrites a longer old one. |
| 384 | // |
| 385 | // New versions of gopls are free to reorganize the contents of the |
| 386 | // version directory as needs evolve. But all versions of gopls must |
| 387 | // in perpetuity treat the "gopls" directory in a common fashion. |
| 388 | // |
| 389 | // In particular, each gopls process attempts to garbage collect |
| 390 | // the entire gopls directory so that newer binaries can clean up |
| 391 | // after older ones: in the development cycle especially, new |
| 392 | // versions may be created frequently. |
| 393 | func filename(kind string, key [32]byte) (string, error) { |
| 394 | base := fmt.Sprintf("%x-%s", key, kind) |
| 395 | dir, err := getCacheDir() |
| 396 | if err != nil { |
| 397 | return "", err // (ErrNoCache) |
| 398 | } |
| 399 | // Keep the BugReports function consistent with this one. |
| 400 | return filepath.Join(dir, base[:2], base), nil |
| 401 | } |
| 402 | |
| 403 | // getCacheDir returns the persistent cache directory of all processes |
| 404 | // running this version of the gopls executable. |
| 405 | // |
| 406 | // It must incorporate the hash of the executable so that we needn't |
| 407 | // worry about incompatible changes to the file format or changes to |
| 408 | // the algorithm that produced the index. |
| 409 | func getCacheDir() (string, error) { |
| 410 | cacheDirOnce.Do(func() { |
| 411 | // Use user's preferred cache directory. |
| 412 | userDir := os.Getenv("GOPLSCACHE") |
| 413 | if userDir == "" { |
| 414 | var err error |
| 415 | userDir, err = os.UserCacheDir() |
| 416 | if err != nil { |
| 417 | userDir = os.TempDir() |
| 418 | } |
| 419 | } |
| 420 | goplsDir := filepath.Join(userDir, "gopls") |
| 421 | |
| 422 | // UserCacheDir may return a nonexistent directory |
| 423 | // (in which case we must create it, which may fail), |
| 424 | // or it may return a non-writable directory, in |
| 425 | // which case we should ideally respect the user's express |
| 426 | // wishes (e.g. XDG_CACHE_HOME) and not write somewhere else. |
| 427 | // Sadly UserCacheDir doesn't currently let us distinguish |
| 428 | // such intent from accidental misconfiguraton such as HOME=/ |
| 429 | // in a CI builder. So, we check whether the gopls subdirectory |
| 430 | // can be created (or already exists) and not fall back to /tmp. |
| 431 | // See also https://github.com/golang/go/issues/57638. |
| 432 | if os.MkdirAll(goplsDir, 0700) != nil { |
| 433 | goplsDir = filepath.Join(os.TempDir(), "gopls") |
| 434 | } |
| 435 | |
| 436 | // Start the garbage collector. |
| 437 | go gc(goplsDir) |
| 438 | |
| 439 | // Compute the hash of this executable (~20ms) and create a subdirectory. |
| 440 | hash, err := hashExecutable() |
| 441 | if err != nil { |
| 442 | cacheDirErr = ErrNoCache{fmt.Errorf("can't hash gopls executable: %w", err)} |
| 443 | } |
| 444 | // Use only 32 bits of the digest to avoid unwieldy filenames. |
| 445 | // It's not an adversarial situation. |
| 446 | cacheDir = filepath.Join(goplsDir, fmt.Sprintf("%x", hash[:4])) |
| 447 | if err := os.MkdirAll(cacheDir, 0700); err != nil { |
| 448 | cacheDirErr = ErrNoCache{fmt.Errorf("can't create cache: %w", err)} |
| 449 | } |
| 450 | }) |
| 451 | return cacheDir, cacheDirErr |
| 452 | } |
| 453 | |
| 454 | var ( |
| 455 | cacheDirOnce sync.Once |
| 456 | cacheDir string |
| 457 | cacheDirErr error |
| 458 | ) |
| 459 | |
| 460 | func hashExecutable() (hash [32]byte, err error) { |
| 461 | exe, err := os.Executable() |
| 462 | if err != nil { |
| 463 | return hash, err |
| 464 | } |
| 465 | f, err := os.Open(exe) |
| 466 | if err != nil { |
| 467 | return hash, err |
| 468 | } |
| 469 | defer f.Close() |
| 470 | h := sha256.New() |
| 471 | if _, err := io.Copy(h, f); err != nil { |
| 472 | return hash, fmt.Errorf("can't read executable: %w", err) |
| 473 | } |
| 474 | h.Sum(hash[:0]) |
| 475 | return hash, nil |
| 476 | } |
| 477 | |
| 478 | // gc runs forever, periodically deleting files from the gopls |
| 479 | // directory until the space budget is no longer exceeded, and also |
| 480 | // deleting files older than the maximum age, regardless of budget. |
| 481 | // |
| 482 | // One gopls process may delete garbage created by a different gopls |
| 483 | // process, possibly running a different version of gopls, possibly |
| 484 | // running concurrently. |
| 485 | func gc(goplsDir string) { |
| 486 | // period between collections |
| 487 | // |
| 488 | // Originally the period was always 1 minute, but this |
| 489 | // consumed 15% of a CPU core when idle (#61049). |
| 490 | // |
| 491 | // The reason for running collections even when idle is so |
| 492 | // that long lived gopls sessions eventually clean up the |
| 493 | // caches created by defunct executables. |
| 494 | const ( |
| 495 | minPeriod = 5 * time.Minute // when active |
| 496 | maxPeriod = 6 * time.Hour // when idle |
| 497 | ) |
| 498 | |
| 499 | // Sleep statDelay*batchSize between stats to smooth out I/O. |
| 500 | // |
| 501 | // The constants below were chosen using the following heuristics: |
| 502 | // - 1GB of filecache is on the order of ~100-200k files, in which case |
| 503 | // 100μs delay per file introduces 10-20s of additional walk time, |
| 504 | // less than the minPeriod. |
| 505 | // - Processing batches of stats at once is much more efficient than |
| 506 | // sleeping after every stat (due to OS optimizations). |
| 507 | const statDelay = 100 * time.Microsecond // average delay between stats, to smooth out I/O |
| 508 | const batchSize = 1000 // # of stats to process before sleeping |
| 509 | const maxAge = 5 * 24 * time.Hour // max time since last access before file is deleted |
| 510 | |
| 511 | // The macOS filesystem is strikingly slow, at least on some machines. |
| 512 | // /usr/bin/find achieves only about 25,000 stats per second |
| 513 | // at full speed (no pause between items), meaning a large |
| 514 | // cache may take several minutes to scan. |
| 515 | // |
| 516 | // (gopls' caches should never actually get this big in |
| 517 | // practice: the example mentioned above resulted from a bug |
| 518 | // that caused filecache to fail to delete any files.) |
| 519 | |
| 520 | const debug = false |
| 521 | |
| 522 | // Names of all directories found in first pass; nil thereafter. |
| 523 | dirs := make(map[string]bool) |
| 524 | |
| 525 | for { |
| 526 | // Wait unconditionally for the minimum period. |
| 527 | // We do this even on the first run so that tests |
| 528 | // don't (all) run the GC. |
| 529 | time.Sleep(minPeriod) |
| 530 | |
| 531 | // Enumerate all files in the cache. |
| 532 | type item struct { |
| 533 | path string |
| 534 | mtime time.Time |
| 535 | size int64 |
| 536 | } |
| 537 | var files []item |
| 538 | start := time.Now() |
| 539 | var total int64 // bytes |
| 540 | _ = filepath.Walk(goplsDir, func(path string, stat os.FileInfo, err error) error { |
| 541 | if err != nil { |
| 542 | return nil // ignore errors |
| 543 | } |
| 544 | if stat.IsDir() { |
| 545 | // Collect (potentially empty) directories. |
| 546 | if dirs != nil { |
| 547 | dirs[path] = true |
| 548 | } |
| 549 | } else { |
| 550 | // Unconditionally delete files we haven't used in ages. |
| 551 | age := time.Since(stat.ModTime()) |
| 552 | if age > maxAge { |
| 553 | if debug { |
| 554 | log.Printf("age: deleting stale file %s (%dB, age %v)", |
| 555 | path, stat.Size(), age) |
| 556 | } |
| 557 | os.Remove(path) // ignore error |
| 558 | } else { |
| 559 | files = append(files, item{path, stat.ModTime(), stat.Size()}) |
| 560 | total += stat.Size() |
| 561 | if debug && len(files)%1000 == 0 { |
| 562 | log.Printf("filecache: checked %d files in %v", len(files), time.Since(start)) |
| 563 | } |
| 564 | if len(files)%batchSize == 0 { |
| 565 | time.Sleep(batchSize * statDelay) |
| 566 | } |
| 567 | } |
| 568 | } |
| 569 | return nil |
| 570 | }) |
| 571 | |
| 572 | // Sort oldest files first. |
| 573 | sort.Slice(files, func(i, j int) bool { |
| 574 | return files[i].mtime.Before(files[j].mtime) |
| 575 | }) |
| 576 | |
| 577 | // Delete oldest files until we're under budget. |
| 578 | budget := atomic.LoadInt64(&budget) |
| 579 | for _, file := range files { |
| 580 | if total < budget { |
| 581 | break |
| 582 | } |
| 583 | if debug { |
| 584 | age := time.Since(file.mtime) |
| 585 | log.Printf("budget: deleting stale file %s (%dB, age %v)", |
| 586 | file.path, file.size, age) |
| 587 | } |
| 588 | os.Remove(file.path) // ignore error |
| 589 | total -= file.size |
| 590 | } |
| 591 | files = nil // release memory before sleep |
| 592 | |
| 593 | // Once only, delete all directories. |
| 594 | // This will succeed only for the empty ones, |
| 595 | // and ensures that stale directories (whose |
| 596 | // files have been deleted) are removed eventually. |
| 597 | // They don't take up much space but they do slow |
| 598 | // down the traversal. |
| 599 | // |
| 600 | // We do this after the sleep to minimize the |
| 601 | // race against Set, which may create a directory |
| 602 | // that is momentarily empty. |
| 603 | // |
| 604 | // (Test processes don't live that long, so |
| 605 | // this may not be reached on the CI builders.) |
| 606 | if dirs != nil { |
| 607 | dirnames := make([]string, 0, len(dirs)) |
| 608 | for dir := range dirs { |
| 609 | dirnames = append(dirnames, dir) |
| 610 | } |
| 611 | dirs = nil |
| 612 | |
| 613 | // Descending length order => children before parents. |
| 614 | sort.Slice(dirnames, func(i, j int) bool { |
| 615 | return len(dirnames[i]) > len(dirnames[j]) |
| 616 | }) |
| 617 | var deleted int |
| 618 | for _, dir := range dirnames { |
| 619 | if os.Remove(dir) == nil { // ignore error |
| 620 | deleted++ |
| 621 | } |
| 622 | } |
| 623 | if debug { |
| 624 | log.Printf("deleted %d empty directories", deleted) |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | // Wait up to the max period, |
| 629 | // or for Set activity in this process. |
| 630 | select { |
| 631 | case <-active: |
| 632 | case <-time.After(maxPeriod): |
| 633 | } |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | func init() { |
| 638 | // Register a handler to durably record this process's first |
| 639 | // assertion failure in the cache so that we can ask users to |
| 640 | // share this information via the stats command. |
| 641 | bug.Handle(func(bug bug.Bug) { |
| 642 | // Wait for cache init (bugs in tests happen early). |
| 643 | _, _ = getCacheDir() |
| 644 | |
| 645 | data, err := json.Marshal(bug) |
| 646 | if err != nil { |
| 647 | panic(fmt.Sprintf("error marshalling bug %+v: %v", bug, err)) |
| 648 | } |
| 649 | |
| 650 | key := sha256.Sum256(data) |
| 651 | _ = Set(bugKind, key, data) |
| 652 | }) |
| 653 | } |
| 654 | |
| 655 | // BugReports returns a new unordered array of the contents |
| 656 | // of all cached bug reports produced by this executable. |
| 657 | // It also returns the location of the cache directory |
| 658 | // used by this process (or "" on initialization error). |
| 659 | func BugReports() (string, []bug.Bug) { |
| 660 | // To test this logic, run: |
| 661 | // $ TEST_GOPLS_BUG=oops gopls bug # trigger a bug |
| 662 | // $ gopls stats # list the bugs |
| 663 | |
| 664 | dir, err := getCacheDir() |
| 665 | if err != nil { |
| 666 | return "", nil // ignore initialization errors |
| 667 | } |
| 668 | var result []bug.Bug |
| 669 | _ = filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error { |
| 670 | if err != nil { |
| 671 | return nil // ignore readdir/stat errors |
| 672 | } |
| 673 | // Parse the key from each "XXXX-bug" cache file name. |
| 674 | if !info.IsDir() && strings.HasSuffix(path, bugKind) { |
| 675 | var key [32]byte |
| 676 | n, err := hex.Decode(key[:], []byte(filepath.Base(path)[:len(key)*2])) |
| 677 | if err != nil || n != len(key) { |
| 678 | return nil // ignore malformed file names |
| 679 | } |
| 680 | content, err := Get(bugKind, key, Bytes) |
| 681 | if err == nil { // ignore read errors |
| 682 | var b bug.Bug |
| 683 | if err := json.Unmarshal(content, &b); err != nil { |
| 684 | log.Printf("error marshalling bug %q: %v", string(content), err) |
| 685 | } |
| 686 | result = append(result, b) |
| 687 | } |
| 688 | } |
| 689 | return nil |
| 690 | }) |
| 691 | return dir, result |
| 692 | } |