func()

in image/resources/knfsd-metrics-agent/internal/oldestfile/scraper.go [93:143]


func (s *oldestFileScraper) findOldestFile(ctx context.Context) (oldestFile, error) {
	// optimistic check if the oldest file from a previous scrape still exists
	if s.last.path != "" {
		stat, err := os.Stat(s.last.path)
		if err == nil && stat.ModTime() == s.last.mtime {
			// assume the file is still the oldest
			return s.last, nil
		}
	}

	count := 0
	found := oldestFile{}
	err := filepath.WalkDir(s.cachePath, func(path string, d fs.DirEntry, err error) error {
		// Avoiding checking the context on every single file. This is because
		// checking the context has to lock a mutex.
		// No heuristics for a good value here, so just chose 100 arbitrarily.
		count++
		if count > 100 {
			count = 0
			if err := ctx.Err(); err != nil {
				// abort walking the tree with the context's error
				return err
			}
		}

		if !d.Type().IsRegular() {
			return nil
		}

		info, err := d.Info()
		if err != nil {
			// if there's an error querying file, just skip the file
			return nil
		}

		mtime := info.ModTime()
		if mtime.IsZero() {
			return nil
		}

		if found.mtime.IsZero() || mtime.Before(found.mtime) {
			found = oldestFile{
				path:  path,
				mtime: mtime,
			}
		}

		return nil
	})
	return found, err
}