// useCached checks if downloadTime plus maxAge is before/after the current time.
// return true if the cached image should be used, false otherwise.
777661
func useCached(downloadTime time.Time, maxAge int) bool {
	freshnessLifetime := int(time.Now().Sub(downloadTime).Seconds())
	if maxAge > 0 && freshnessLifetime < maxAge {
		return true
	}
	return false
}
1200465
func cleanCacheDir() {
	dir := osutil.CacheDir()
	f, err := os.Open(dir)
	if err != nil {
		return
	}
	defer f.Close()
	fis, err := f.Readdir(-1)
	if err != nil {
		return
	}
	var haveCache, statCache []os.FileInfo
	seen := make(map[string]bool)
	for _, fi := range fis {
		seen[fi.Name()] = true
	}

	for _, fi := range fis {
		if strings.HasPrefix(fi.Name(), "pk-put.havecache.") {
			haveCache = append(haveCache, fi)
			continue
		}
		if strings.HasPrefix(fi.Name(), "pk-put.statcache.") {
			statCache = append(statCache, fi)
			continue
		}
	}
	for _, list := range [][]os.FileInfo{haveCache, statCache} {
		if len(list) <= 5 {
			continue
		}
		sort.Sort(byModtime(list))
		list = list[:len(list)-5]
		for _, fi := range list {
			if fi.ModTime().Before(time.Now().Add(-30 * 24 * time.Hour)) {
				os.RemoveAll(filepath.Join(dir, fi.Name()))
			}
		}
	}
}
1227010
func (d Docker) GetCachedImage(imgID string, cfg *container.Config) (string, error) {
	cache, err := d.Daemon.ImageGetCached(image.ID(imgID), cfg)
	if cache == nil || err != nil {
		return "", err
	}
	return cache.ID().String(), nil
}
542783
func DeleteFromImageCacheDir(images []string) error {
	for _, image := range images {
		path := filepath.Join(constants.ImageCacheDir, image)
		path = sanitizeCacheDir(path)
		glog.Infoln("Deleting image in cache at ", path)
		if err := os.Remove(path); err != nil {
			return err
		}
	}
	return cleanImageCacheDir()
}
1346958
func (e *Engine) compactCache() {
	t := time.NewTicker(time.Second)
	defer t.Stop()
	for {
		e.mu.RLock()
		quit := e.snapDone
		e.mu.RUnlock()

		select {
		case <-quit:
			return

		case <-t.C:
			e.Cache.UpdateAge()
			if e.ShouldCompactCache(time.Now()) {
				start := time.Now()
				e.traceLogger.Info("Compacting cache", zap.String("path", e.path))
				err := e.WriteSnapshot()
				if err != nil && err != errCompactionsDisabled {
					e.logger.Info("Error writing snapshot", zap.Error(err))
				}
				e.compactionTracker.SnapshotAttempted(err == nil || err == errCompactionsDisabled, time.Since(start))
			}
		}
	}
}
139703
func (cache *DiskBlockCacheLocal) checkCacheLocked(method string) error {
	select {
	case <-cache.startedCh:
	case <-cache.startErrCh:
		// The cache will never be started. No need for a stack here since this
		// could happen anywhere.
		return DiskCacheStartingError{method}
	default:
		// If the cache hasn't started yet, return an error.  No need for a
		// stack here since this could happen anywhere.
		return DiskCacheStartingError{method}
	}
	// shutdownCh has to be checked under lock, otherwise we can race.
	select {
	case <-cache.shutdownCh:
		return errors.WithStack(DiskCacheClosedError{method})
	default:
	}
	if cache.blockDb == nil {
		return errors.WithStack(DiskCacheClosedError{method})
	}
	return nil
}
478515
func Cached(listener func(*vecty.Event)) *vecty.EventListener {
	return &vecty.EventListener{Name: "cached", Listener: listener}
}
174938
func (e *Engine) ShouldCompactCache(t time.Time) bool {
	sz := e.Cache.Size()

	if sz == 0 {
		return false
	}

	if sz > e.CacheFlushMemorySizeThreshold {
		return true
	}

	return t.Sub(e.Cache.LastWriteTime()) > e.CacheFlushWriteColdDuration
}
371366
func (app *App) ServeDirNoCacheCustom(path string, stripSlashes int, compress bool, generateIndexPages bool, indexNames []string) func(*Context) {
	if indexNames == nil {
		indexNames = []string{}
	}
	fs := &fasthttp.FS{
		Root:                 path,
		IndexNames:           indexNames,
		GenerateIndexPages:   generateIndexPages,
		Compress:             compress,
		CacheDuration:        time.Millisecond,
		CompressedFileSuffix: ".gz",
	}

	if stripSlashes > 0 {
		fs.PathRewrite = fasthttp.NewPathSlashesStripper(stripSlashes)
	}

	h := fs.NewRequestHandler()
	pragmaH := "Pragma"
	pragmaV := "no-cache"
	expiresH := "Expires"
	expiresV := "0"
	ccH := "Cache-Control"
	ccV := "no-cache, no-store, must-revalidate"
	return func(ctx *Context) {
		ctx.Response.Header.Add(pragmaH, pragmaV)
		ctx.Response.Header.Add(expiresH, expiresV)
		ctx.Response.Header.Add(ccH, ccV)
		h(ctx.RequestCtx)
	}
}
880038
func (s *AccountAttribute) SetUsed(v int64) *AccountAttribute {
	s.Used = &v
	return s
}
358118
func (b *Bundler) ClearCache() (err error) {
	// Remove cache folder
	astilog.Debugf("Removing %s", b.pathCache)
	if err = os.RemoveAll(b.pathCache); err != nil {
		err = errors.Wrapf(err, "removing %s failed", b.pathCache)
		return
	}
	return
}
560990
func (h *HTTPBin) Cache(w http.ResponseWriter, r *http.Request) {
	if r.Header.Get("If-Modified-Since") != "" || r.Header.Get("If-None-Match") != "" {
		w.WriteHeader(http.StatusNotModified)
		return
	}

	lastModified := time.Now().Format(time.RFC1123)
	w.Header().Add("Last-Modified", lastModified)
	w.Header().Add("ETag", sha1hash(lastModified))
	h.Get(w, r)
}
1224136
func NewCache(maxSize uint64) *Cache {
	return &Cache{
		maxSize:      maxSize,
		store:        newRing(),
		lastSnapshot: time.Now(),
		tracker:      newCacheTracker(newCacheMetrics(nil), nil),
	}
}
753684
func (s *AccountQuota) SetUsed(v int64) *AccountQuota {
	s.Used = &v
	return s
}
863345
func RequestCache(c context.Context) *lru.Cache {
	rc, _ := c.Value(&requestCacheKey).(*lru.Cache)
	if rc == nil {
		panic("server/caching: no request cache installed in Context")
	}
	return rc
}
809048
func (cfs *cacheFSObjects) diskUsageHigh() bool {
	di, err := disk.GetInfo(cfs.dir)
	if err != nil {
		reqInfo := (&logger.ReqInfo{}).AppendTags("cachePath", cfs.dir)
		ctx := logger.SetReqInfo(context.Background(), reqInfo)
		logger.LogIf(ctx, err)
		return true
	}
	usedPercent := (di.Total - di.Free) * 100 / di.Total
	return int(usedPercent) > cfs.maxDiskUsagePct
}
74509
func (cache *DiskQuotaCacheLocal) checkCacheLocked(
	ctx context.Context, method string) error {
	// First see if the context has expired since we began.
	select {
	case <-ctx.Done():
		return ctx.Err()
	default:
	}

	select {
	case <-cache.startedCh:
	case <-cache.startErrCh:
		// The cache will never be started. No need for a stack here since this
		// could happen anywhere.
		return DiskCacheStartingError{method}
	default:
		// If the cache hasn't started yet, return an error.  No need for a
		// stack here since this could happen anywhere.
		return DiskCacheStartingError{method}
	}
	// shutdownCh has to be checked under lock, otherwise we can race.
	select {
	case <-cache.shutdownCh:
		return errors.WithStack(DiskCacheClosedError{method})
	default:
	}
	if cache.db == nil {
		return errors.WithStack(DiskCacheClosedError{method})
	}
	return nil
}