// cleanupUnusedLogs cleans up temporary or unused log files generated by previous log rotation
// failure.
193202
func (c *containerLogManager) cleanupUnusedLogs(logs []string) ([]string, error) {
	inuse, unused := filterUnusedLogs(logs)
	for _, l := range unused {
		if err := os.Remove(l); err != nil {
			return nil, fmt.Errorf("failed to remove unused log %q: %v", l, err)
		}
	}
	return inuse, nil
}
316734
func (fbo *folderBlockOps) cleanUpUnusedBlocks(ctx context.Context,
	md ReadOnlyRootMetadata, syncState fileSyncState, fbm *folderBlockManager) error {
	numToClean := len(syncState.si.toCleanIfUnused)
	if numToClean == 0 {
		return nil
	}

	// What blocks are referenced in the successful MD?
	refs := make(map[data.BlockPointer]bool)
	for _, op := range md.data.Changes.Ops {
		for _, ptr := range op.Refs() {
			if ptr == data.ZeroPtr {
				panic("Unexpected zero ref ptr in a sync MD revision")
			}
			refs[ptr] = true
		}
		for _, update := range op.allUpdates() {
			if update.Ref == data.ZeroPtr {
				panic("Unexpected zero update ref ptr in a sync MD revision")
			}

			refs[update.Ref] = true
		}
	}

	// For each MD to clean, clean up the old failed blocks
	// immediately if the merge status matches the successful put, if
	// they didn't get referenced in the successful put.  If the merge
	// status is different (e.g., we ended up on a conflict branch),
	// clean it up only if the original revision failed.  If the same
	// block appears more than once, the one with a different merged
	// status takes precedence (which will always come earlier in the
	// list of MDs).
	blocksSeen := make(map[data.BlockPointer]bool)
	for _, oldMD := range syncState.si.toCleanIfUnused {
		bdType := blockDeleteAlways
		if oldMD.md.MergedStatus() != md.MergedStatus() {
			bdType = blockDeleteOnMDFail
		}

		failedBps := newBlockPutStateMemory(oldMD.bps.numBlocks())
		for _, ptr := range oldMD.bps.ptrs() {
			if ptr == data.ZeroPtr {
				panic("Unexpected zero block ptr in an old sync MD revision")
			}
			if blocksSeen[ptr] {
				continue
			}
			blocksSeen[ptr] = true
			if refs[ptr] && bdType == blockDeleteAlways {
				continue
			}
			failedBps.blockStates[ptr] = blockState{}
			fbo.vlog.CLogf(
				ctx, libkb.VLog1, "Cleaning up block %v from a previous "+
					"failed revision %d (oldMD is %s, bdType=%d)", ptr,
				oldMD.md.Revision(), oldMD.md.MergedStatus(), bdType)
		}

		if len(failedBps.blockStates) > 0 {
			fbm.cleanUpBlockState(oldMD.md, failedBps, bdType)
		}
	}
	return nil
}
154482
func (o *copier) Cleanup() {
	for _, path := range o.tmpPaths {
		os.RemoveAll(path)
	}
	o.tmpPaths = []string{}
	if o.activeLayer != nil {
		o.activeLayer.Release()
		o.activeLayer = nil
	}
}
425773
func (m *MySQLStore) cleanup(interval time.Duration, quit <-chan struct{}, done chan<- struct{}) {
	ticker := time.NewTicker(interval)

	defer func() {
		ticker.Stop()
	}()

	for {
		select {
		case <-quit:
			// Handle the quit signal.
			done <- struct{}{}
			return
		case <-ticker.C:
			// Delete expired sessions on each tick.
			err := m.deleteExpired()
			if err != nil {
				log.Printf("sessions: mysqlstore: unable to delete expired sessions: %v", err)
			}
		}
	}
}
1331673
func cleanup(ctx context.Context, client *containerd.Client) error {
	containers, err := client.Containers(ctx)
	if err != nil {
		return err
	}
	for _, c := range containers {
		task, err := c.Task(ctx, nil)
		if err == nil {
			task.Delete(ctx, containerd.WithProcessKill)
		}
		if err := c.Delete(ctx, containerd.WithSnapshotCleanup); err != nil {
			if derr := c.Delete(ctx); derr == nil {
				continue
			}
			return err
		}
	}
	return nil
}
386693
func (d *Driver) Cleanup() error {
	err := d.DeviceSet.Shutdown()

	if err2 := mount.Unmount(d.home); err == nil {
		err = err2
	}

	return err
}
106828
func (p *XPod) cleanup() {
	//if removing, the remove will get the resourceLock in advance, and it will set
	// the pod status to NONE when it complete.
	// Therefore, if get into cleanup() after remove, cleanup should exit when it
	// got a
	p.resourceLock.Lock()
	defer p.resourceLock.Unlock()

	p.statusLock.Lock()
	if p.status == S_POD_STOPPED {
		p.statusLock.Unlock()
		return
	} else if p.status != S_POD_NONE {
		p.status = S_POD_STOPPING
	}
	p.statusLock.Unlock()

	err := p.decommissionResources()
	if err != nil {
		// even if error, we set the vm to be stopped
		p.Log(ERROR, "pod stopping failed, failed to decommit the resources: %v", err)
		err = nil
	}

	err = p.removeSandboxFromDB()
	if err != nil {
		p.Log(ERROR, "pod stopping failed, failed to remove sandbox persist data: %v", err)
		err = nil
	}

	p.Log(DEBUG, "tag pod as stopped")
	p.statusLock.Lock()
	if p.status != S_POD_NONE {
		p.status = S_POD_STOPPED
	}
	p.statusLock.Unlock()

	p.Log(INFO, "pod stopped")
	select {
	case p.stoppedChan <- true:
	default:
	}
}
333301
func GetAllLogs(log string) ([]string, error) {
	// pattern is used to match all rotated files.
	pattern := fmt.Sprintf("%s.*", log)
	logs, err := filepath.Glob(pattern)
	if err != nil {
		return nil, fmt.Errorf("failed to list all log files with pattern %q: %v", pattern, err)
	}
	inuse, _ := filterUnusedLogs(logs)
	sort.Strings(inuse)
	return append(inuse, log), nil
}
417835
func (mr *MockInstallerMockRecorder) Cleanup(arg0 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Cleanup", reflect.TypeOf((*MockInstaller)(nil).Cleanup), arg0)
}
621467
func (c *DefaultCleaner) Cleanup(config *api.Config) {
	if config.PreserveWorkingDir {
		glog.V(2).Infof("Temporary directory %q will be saved, not deleted", config.WorkingDir)
	} else {
		glog.V(2).Infof("Removing temporary directory %s", config.WorkingDir)
		if err := c.fs.RemoveDirectory(config.WorkingDir); err != nil {
			glog.Warningf("Error removing temporary directory %q: %v", config.WorkingDir, err)
		}
	}
	if config.LayeredBuild {
		// config.LayeredBuild is true only when layered build was finished successfully.
		// Also in this case config.BuilderImage contains name of the new just built image,
		// not the original one that was specified by the user.
		glog.V(2).Infof("Removing temporary image %s", config.BuilderImage)
		if err := c.docker.RemoveImage(config.BuilderImage); err != nil {
			glog.Warningf("Error removing temporary image %s: %v", config.BuilderImage, err)
		}
	}
}
1161863
func (r *readWorkerState) Cleanup() {
	r.bufferPool.Return(r.readBuf)
	r.readBuf = nil
}
501758
func cleanupTempFiles() {
	tempFilesMu.Lock()
	for _, f := range tempFiles {
		os.Remove(f)
	}
	tempFiles = nil
	tempFilesMu.Unlock()
}
993939
func (c *DeploymentConfigController) cleanupOldDeployments(existingDeployments []*v1.ReplicationController, deploymentConfig *appsv1.DeploymentConfig) error {
	if deploymentConfig.Spec.RevisionHistoryLimit == nil {
		// there is no past deplyoment quota set
		return nil
	}

	prunableDeployments := appsutil.DeploymentsForCleanup(deploymentConfig, existingDeployments)
	if len(prunableDeployments) <= int(*deploymentConfig.Spec.RevisionHistoryLimit) {
		// the past deployment quota has not been exceeded
		return nil
	}

	deletionErrors := []error{}
	for i := 0; i < (len(prunableDeployments) - int(*deploymentConfig.Spec.RevisionHistoryLimit)); i++ {
		deployment := prunableDeployments[i]
		if *deployment.Spec.Replicas != 0 {
			// we do not want to clobber active older deployments, but we *do* want them to count
			// against the quota so that they will be pruned when they're scaled down
			continue
		}

		policy := metav1.DeletePropagationBackground
		err := c.kubeClient.ReplicationControllers(deployment.Namespace).Delete(deployment.Name, &metav1.DeleteOptions{
			PropagationPolicy: &policy,
		})
		if err != nil && !kapierrors.IsNotFound(err) {
			deletionErrors = append(deletionErrors, err)
		}
	}

	return kutilerrors.NewAggregate(deletionErrors)
}
652258
func (c *Config) CleanUp() {
	for _, d := range c.Definitions.All {
		sort.Sort(d.AppearsIn)
		sort.Sort(d.Fields)
		dedup := SortDefinitionsByName{}
		var last *Definition
		for _, i := range d.AppearsIn {
			if last != nil &&
				i.Name == last.Name &&
				i.Group.String() == last.Group.String() &&
				i.Version.String() == last.Version.String() {
				continue
			}
			last = i
			dedup = append(dedup, i)
		}
		d.AppearsIn = dedup
	}
}
613012
func (m *MountPoint) Cleanup() error {
	if m.Volume == nil || m.ID == "" {
		return nil
	}

	if err := m.Volume.Unmount(m.ID); err != nil {
		return errors.Wrapf(err, "error unmounting volume %s", m.Volume.Name())
	}

	m.active--
	if m.active == 0 {
		m.ID = ""
	}
	return nil
}
844056
func (mr *MockSupervisorMockRecorder) CleanUp() *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CleanUp", reflect.TypeOf((*MockSupervisor)(nil).CleanUp))
}
233345
func (c *containerLogManager) removeExcessLogs(logs []string) ([]string, error) {
	// Sort log files in oldest to newest order.
	sort.Strings(logs)
	// Container will create a new log file, and we'll rotate the latest log file.
	// Other than those 2 files, we can have at most MaxFiles-2 rotated log files.
	// Keep MaxFiles-2 files by removing old files.
	// We should remove from oldest to newest, so as not to break ongoing `kubectl logs`.
	maxRotatedFiles := c.policy.MaxFiles - 2
	if maxRotatedFiles < 0 {
		maxRotatedFiles = 0
	}
	i := 0
	for ; i < len(logs)-maxRotatedFiles; i++ {
		if err := os.Remove(logs[i]); err != nil {
			return nil, fmt.Errorf("failed to remove old log %q: %v", logs[i], err)
		}
	}
	logs = logs[i:]
	return logs, nil
}