// RemoveUninteresting prunes and elides profiles using built-in
// tables of uninteresting function names.
183127
func (p *Profile) RemoveUninteresting() error {
	var keep, drop *regexp.Regexp
	var err error

	if p.DropFrames != "" {
		if drop, err = regexp.Compile("^(" + p.DropFrames + ")$"); err != nil {
			return fmt.Errorf("failed to compile regexp %s: %v", p.DropFrames, err)
		}
		if p.KeepFrames != "" {
			if keep, err = regexp.Compile("^(" + p.KeepFrames + ")$"); err != nil {
				return fmt.Errorf("failed to compile regexp %s: %v", p.KeepFrames, err)
			}
		}
		p.Prune(drop, keep)
	}
	return nil
}
368391
func (w *MachineLXDProfileWatcher) removeUnit(topic string, value interface{}) {
	// We don't want to respond to any events until we have been fully initialized.
	select {
	case <-w.initialized:
	case <-w.tomb.Dying():
		return
	}
	var notify bool
	defer func(notify *bool) {
		if *notify {
			logger.Tracef("notifying due to remove unit requires lxd profile change machine-%s", w.machineId)
			w.notify()
			w.metrics.LXDProfileChangeHit.Inc()
		} else {
			w.metrics.LXDProfileChangeMiss.Inc()
		}
	}(&notify)

	rUnit, ok := value.(unitLXDProfileRemove)
	if !ok {
		w.logError("programming error, value not of type unitLXDProfileRemove")
		return
	}

	app, ok := w.applications[rUnit.appName]
	if !ok {
		w.logError("programming error, unit removed before being added, application name not found")
		return
	}
	if !app.units.Contains(rUnit.name) {
		return
	}
	profile := app.charmProfile
	app.units.Remove(rUnit.name)
	if app.units.Size() == 0 {
		// the application has no more units on this machine,
		// stop watching it.
		delete(w.applications, rUnit.appName)
	}
	// If there are additional units on the machine and the current
	// application has an lxd profile, notify so it can be removed
	// from the machine.
	if len(w.applications) > 0 && !profile.Empty() {
		notify = true
	}
	return
}
1331048
func (g *Generator) Cleanup() {
	for _, f := range g.genfiles {
		os.Remove(f)
	}
	g.genfiles = nil
}
354839
func (p *ErrorList) RemoveMultiples() {
	sort.Sort(p)
	var last token.Position // initial last.Line is != any legal error line
	i := 0
	for _, e := range *p {
		if e.Pos.Filename != last.Filename || e.Pos.Line != last.Line {
			last = e.Pos
			(*p)[i] = e
			i++
		}
	}
	(*p) = (*p)[0:i]
}
414244
func (s *LoadBalancerService) NewRemoveCertFromLoadBalancerParams(lbruleid string) *RemoveCertFromLoadBalancerParams {
	p := &RemoveCertFromLoadBalancerParams{}
	p.p = make(map[string]interface{})
	p.p["lbruleid"] = lbruleid
	return p
}
489300
func (s *Storage) removeLeastRecent(name string, max int) error {
	if max < 0 {
		return nil
	}
	h, err := s.History(name)
	if err != nil {
		return err
	}
	if len(h) <= max {
		return nil
	}

	// We want oldest to newest
	relutil.SortByRevision(h)

	lastDeployed, err := s.Deployed(name)
	if err != nil {
		return err
	}

	var toDelete []*rspb.Release
	for _, rel := range h {
		// once we have enough releases to delete to reach the max, stop
		if len(h)-len(toDelete) == max {
			break
		}
		if lastDeployed != nil {
			if rel.GetVersion() != lastDeployed.GetVersion() {
				toDelete = append(toDelete, rel)
			}
		} else {
			toDelete = append(toDelete, rel)
		}
	}

	// Delete as many as possible. In the case of API throughput limitations,
	// multiple invocations of this function will eventually delete them all.
	errors := []error{}
	for _, rel := range toDelete {
		err = s.deleteReleaseVersion(name, rel.GetVersion())
		if err != nil {
			errors = append(errors, err)
		}
	}

	s.Log("Pruned %d record(s) from %s with %d error(s)", len(toDelete), name, len(errors))
	switch c := len(errors); c {
	case 0:
		return nil
	case 1:
		return errors[0]
	default:
		return fmt.Errorf("encountered %d deletion errors. First is: %s", c, errors[0])
	}
}
577467
func (u *Unit) RemoveOperation(force bool) *RemoveUnitOperation {
	return &RemoveUnitOperation{
		unit:            &Unit{st: u.st, doc: u.doc, modelType: u.modelType},
		ForcedOperation: ForcedOperation{Force: force},
	}
}
304746
func pruneServices(ctx context.Context, dockerCli command.Cli, namespace convert.Namespace, services map[string]struct{}) {
	client := dockerCli.Client()

	oldServices, err := getStackServices(ctx, client, namespace.Name())
	if err != nil {
		fmt.Fprintf(dockerCli.Err(), "Failed to list services: %s\n", err)
	}

	pruneServices := []swarm.Service{}
	for _, service := range oldServices {
		if _, exists := services[namespace.Descope(service.Spec.Name)]; !exists {
			pruneServices = append(pruneServices, service)
		}
	}
	removeServices(ctx, dockerCli, pruneServices)
}
345555
func (b *Builder) Prune(ctx context.Context, opts types.BuildCachePruneOptions) (int64, []string, error) {
	ch := make(chan *controlapi.UsageRecord)

	eg, ctx := errgroup.WithContext(ctx)

	validFilters := make(map[string]bool, 1+len(cacheFields))
	validFilters["unused-for"] = true
	validFilters["until"] = true
	validFilters["label"] = true  // TODO(tiborvass): handle label
	validFilters["label!"] = true // TODO(tiborvass): handle label!
	for k, v := range cacheFields {
		validFilters[k] = v
	}
	if err := opts.Filters.Validate(validFilters); err != nil {
		return 0, nil, err
	}

	pi, err := toBuildkitPruneInfo(opts)
	if err != nil {
		return 0, nil, err
	}

	eg.Go(func() error {
		defer close(ch)
		return b.controller.Prune(&controlapi.PruneRequest{
			All:          pi.All,
			KeepDuration: int64(pi.KeepDuration),
			KeepBytes:    pi.KeepBytes,
			Filter:       pi.Filter,
		}, &pruneProxy{
			streamProxy: streamProxy{ctx: ctx},
			ch:          ch,
		})
	})

	var size int64
	var cacheIDs []string
	eg.Go(func() error {
		for r := range ch {
			size += r.Size_
			cacheIDs = append(cacheIDs, r.ID)
		}
		return nil
	})

	if err := eg.Wait(); err != nil {
		return 0, nil, err
	}

	return size, cacheIDs, nil
}
164424
func (c *removeUnitCommand) removeUnitsDeprecated(ctx *cmd.Context, client RemoveApplicationAPI) error {
	err := client.DestroyUnitsDeprecated(c.EntityNames...)
	return block.ProcessBlockedError(err, block.BlockRemove)
}
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()...)
}
717099
func (c *Cache) pruneSizeLocked() {
	// There is no size constraint.
	if c.size <= 0 {
		return
	}

	// Prune the oldest entries until we're within our size constraint.
	for e := c.lru.Back(); e != nil; e = c.lru.Back() {
		if len(c.cache) <= c.size {
			return
		}
		c.evictEntryLocked(e)
	}
}
287914
func (p *LogicalUnionScan) PruneColumns(parentUsedCols []*expression.Column) error {
	for _, col := range p.Schema().TblID2Handle {
		parentUsedCols = append(parentUsedCols, col[0])
	}
	return p.children[0].PruneColumns(parentUsedCols)
}
882144
func cleanupIptablesLeftovers(ipt utiliptables.Interface) (encounteredError bool) {
	// Unlink the iptables chains created by ipvs Proxier
	for _, jc := range iptablesJumpChain {
		args := []string{
			"-m", "comment", "--comment", jc.comment,
			"-j", string(jc.to),
		}
		if err := ipt.DeleteRule(jc.table, jc.from, args...); err != nil {
			if !utiliptables.IsNotFoundError(err) {
				klog.Errorf("Error removing iptables rules in ipvs proxier: %v", err)
				encounteredError = true
			}
		}
	}

	// Flush and remove all of our chains. Flushing all chains before removing them also removes all links between chains first.
	for _, ch := range iptablesChains {
		if err := ipt.FlushChain(ch.table, ch.chain); err != nil {
			if !utiliptables.IsNotFoundError(err) {
				klog.Errorf("Error removing iptables rules in ipvs proxier: %v", err)
				encounteredError = true
			}
		}
	}

	// Remove all of our chains.
	for _, ch := range iptablesChains {
		if err := ipt.DeleteChain(ch.table, ch.chain); err != nil {
			if !utiliptables.IsNotFoundError(err) {
				klog.Errorf("Error removing iptables rules in ipvs proxier: %v", err)
				encounteredError = true
			}
		}
	}

	return encounteredError
}
349233
func (pl *List) removePeerIdentifierReferences(pid peer.Identifier) (*peerThunk, error) {
	if t := pl.availablePeers[pid.Identifier()]; t != nil {
		return t, pl.removeFromAvailablePeers(t)
	}

	if t, ok := pl.unavailablePeers[pid.Identifier()]; ok && t != nil {
		pl.removeFromUnavailablePeers(t)
		return t, nil
	}

	return nil, peer.ErrPeerRemoveNotInList(pid.Identifier())
}
1156005
func (m *MetaClient) RemoveRolePerms(ctx context.Context, name string, perms Permissions) error {
	a := &RoleAction{
		Action: "remove-permissions",
		Role: &Role{
			Name:        name,
			Permissions: perms,
		},
	}
	return m.Post(ctx, "/role", a, nil)
}
518556
func (dc *DeploymentController) cleanupUnhealthyReplicas(oldRSs []*apps.ReplicaSet, deployment *apps.Deployment, maxCleanupCount int32) ([]*apps.ReplicaSet, int32, error) {
	sort.Sort(controller.ReplicaSetsByCreationTimestamp(oldRSs))
	// Safely scale down all old replica sets with unhealthy replicas. Replica set will sort the pods in the order
	// such that not-ready < ready, unscheduled < scheduled, and pending < running. This ensures that unhealthy replicas will
	// been deleted first and won't increase unavailability.
	totalScaledDown := int32(0)
	for i, targetRS := range oldRSs {
		if totalScaledDown >= maxCleanupCount {
			break
		}
		if *(targetRS.Spec.Replicas) == 0 {
			// cannot scale down this replica set.
			continue
		}
		klog.V(4).Infof("Found %d available pods in old RS %s/%s", targetRS.Status.AvailableReplicas, targetRS.Namespace, targetRS.Name)
		if *(targetRS.Spec.Replicas) == targetRS.Status.AvailableReplicas {
			// no unhealthy replicas found, no scaling required.
			continue
		}

		scaledDownCount := int32(integer.IntMin(int(maxCleanupCount-totalScaledDown), int(*(targetRS.Spec.Replicas)-targetRS.Status.AvailableReplicas)))
		newReplicasCount := *(targetRS.Spec.Replicas) - scaledDownCount
		if newReplicasCount > *(targetRS.Spec.Replicas) {
			return nil, 0, fmt.Errorf("when cleaning up unhealthy replicas, got invalid request to scale down %s/%s %d -> %d", targetRS.Namespace, targetRS.Name, *(targetRS.Spec.Replicas), newReplicasCount)
		}
		_, updatedOldRS, err := dc.scaleReplicaSetAndRecordEvent(targetRS, newReplicasCount, deployment)
		if err != nil {
			return nil, totalScaledDown, err
		}
		totalScaledDown += scaledDownCount
		oldRSs[i] = updatedOldRS
	}
	return oldRSs, totalScaledDown, nil
}