// Evictions returns the eviction count.
975091
func (lru *LRUCache) Evictions() int64 {
	lru.mu.Lock()
	defer lru.mu.Unlock()
	return lru.evictions
}
349623
func (s *Snapshot) ConfigEntries() ([]structs.ConfigEntry, error) {
	entries, err := s.tx.Get(configTableName, "id")
	if err != nil {
		return nil, err
	}

	var ret []structs.ConfigEntry
	for wrapped := entries.Next(); wrapped != nil; wrapped = entries.Next() {
		ret = append(ret, wrapped.(structs.ConfigEntry))
	}

	return ret, nil
}
1085360
func (m *Migrator) Migrations(status int) []*Migration {
	// Sort all migration ids.
	ids := make([]uint64, 0)
	for id, _ := range m.migrations {
		ids = append(ids, id)
	}
	sort.Sort(uint64slice(ids))

	// Find ids for the given status.
	migrations := make([]*Migration, 0)
	for _, id := range ids {
		migration := m.migrations[id]
		if status == -1 || migration.Status == status {
			migrations = append(migrations, migration)
		}
	}
	return migrations
}
89663
func cmdMounts(mounts []*drivers.MountConfig) []*lconfigs.Mount {
	if len(mounts) == 0 {
		return nil
	}

	r := make([]*lconfigs.Mount, len(mounts))

	for i, m := range mounts {
		flags := unix.MS_BIND
		if m.Readonly {
			flags |= unix.MS_RDONLY
		}
		r[i] = &lconfigs.Mount{
			Source:      m.HostPath,
			Destination: m.TaskPath,
			Device:      "bind",
			Flags:       flags,
		}
	}

	return r
}
37737
func (r *Resident) cleanupWorkers() error {
	var errs []string
	for id, w := range r.workers {
		if err := worker.Stop(w); err != nil {
			errs = append(errs, errors.Annotatef(err, "worker %d", id).Error())
		}
	}

	if len(errs) != 0 {
		return errors.Errorf("worker cleanup errors:\n\t%s", strings.Join(errs, "\n\t"))
	}
	return nil
}
216032
func (s *Store) EvictMaxSize(maxCacheSizeBytes int64) (stats EvictStats, err error) {
	isZip := func(fi os.FileInfo) bool {
		return strings.HasSuffix(fi.Name(), ".zip")
	}

	list, err := ioutil.ReadDir(s.Dir)
	if err != nil {
		if os.IsNotExist(err) {
			return EvictStats{
				CacheSize: 0,
				Evicted:   0,
			}, nil
		}
		return stats, errors.Wrapf(err, "failed to ReadDir %s", s.Dir)
	}

	// Sum up the total size of all zips
	var size int64
	for _, fi := range list {
		if isZip(fi) {
			size += fi.Size()
		}
	}
	stats.CacheSize = size

	// Nothing to evict
	if size <= maxCacheSizeBytes {
		return stats, nil
	}

	// Keep removing files until we are under the cache size. Remove the
	// oldest first.
	sort.Slice(list, func(i, j int) bool {
		return list[i].ModTime().Before(list[j].ModTime())
	})
	for _, fi := range list {
		if size <= maxCacheSizeBytes {
			break
		}
		if !isZip(fi) {
			continue
		}
		path := filepath.Join(s.Dir, fi.Name())
		if s.BeforeEvict != nil {
			s.BeforeEvict(path)
		}
		err = os.Remove(path)
		if err != nil {
			log.Printf("failed to remove %s: %s", path, err)
			continue
		}
		stats.Evicted++
		size -= fi.Size()
	}

	return stats, nil
}
497112
func (s *BatchServiceStateManager) ScheduleServices(svcs []*service.Service, tenantID string, desiredState service.DesiredState, emergency bool) error {
	logger := plog.WithFields(logrus.Fields{
		"servicecount": len(svcs),
		"tenantid":     tenantID,
		"desiredstate": desiredState.String(),
		"emergency":    emergency,
	})

	var err error
	logger.Debug("Scheduling services")
	s.lock.Lock()
	var queues map[service.DesiredState]*ServiceStateQueue
	queues, ok := s.TenantQueues[tenantID]

	if !ok {
		s.lock.Unlock()
		return ErrBadTenantID
	}

	// Get a lock on all queues
	for _, q := range queues {
		q.lock.Lock()
		defer q.lock.Unlock()
	}
	s.lock.Unlock()
	// Build the cancellable services from the list
	cancellableServices := make(map[string]*CancellableService)
	for _, svc := range svcs {
		cancellableServices[svc.ID] = NewCancellableService(svc)
	}

	// Merge with oldBatch batchQueue
	// 1. If this is emergency, merge with other emergencies and move to front of the queue
	// 2. If any service in this batch is currently in the "pending" batch:
	//    A. If the desired states are the same, leave it pending and remove it from this batch
	//    B. If the desired states are different, cancel waits on the pending request and leave it in this batch
	// 3. If this and the last N batches at the end of the queue all have the same desired state, merge and re-group them
	// 4. If any service in this batch also appears in an earlier batch:
	//    A. If the desired state is the same, leave it in the earlier batch and remove it here
	//    B. If the desired state is different, delete it from the earlier batch and leave it in the new one
	newBatch := ServiceStateChangeBatch{
		Services:     cancellableServices,
		DesiredState: desiredState,
		Emergency:    emergency,
	}
	var expeditedBatch ServiceStateChangeBatch
	expeditedServices := make(map[string]*CancellableService)
	var cancelledIDs []string
	for _, queue := range queues {
		// reconcile the new batch against all batches in q
		var cancelled []string
		newBatch, expeditedBatch, cancelled = queue.reconcileWithBatchQueue(newBatch)
		cancelledIDs = append(cancelledIDs, cancelled...)
		for id, svc := range expeditedBatch.Services {
			expeditedServices[id] = svc
		}

		if len(newBatch.Services) == 0 {
			// Nothing left to reconcile
			break
		}

		// reconcile with the pending batch
		newBatch = queue.reconcileWithPendingBatch(newBatch)
	}

	// Now check for services that are already in the desired state
	var cancelled []string
	newBatch, cancelled = s.reconcileWithCurrentState(newBatch)
	cancelledIDs = append(cancelledIDs, cancelled...)

	if len(cancelledIDs) > 0 {
		// Spawn a goroutine to update the current state of all cancelled services
		defer func() {
			logger.WithField("services", cancelledIDs).Debug("Cancelling and re-syncing services")
			go s.SyncCurrentStates(cancelledIDs)
		}()
	}

	expeditedBatch.Services = expeditedServices

	if len(expeditedBatch.Services) > 0 {
		// process the expedited batch now
		go func() {
			s.updateBatch(&expeditedBatch)
			failed := s.processBatch(tenantID, expeditedBatch)
			// Cancel these services to notify waiters that they have been scheduled
			for _, svc := range expeditedBatch.Services {
				svc.Cancel()
			}
			if len(failed) > 0 {
				s.SyncCurrentStates(failed)
			}
		}()
	}

	if len(newBatch.Services) == 0 {
		return nil
	}

	queueDesiredState := newBatch.DesiredState
	switch newBatch.DesiredState {
	case service.SVCRestart:
		queueDesiredState = service.SVCRun
	case service.SVCPause:
		queueDesiredState = service.SVCStop
	}

	// Merge this into the queue
	queue, ok := queues[queueDesiredState]
	if !ok {
		return ErrMissingQueue
	}

	if newBatch.Emergency {
		err = queue.mergeEmergencyBatch(newBatch)
	} else {
		err = queue.mergeBatch(newBatch)
	}

	// Set pending desired state
	currentState := service.DesiredToCurrentPendingState(newBatch.DesiredState, newBatch.Emergency)
	var sids []string
	for sid := range newBatch.Services {
		sids = append(sids, sid)
	}
	s.currentStateLock.Lock()
	s.updateServiceCurrentState(currentState, sids...)
	s.currentStateLock.Unlock()

	// Signal update or exit
	select {
	case queue.Changed <- true:
	default:
	}

	return err
}
318517
func parseThresholdStatements(statements map[string]string) ([]evictionapi.Threshold, error) {
	if len(statements) == 0 {
		return nil, nil
	}
	results := []evictionapi.Threshold{}
	for signal, val := range statements {
		result, err := parseThresholdStatement(evictionapi.Signal(signal), val)
		if err != nil {
			return nil, err
		}
		if result != nil {
			results = append(results, *result)
		}
	}
	return results, nil
}
537843
func (m *LocalDatasetShardsManager) purgeExpiredEntries() {
	for {
		func() {
			m.Lock()
			cutoverLimit := time.Now().Add(-24 * time.Hour)
			var oldShardNames []string
			for name, ds := range m.name2Store {
				if ds.LastWriteAt().Before(cutoverLimit) && ds.LastReadAt().Before(cutoverLimit) {
					println("purging dataset", name, "last write:", ds.LastWriteAt().String(), "last read:", ds.LastReadAt().String())
					oldShardNames = append(oldShardNames, name)
				}
			}
			for _, name := range oldShardNames {
				m.doDelete(name)
			}
			m.Unlock()
			time.Sleep(1 * time.Hour)
		}()
	}
}
163545
func thresholdsMetGracePeriod(observedAt thresholdsObservedAt, now time.Time) []evictionapi.Threshold {
	results := []evictionapi.Threshold{}
	for threshold, at := range observedAt {
		duration := now.Sub(at)
		if duration < threshold.GracePeriod {
			klog.V(2).Infof("eviction manager: eviction criteria not yet met for %v, duration: %v", formatThreshold(threshold), duration)
			continue
		}
		results = append(results, threshold)
	}
	return results
}
1014076
func (e *Events) Evict(l chan interface{}) {
	eventSubscribers.Dec()
	e.pub.Evict(l)
}
447819
func (c *Client) Tenants(o ...Modifier) ([]*TenantDefinition, error) {
	o = prepend(o, c.URL("GET", TenantEndpoint()), AdminAuthentication(c.AdminToken))

	r, err := c.Send(o...)
	if err != nil {
		return nil, err
	}

	defer r.Body.Close()

	if r.StatusCode == http.StatusOK {
		b, err := ioutil.ReadAll(r.Body)
		if err != nil {
			return nil, err
		}
		tenants := []*TenantDefinition{}
		if b != nil {
			if err = json.Unmarshal(b, &tenants); err != nil {
				return nil, err
			}
		}
		return tenants, err
	} else if r.StatusCode > 399 {
		return nil, c.parseErrorResponse(r)
	}

	return nil, nil
}
815982
func (d *Dispatcher) Inbounds() Inbounds {
	inbounds := make(Inbounds, len(d.inbounds))
	copy(inbounds, d.inbounds)
	return inbounds
}
1362137
func (b *Broker) DeleteRecords(request *DeleteRecordsRequest) (*DeleteRecordsResponse, error) {
	response := new(DeleteRecordsResponse)

	err := b.sendAndReceive(request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}
515430
func (f *FSM) filteredLeases(getLocalTime func() time.Time, keys []lease.Key) map[lease.Key]lease.Info {
	results := make(map[lease.Key]lease.Info)
	f.mu.Lock()
	localTime := getLocalTime()
	for _, key := range keys {
		entries, found := f.getGroup(key)
		if !found {
			continue
		}
		if entry, ok := entries[key]; ok {
			results[key] = f.infoFromEntry(localTime, key, entry)
		}
	}
	f.mu.Unlock()
	return results
}
957036
func (sa *StorageAuthority) CountOrders(_ context.Context, _ int64, _, _ time.Time) (int, error) {
	return 0, nil
}
979944
func (s evictionNamespaceLister) List(selector labels.Selector) (ret []*v1beta1.Eviction, err error) {
	err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
		ret = append(ret, m.(*v1beta1.Eviction))
	})
	return ret, err
}