// SessionGC clean expired session stores in memory session
173486
func (pder *MemProvider) SessionGC() {
	pder.lock.RLock()
	for {
		element := pder.list.Back()
		if element == nil {
			break
		}
		if (element.Value.(*MemSessionStore).timeAccessed.Unix() + pder.maxlifetime) < time.Now().Unix() {
			pder.lock.RUnlock()
			pder.lock.Lock()
			pder.list.Remove(element)
			delete(pder.sessions, element.Value.(*MemSessionStore).sid)
			pder.lock.Unlock()
			pder.lock.RLock()
		} else {
			break
		}
	}
	pder.lock.RUnlock()
}
538199
func ForceGC() {
	fmt.Printf("Flushing global caches\n")
	kbCtx.FlushCaches()
	fmt.Printf("Done flushing global caches\n")

	fmt.Printf("Starting force gc\n")
	debug.FreeOSMemory()
	fmt.Printf("Done force gc\n")
}
826807
func (ec *Cache) Cleaner(d time.Duration) {

	for {
		cleanerSleep(d)

		now := timeNow()
		ec.Lock()

		// We could potentially be holding this lock for a long time,
		// but since we keep the cache expiration times small, we
		// expect only a small number of elements here to loop over

		for i := 0; i < len(ec.keys); i++ {
			k := ec.keys[i]
			v := ec.cache[k]
			if v.validUntil.Before(now) {
				ec.totalSize -= v.size
				delete(ec.cache, k)

				ec.keys[i] = ec.keys[len(ec.keys)-1]
				ec.keys = ec.keys[:len(ec.keys)-1]
				i-- // so we reprocess this index
			}
		}

		ec.Unlock()
		cleanerDone()
	}
}
420365
func (db *PGStore) Cleanup(interval time.Duration) (chan<- struct{}, <-chan struct{}) {
	if interval <= 0 {
		interval = defaultInterval
	}

	quit, done := make(chan struct{}), make(chan struct{})
	go db.cleanup(interval, quit, done)
	return quit, done
}
526604
func (s Session) SessionTimeoutExpiredOrMissing() bool {
	if exp, present := s[TimestampKey]; !present {
		return true
	} else if exp == SessionValueName {
		return false
	} else if expInt, _ := strconv.Atoi(exp.(string)); int64(expInt) < time.Now().Unix() {
		return true
	}
	return false
}
775693
func checkSessionClearSyntax(ctx *cli.Context) {
	if len(ctx.Args()) == 0 || len(ctx.Args()) > 2 {
		cli.ShowCommandHelpAndExit(ctx, "clear", 1) // last argument is exit code
	}
}
14133
func (st *CookieSessionStore) Flush() {
	st.lock.Lock()
	defer st.lock.Unlock()
	st.values = make(map[interface{}]interface{})
}
214280
func (s *inMemStore) sessCleaner(interval time.Duration) {
	ticker := time.NewTicker(interval)

	for {
		select {
		case <-s.closeTicker:
			// We are being shut down...
			ticker.Stop()
			return
		case now := <-ticker.C:
			// Do a sweep.
			// Remove is very rare compared to the number of checks, so:
			// "Quick" check with read-lock to see if there's anything to remove:
			// Note: Session.Access() is called with s.mux, the same mutex we use
			// when looking for timed-out sessions, so we're good.
			needRemove := func() bool {
				s.mux.RLock() // Read lock is enough
				defer s.mux.RUnlock()

				for _, sess := range s.sessions {
					if now.Sub(sess.Accessed()) > sess.Timeout() {
						return true
					}
				}
				return false
			}()
			if !needRemove {
				continue
			}

			// Remove required:
			func() {
				s.mux.Lock() // Read-write lock required
				defer s.mux.Unlock()

				for _, sess := range s.sessions {
					if now.Sub(sess.Accessed()) > sess.Timeout() {
						s.logPrintln("Session timed out:", sess.ID())
						delete(s.sessions, sess.ID())
					}
				}
			}()
		}
	}
}
157247
func (db *PGStore) deleteExpired() error {
	_, err := db.DbPool.Exec("DELETE FROM http_sessions WHERE expires_on < now()")
	return err
}
11681
func (fp *FileProvider) SessionRegenerate(oldsid, sid string) (Store, error) {
	filepder.lock.Lock()
	defer filepder.lock.Unlock()

	err := os.MkdirAll(path.Join(fp.savePath, string(oldsid[0]), string(oldsid[1])), 0777)
	if err != nil {
		SLogger.Println(err.Error())
	}
	err = os.MkdirAll(path.Join(fp.savePath, string(sid[0]), string(sid[1])), 0777)
	if err != nil {
		SLogger.Println(err.Error())
	}
	_, err = os.Stat(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
	var newf *os.File
	if err == nil {
		return nil, errors.New("newsid exist")
	} else if os.IsNotExist(err) {
		newf, err = os.Create(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
	}

	_, err = os.Stat(path.Join(fp.savePath, string(oldsid[0]), string(oldsid[1]), oldsid))
	var f *os.File
	if err == nil {
		f, err = os.OpenFile(path.Join(fp.savePath, string(oldsid[0]), string(oldsid[1]), oldsid), os.O_RDWR, 0777)
		io.Copy(newf, f)
	} else if os.IsNotExist(err) {
		newf, err = os.Create(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
	} else {
		return nil, err
	}
	f.Close()
	os.Remove(path.Join(fp.savePath, string(oldsid[0]), string(oldsid[1])))
	os.Chtimes(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid), time.Now(), time.Now())
	var kv map[interface{}]interface{}
	b, err := ioutil.ReadAll(newf)
	if err != nil {
		return nil, err
	}
	if len(b) == 0 {
		kv = make(map[interface{}]interface{})
	} else {
		kv, err = DecodeGob(b)
		if err != nil {
			return nil, err
		}
	}
	ss := &FileSessionStore{sid: sid, values: kv}
	return ss, nil
}
1192915
func (s *Server) GC() error {
	leases, err := s.leasePool.GetLeases()
	if err != nil {
		return err
	}

	for i := range leases {
		if leases[i].Status != leasepool.Free {
			//Lease Is Not Free

			if time.Now().After(leases[i].Expiry) {
				//Lease has expired.
				leases[i].Status = leasepool.Free
				updated, err := s.leasePool.UpdateLease(leases[i])
				if err != nil {
					log.Printf("Warning: Error trying to Free Lease %s \"%v\"\n", leases[i].IP.To4().String(), err)
				}
				if !updated {
					log.Printf("Warning: Unable to Free Lease %s\n", leases[i].IP.To4().String())
				}
				continue
			}
		}
	}
	return nil
}
774644
func clearSession(sid string, isForce bool) {
	var toRemove []string
	if sid == "all" {
		toRemove = getSessionIDs()
	} else {
		toRemove = append(toRemove, sid)
	}
	for _, sid := range toRemove {
		session, err := loadSessionV8(sid)
		if !isForce {
			fatalIf(err.Trace(sid), "Unable to load session `"+sid+"`. Use --force flag to remove obsolete session files.")

			fatalIf(session.Delete().Trace(sid), "Unable to remove session `"+sid+"`. Use --force flag to remove obsolete session files.")

			printMsg(clearSessionMessage{Status: "success", SessionID: sid})
			continue
		}
		// Forced removal of a session.
		forceClear(sid, session)
	}
	return
}
660993
func (cache *Cache) Clean() {
	now := time.Now().UnixNano()

	cache.mutex.Lock()
	for key, counter := range cache.counters {
		if now > counter.Expiration {
			delete(cache.counters, key)
		}
	}
	cache.mutex.Unlock()
}
1323171
func (a *Allocator) RunGC() error {
	// fetch list of all /id/ keys
	allocated, err := kvstore.ListPrefix(a.idPrefix)
	if err != nil {
		return fmt.Errorf("list failed: %s", err)
	}

	// iterate over /id/
	for key, v := range allocated {
		// if a.lockless {
		// FIXME: Add DeleteOnZeroCount support
		// }

		lock, err := a.lockPath(context.Background(), key)
		if err != nil {
			log.WithError(err).WithField(fieldKey, key).Warning("allocator garbage collector was unable to lock key")
			continue
		}

		// fetch list of all /value/<key> keys
		valueKeyPrefix := path.Join(a.valuePrefix, string(v))
		uses, err := kvstore.ListPrefix(valueKeyPrefix)
		if err != nil {
			log.WithError(err).WithField(fieldPrefix, valueKeyPrefix).Warning("allocator garbage collector was unable to list keys")
			lock.Unlock()
			continue
		}

		// if ID has no user, delete it
		if len(uses) == 0 {
			scopedLog := log.WithFields(logrus.Fields{
				fieldKey: key,
				fieldID:  path.Base(key),
			})
			if err := kvstore.Delete(key); err != nil {
				scopedLog.WithError(err).Warning("Unable to delete unused allocator master key")
			} else {
				scopedLog.Info("Deleted unused allocator master key")
			}
		}

		lock.Unlock()
	}

	return nil
}
764294
func (d *DiskStorer) Clean() {
	t := time.Now().UTC()

	files, err := ioutil.ReadDir(d.folderPath)

	if err != nil {
		panic(err)
	}

	for _, file := range files {
		tspec := times.Get(file)

		// File is expired
		if tspec.AccessTime().UTC().UTC().Add(d.maxAge).Before(t) {
			filePath := path.Join(d.folderPath, file.Name())

			d.mut.Lock()
			_, err := os.Stat(filePath)
			// If the file has been deleted manually from the server
			// in between the time we read the directory and now, it will
			// fail here with a ErrNotExist. If so, continue gracefully.
			// It would be innefficient to hold a lock for the duration of
			// the loop, so we only lock when we find an expired file.
			if os.IsNotExist(err) {
				d.mut.Unlock()
				continue
			} else if err != nil {
				panic(err)
			}

			err = os.Remove(filePath)
			d.mut.Unlock()
			if err != nil {
				panic(err)
			}
		}
	}
}
572080
func (t *TombstoneGC) purgeBin(expires time.Time) uint64 {
	t.Lock()
	defer t.Unlock()

	// Get the maximum index and clear the entry. It's possible that the GC
	// has been shut down while this timer fired and got blocked on the lock,
	// so if there's nothing in the map for us we just exit out since there
	// is no work to do.
	exp, ok := t.expires[expires]
	if !ok {
		return 0
	}
	delete(t.expires, expires)
	return exp.maxIndex
}
595100
func MountGC(path, uuid string) error {
	err := common.ChrootPrivateUnmount(path, log, debug)
	if err != nil {
		return errwrap.Wrap(fmt.Errorf("error cleaning mounts for pod %s", uuid), err)
	}
	return nil
}