// Prune prunes series from the index if they have become stale per their index-rule
486623
func (m *UnpartitionedMemoryIdx) Prune(now time.Time) ([]idx.Archive, error) {
	log.Info("memory-idx: start pruning of series across all orgs")
	orgs := make(map[uint32]struct{})
	m.RLock()
	for org := range m.tree {
		orgs[org] = struct{}{}
	}
	if TagSupport {
		for org := range m.tags {
			orgs[org] = struct{}{}
		}
	}
	m.RUnlock()

	var pruned []idx.Archive
	toPruneUntagged := make(map[uint32]map[string]struct{}, len(orgs))
	toPruneTagged := make(map[uint32]IdSet, len(orgs))
	for org := range orgs {
		toPruneTagged[org] = make(IdSet)
		toPruneUntagged[org] = make(map[string]struct{})
	}
	pre := time.Now()

	// getting all cutoffs once saves having to recompute everytime we have a match
	cutoffs := IndexRules.Cutoffs(now)

	m.RLock()

DEFS:
	for _, def := range m.defById {
		cutoff := cutoffs[def.IrId]
		if atomic.LoadInt64(&def.LastUpdate) >= cutoff {
			continue DEFS
		}

		if len(def.Tags) == 0 {
			tree, ok := m.tree[def.OrgId]
			if !ok {
				continue DEFS
			}

			n, ok := tree.Items[def.Name]
			if !ok || !n.Leaf() {
				continue DEFS
			}

			for _, id := range n.Defs {
				if atomic.LoadInt64(&m.defById[id].LastUpdate) >= cutoff {
					continue DEFS
				}
			}

			toPruneUntagged[def.OrgId][n.Path] = struct{}{}
		} else {
			defs := m.defByTagSet.defs(def.OrgId, def.NameWithTags())
			// if any other MetricDef with the same tag set is not expired yet,
			// then we do not want to prune any of them
			for def := range defs {
				if atomic.LoadInt64(&def.LastUpdate) >= cutoff {
					continue DEFS
				}
			}

			for def := range defs {
				toPruneTagged[def.OrgId][def.Id] = struct{}{}
			}
		}
	}
	m.RUnlock()

	// create a new timeLimiter that allows us to limit the amount of time we spend
	// holding a lock to maxPruneLockTime (default 100ms) every second.
	tl := NewTimeLimiter(time.Second, maxPruneLockTime, time.Now())

	for org, ids := range toPruneTagged {
		if len(ids) == 0 {
			continue
		}
		// make sure we are not locking for too long.
		tl.Wait()
		lockStart := time.Now()
		m.Lock()
		defs := m.deleteTaggedByIdSet(org, ids)
		m.Unlock()
		tl.Add(time.Since(lockStart))
		pruned = append(pruned, defs...)
	}

ORGS:
	for org, paths := range toPruneUntagged {
		if len(paths) == 0 {
			continue
		}

		for path := range paths {
			tl.Wait()
			lockStart := time.Now()
			m.Lock()
			tree, ok := m.tree[org]

			if !ok {
				m.Unlock()
				tl.Add(time.Since(lockStart))
				continue ORGS
			}

			n, ok := tree.Items[path]

			if !ok {
				m.Unlock()
				tl.Add(time.Since(lockStart))
				log.Debugf("memory-idx: series %s for orgId:%d was identified for pruning but cannot be found.", path, org)
				continue
			}

			log.Debugf("memory-idx: series %s for orgId:%d is stale. pruning it.", n.Path, org)
			defs := m.delete(org, n, true, false)
			m.Unlock()
			tl.Add(time.Since(lockStart))
			pruned = append(pruned, defs...)
		}
		if m.findCache != nil {
			if len(paths) > findCacheInvalidateQueueSize {
				m.findCache.Purge(org)
			} else {
				for path := range paths {
					m.findCache.InvalidateFor(org, path)
				}
			}
		}
	}

	statMetricsActive.Set(len(m.defById))

	duration := time.Since(pre)
	log.Infof("memory-idx: finished pruning of %d series in %s", len(pruned), duration)

	statPruneDuration.Value(duration)
	return pruned, nil
}
540411
func (p *Update) PruneColumns(parentUsedCols []*expression.Column) {
	p.baseLogicalPlan.PruneColumns(p.GetChildByIndex(0).GetSchema().Columns)
}
504614
func (pq *BlockPriorityQueue) RemoveIndex(idx int) {
	removedHeight := pq.bh[idx].height
	heap.Remove(pq, idx)
	pq.RescanMinMaxForRemove(removedHeight)
}
169519
func (p *LinuxResourcePool) pruneEntry(id string) {
	pLog := p.logger.Session("prune", lager.Data{"id": id})

	pLog.Info("prune")

	err := p.releaseSystemResources(pLog, id)
	if err != nil {
		pLog.Error("release-system-resources-error", err)
	}

	pLog.Info("end of prune")
}
548857
func (la *LogicalApply) PruneColumns(parentUsedCols []*expression.Column) error {
	leftCols, rightCols := la.extractUsedCols(parentUsedCols)

	err := la.children[1].PruneColumns(rightCols)
	if err != nil {
		return err
	}

	la.corCols = extractCorColumnsBySchema(la.children[1], la.children[0].Schema())
	for _, col := range la.corCols {
		leftCols = append(leftCols, &col.Column)
	}

	err = la.children[0].PruneColumns(leftCols)
	if err != nil {
		return err
	}

	la.mergeSchema()
	return nil
}
964892
func (s *Store) Prune(ctx context.Context, prefix string) error {
	prefix = s.prefix + prefix
	out.Debug(ctx, "consul.Prune(%s)", prefix)
	return s.Delete(ctx, prefix)
}
386993
func (g *MutableDirectedGraph) PruneOrphans() []*Node {
	removed := []*Node{}

	for _, n := range g.nodesByName {
		node, ok := n.(*Node)
		if !ok {
			continue
		}
		if len(g.To(n)) > 0 {
			continue
		}
		if contains(node.UniqueName, g.rootNodeNames) {
			continue
		}

		g.RemoveNode(node)
		removed = append(removed, node)
	}

	if len(removed) == 0 {
		return []*Node{}
	}

	return append(removed, g.PruneOrphans()...)
}
1023502
func (md *MDServerDisk) PruneBranch(ctx context.Context, id tlf.ID, bid kbfsmd.BranchID) error {
	if err := checkContext(ctx); err != nil {
		return err
	}

	if bid == kbfsmd.NullBranchID {
		return kbfsmd.ServerErrorBadRequest{Reason: "Invalid branch ID"}
	}

	currBID, err := md.getBranchID(ctx, id)
	if err != nil {
		return err
	}
	if currBID == kbfsmd.NullBranchID || bid != currBID {
		return kbfsmd.ServerErrorBadRequest{Reason: "Invalid branch ID"}
	}

	// Don't actually delete unmerged history. This is intentional
	// to be consistent with the mdserver behavior-- it garbage
	// collects discarded branches in the background.
	return md.deleteBranchID(ctx, id)
}
1058085
func (m *ModuleState) prune() {
	m.Lock()
	defer m.Unlock()

	for k, v := range m.Resources {
		if v == nil || (v.Primary == nil || v.Primary.ID == "") && len(v.Deposed) == 0 {
			delete(m.Resources, k)
			continue
		}

		v.prune()
	}

	for k, v := range m.Outputs {
		if v.Value == config.UnknownVariableValue {
			delete(m.Outputs, k)
		}
	}

	m.Dependencies = uniqueStrings(m.Dependencies)
}
271507
func (p *Apply) PruneColumns(parentUseCols []*expression.Column) {
	for _, col := range p.corCols {
		parentUseCols = append(parentUseCols, &col.Column)
	}
	p.Join.PruneColumns(parentUseCols)
}
393364
func (pruner *Pruner) Prune(baseFilePath string) {
	if pruner.pruneHours > 0 {
		pruner.pruneByHour(baseFilePath, pruner.pruneHours)
	}
	if pruner.pruneCount > 0 {
		pruner.pruneByCount(baseFilePath, pruner.pruneCount)
	}
	if pruner.pruneSize > 0 {
		pruner.pruneToSize(baseFilePath, pruner.pruneSize)
	}
}
1249159
func (p *Pruner) Prune(memCache map[int64]string) error {
	err := p.removeOldPings()
	if err != nil {
		return errors.Trace(err)
	}
	err = p.removeUnusedBeings(memCache)
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}
782222
func (c Caches) Prune() (int, error) {
	counter := 0
	for k, cache := range c {
		err := afero.Walk(cache.Fs, "", func(name string, info os.FileInfo, err error) error {
			if info == nil {
				return nil
			}

			name = cleanID(name)

			if info.IsDir() {
				f, err := cache.Fs.Open(name)
				if err != nil {
					// This cache dir may not exist.
					return nil
				}
				defer f.Close()
				_, err = f.Readdirnames(1)
				if err == io.EOF {
					// Empty dir.
					return cache.Fs.Remove(name)
				}

				return nil
			}

			shouldRemove := cache.isExpired(info.ModTime())

			if !shouldRemove && len(cache.nlocker.seen) > 0 {
				// Remove it if it's not been touched/used in the last build.
				_, seen := cache.nlocker.seen[name]
				shouldRemove = !seen
			}

			if shouldRemove {
				err := cache.Fs.Remove(name)
				if err == nil {
					counter++
				}
				return err
			}

			return nil
		})

		if err != nil {
			return counter, errors.Wrapf(err, "failed to prune cache %q", k)
		}

	}

	return counter, nil
}
1168902
func pruneCollection(mb modelBackend, maxHistoryTime time.Duration, maxHistoryMB int, collectionName string, ageField string, timeUnit TimeUnit) error {

	// NOTE(axw) we require a raw collection to obtain the size of the
	// collection. Take care to include model-uuid in queries where
	// appropriate.
	entries, closer := mb.db().GetRawCollection(collectionName)
	defer closer()

	p := collectionPruner{
		st:       mb,
		coll:     entries,
		maxAge:   maxHistoryTime,
		maxSize:  maxHistoryMB,
		ageField: ageField,
		timeUnit: timeUnit,
	}
	if err := p.validate(); err != nil {
		return errors.Trace(err)
	}
	if err := p.pruneByAge(); err != nil {
		return errors.Trace(err)
	}
	return errors.Trace(p.pruneBySize())
}
691329
func (p *Aggregation) PruneColumns(parentUsedCols []*expression.Column) {
	child := p.GetChildByIndex(0).(LogicalPlan)
	used := getUsedList(parentUsedCols, p.schema)
	for i := len(used) - 1; i >= 0; i-- {
		if !used[i] {
			p.schema.Columns = append(p.schema.Columns[:i], p.schema.Columns[i+1:]...)
			p.AggFuncs = append(p.AggFuncs[:i], p.AggFuncs[i+1:]...)
		}
	}
	var selfUsedCols []*expression.Column
	for _, aggrFunc := range p.AggFuncs {
		for _, arg := range aggrFunc.GetArgs() {
			selfUsedCols = append(selfUsedCols, expression.ExtractColumns(arg)...)
		}
	}
	for _, expr := range p.GroupByItems {
		selfUsedCols = append(selfUsedCols, expression.ExtractColumns(expr)...)
	}
	child.PruneColumns(selfUsedCols)
}
1034989
func pruneArchive(archiveDir string, refTime time.Time, max archiveConfig) (*pruneStats, error) {
	d, err := os.Open(archiveDir)
	if err != nil {
		return nil, err
	}
	defer d.Close()

	files, err := d.Readdir(0)
	if err != nil {
		return nil, err
	}

	sort.Sort(sort.Reverse(byModTime(files)))

	var seen, curr pruneStats
	for i := 0; i < len(files); i++ {
		curr.age = refTime.Sub(files[i].ModTime())
		curr.bytes = seen.bytes + files[i].Size()
		curr.count = seen.count + 1
		if curr.count > max.count || curr.bytes > max.bytes || curr.age > max.age {
			seen.filesRemoved, seen.filesErrored = removeFiles(archiveDir, files[i:])
			return &seen, nil
		}
		seen = curr
	}

	return &seen, nil
}
1258987
func PrunePrefixes(prefixes []string) []string {
	prunedPrefixes := []string{}
	for i := 0; i < len(prefixes); i++ {
		foundPrefix := false
		for j := 0; j < len(prefixes); j++ {
			if i == j {
				continue
			}
			if strings.HasPrefix(prefixes[i], prefixes[j]) {
				foundPrefix = true
			}
		}
		if !foundPrefix {
			prunedPrefixes = append(prunedPrefixes, prefixes[i])
		}
	}
	return prunedPrefixes
}