// Removes any *.zap files which aren't listed in the rootBolt.
9639
func (s *Scorch) removeOldZapFiles() error {
	liveFileNames, err := s.loadZapFileNames()
	if err != nil {
		return err
	}

	currFileInfos, err := ioutil.ReadDir(s.path)
	if err != nil {
		return err
	}

	s.rootLock.RLock()

	for _, finfo := range currFileInfos {
		fname := finfo.Name()
		if filepath.Ext(fname) == ".zap" {
			if _, exists := liveFileNames[fname]; !exists && !s.ineligibleForRemoval[fname] {
				err := os.Remove(s.path + string(os.PathSeparator) + fname)
				if err != nil {
					log.Printf("got err removing file: %s, err: %v", fname, err)
				}
			}
		}
	}

	s.rootLock.RUnlock()

	return nil
}
1061402
func (p *Partition) deleteNonManifestFiles(m *Manifest) error {
	dir, err := os.Open(p.path)
	if err != nil {
		return err
	}
	defer dir.Close()

	fis, err := dir.Readdir(-1)
	if err != nil {
		return err
	}

	// Loop over all files and remove any not in the manifest.
	for _, fi := range fis {
		filename := filepath.Base(fi.Name())
		if filename == ManifestFileName || filename == StatsFileName || m.HasFile(filename) {
			continue
		}

		if err := os.RemoveAll(filename); err != nil {
			return err
		}
	}

	return dir.Close()
}
152340
func (d *DB) deleteObsoleteFiles() {
	liveFileNums := map[uint64]struct{}{}
	for fileNum := range d.pendingOutputs {
		liveFileNums[fileNum] = struct{}{}
	}
	d.versions.addLiveFileNums(liveFileNums)
	logNumber := d.versions.logNumber
	manifestFileNumber := d.versions.manifestFileNumber

	// Release the d.mu lock while doing I/O.
	// Note the unusual order: Unlock and then Lock.
	d.mu.Unlock()
	defer d.mu.Lock()

	fs := d.opts.GetFileSystem()
	list, err := fs.List(d.dirname)
	if err != nil {
		// Ignore any filesystem errors.
		return
	}
	for _, filename := range list {
		fileType, fileNum, ok := parseDBFilename(filename)
		if !ok {
			return
		}
		keep := true
		switch fileType {
		case fileTypeLog:
			// TODO: also look at prevLogNumber?
			keep = fileNum >= logNumber
		case fileTypeManifest:
			keep = fileNum >= manifestFileNumber
		case fileTypeTable, fileTypeOldFashionedTable:
			_, keep = liveFileNums[fileNum]
		}
		if keep {
			continue
		}
		if fileType == fileTypeTable {
			d.tableCache.evict(fileNum)
		}
		// Ignore any file system errors.
		fs.Remove(filepath.Join(d.dirname, filename))
	}
}
32455
func cleanPluginExecutable(name string) string {
	switch {
	case strings.HasSuffix(name, ".exe"):
		return strings.TrimSuffix(name, ".exe")
	default:
		return name
	}
}
411519
func (s *Store) removeEmptyParentDirectories(path string) error {
	parent := filepath.Dir(path)

	if relpath, err := filepath.Rel(s.path, parent); err != nil {
		return err
	} else if strings.HasPrefix(relpath, ".") {
		return nil
	}

	err := os.Remove(parent)
	switch {
	case err == nil:
		return s.removeEmptyParentDirectories(parent)
	case err.(*os.PathError).Err == syscall.ENOTEMPTY:
		// ignore when directory is non-empty
		return nil
	default:
		return err
	}
}
189201
func (zk *zkf) RemoveServiceEndpoints(serviceID string) error {
	logger := plog.WithField("serviceid", serviceID)

	// get the root-based connection to delete the service endpoints
	rootconn, err := zzk.GetLocalConnection("/")
	if err != nil {
		logger.WithError(err).Debug("Could not acquire a root-based connection to delete the service's public endpoints in zookeeper")
		return err
	}

	zk.svcRegistry.Lock()
	defer zk.svcRegistry.Unlock()
	if zk.svcRegistry.registry == nil {
		err = zk.buildServiceRegistryCache(rootconn)
		if err != nil {
			logger.WithError(err).Debug("Could not build cache of the service registry")
			return err
		}
	}

	// delete the public endpoints for this service
	syncRequest := zkr.ServiceRegistrySyncRequest{
		ServiceID:       serviceID,
		PortsToPublish:  make(map[zkr.PublicPortKey]zkr.PublicPort),
		PortsToDelete:   []zkr.PublicPortKey{},
		VHostsToPublish: make(map[zkr.VHostKey]zkr.VHost),
		VHostsToDelete:  []zkr.VHostKey{},
	}

	serviceRegistry := zk.svcRegistry.GetRegistryForService(serviceID)
	for key, _ := range serviceRegistry.PublicPorts {
		syncRequest.PortsToDelete = append(syncRequest.PortsToDelete, key)
	}
	for key, _ := range serviceRegistry.VHosts {
		syncRequest.VHostsToDelete = append(syncRequest.VHostsToDelete, key)
	}

	// sync the registry
	if err := zkr.SyncServiceRegistry(rootconn, syncRequest); err != nil {
		logger.WithError(err).Debug("Could not delete the service's public endpoints in zookeeper")
		return err
	}

	// Update our local cache now that we know that ZK was updated successfully
	zk.svcRegistry.UpdateRegistry(serviceID, syncRequest.PortsToPublish, syncRequest.VHostsToPublish)
	logger.Debug("Deleted the service's public endpoints in zookeeper")
	return nil
}
457640
func (s *StepTeardownInstance) Cleanup(state multistep.StateBag) {
	config := state.Get("config").(*Config)
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Deleting disk...")
	errCh, err := driver.DeleteDisk(config.Zone, config.DiskName)
	if err == nil {
		select {
		case err = <-errCh:
		case <-time.After(config.stateTimeout):
			err = errors.New("time out while waiting for disk to delete")
		}
	}

	if err != nil {
		ui.Error(fmt.Sprintf(
			"Error deleting disk. Please delete it manually.\n\n"+
				"DiskName: %s\n"+
				"Zone: %s\n"+
				"Error: %s", config.DiskName, config.Zone, err))
	}

	ui.Message("Disk has been deleted!")

	return
}
1093336
func removeVolumes(ctx *context, ops map[names.VolumeTag]*removeVolumeOp) error {
	tags := make([]names.VolumeTag, 0, len(ops))
	for tag := range ops {
		tags = append(tags, tag)
	}
	removeVolumeParams, err := removeVolumeParams(ctx, tags)
	if err != nil {
		return errors.Trace(err)
	}
	volumeParams := make([]storage.VolumeParams, len(tags))
	removeVolumeParamsByTag := make(map[names.VolumeTag]params.RemoveVolumeParams)
	for i, args := range removeVolumeParams {
		removeVolumeParamsByTag[tags[i]] = args
		volumeParams[i] = storage.VolumeParams{
			Tag:      tags[i],
			Provider: storage.ProviderType(args.Provider),
		}
	}
	paramsBySource, volumeSources, err := volumeParamsBySource(
		ctx.config.StorageDir, volumeParams, ctx.config.Registry,
	)
	if err != nil {
		return errors.Trace(err)
	}
	var remove []names.Tag
	var reschedule []scheduleOp
	var statuses []params.EntityStatusArgs
	removeVolumes := func(tags []names.VolumeTag, ids []string, f func(environscontext.ProviderCallContext, []string) ([]error, error)) error {
		if len(ids) == 0 {
			return nil
		}
		errs, err := f(ctx.config.CloudCallContext, ids)
		if err != nil {
			return errors.Trace(err)
		}
		for i, err := range errs {
			tag := tags[i]
			if err == nil {
				remove = append(remove, tag)
				continue
			}
			// Failed to destroy or release volume; reschedule and update status.
			reschedule = append(reschedule, ops[tag])
			statuses = append(statuses, params.EntityStatusArgs{
				Tag:    tag.String(),
				Status: status.Error.String(),
				Info:   errors.Annotate(err, "destroying volume").Error(),
			})
		}
		return nil
	}
	for sourceName, volumeParams := range paramsBySource {
		logger.Debugf("removing volumes from %q: %v", sourceName, volumeParams)
		volumeSource := volumeSources[sourceName]
		removeTags := make([]names.VolumeTag, len(volumeParams))
		removeParams := make([]params.RemoveVolumeParams, len(volumeParams))
		for i, args := range volumeParams {
			removeTags[i] = args.Tag
			removeParams[i] = removeVolumeParamsByTag[args.Tag]
		}
		destroyTags, destroyIds, releaseTags, releaseIds := partitionRemoveVolumeParams(removeTags, removeParams)
		if err := removeVolumes(destroyTags, destroyIds, volumeSource.DestroyVolumes); err != nil {
			return errors.Trace(err)
		}
		if err := removeVolumes(releaseTags, releaseIds, volumeSource.ReleaseVolumes); err != nil {
			return errors.Trace(err)
		}
	}
	scheduleOperations(ctx, reschedule...)
	setStatus(ctx, statuses)
	if err := removeEntities(ctx, remove); err != nil {
		return errors.Annotate(err, "removing volumes from state")
	}
	return nil
}
614236
func (task *provisionerTask) removeMachineFromAZMap(machine apiprovisioner.MachineProvisioner) {
	machineId := machine.Id()
	task.machinesMutex.Lock()
	defer task.machinesMutex.Unlock()
	for _, zoneMachines := range task.availabilityZoneMachines {
		zoneMachines.MachineIds.Remove(machineId)
		zoneMachines.FailedMachineIds.Remove(machineId)
	}
}
219066
func removeNils(m map[string]interface{}) {
	for k, v := range m {
		if v == nil {
			delete(m, k)
		}
	}
}
302907
func removeMountDir(plug *csiPlugin, mountPath string) error {
	klog.V(4).Info(log("removing mount path [%s]", mountPath))

	mnt, err := isDirMounted(plug, mountPath)
	if err != nil {
		return err
	}
	if !mnt {
		klog.V(4).Info(log("dir not mounted, deleting it [%s]", mountPath))
		if err := os.Remove(mountPath); err != nil && !os.IsNotExist(err) {
			klog.Error(log("failed to remove dir [%s]: %v", mountPath, err))
			return err
		}
		// remove volume data file as well
		volPath := path.Dir(mountPath)
		dataFile := filepath.Join(volPath, volDataFileName)
		klog.V(4).Info(log("also deleting volume info data file [%s]", dataFile))
		if err := os.Remove(dataFile); err != nil && !os.IsNotExist(err) {
			klog.Error(log("failed to delete volume data file [%s]: %v", dataFile, err))
			return err
		}
		// remove volume path
		klog.V(4).Info(log("deleting volume path [%s]", volPath))
		if err := os.Remove(volPath); err != nil && !os.IsNotExist(err) {
			klog.Error(log("failed to delete volume path [%s]: %v", volPath, err))
			return err
		}
	}
	return nil
}
1171365
func (cl FileChangelist) Remove(idxs []int) error {
	fileInfos, err := getFileNames(cl.dir)
	if err != nil {
		return err
	}
	remove := make(map[int]struct{})
	for _, i := range idxs {
		remove[i] = struct{}{}
	}
	for i, c := range fileInfos {
		if _, ok := remove[i]; ok {
			file := filepath.Join(cl.dir, c.Name())
			if err := os.Remove(file); err != nil {
				logrus.Errorf("could not remove change %d: %s", i, err.Error())
			}
		}
	}
	return nil
}
1053768
func (c *Cache) RemoveOldest() {
	c.lock.Lock()
	c.lru.RemoveOldest()
	c.lock.Unlock()
}
730227
func (f *FakeFS) RemoveAll(name string) error {
	_, ok := f.Files[name]
	if !ok {
		return FakeFileNotFound{Filename: name}
	}
	delete(f.Files, name)
	return nil
}
291109
func (zk *zkf) RemoveService(poolID, serviceID string) error {
	logger := plog.WithFields(log.Fields{
		"poolid":    poolID,
		"serviceid": serviceID,
	})

	// get the root-based connection to delete the service
	rootconn, err := zzk.GetLocalConnection("/")
	if err != nil {
		logger.WithError(err).Debug("Could not acquire a root-based connection to delete the service in zookeeper")
		return err
	}

	if err := zks.RemoveService(rootconn, poolID, serviceID); err != nil {
		logger.WithError(err).Debug("Could not delete the service in zookeeper")
		return err
	}
	logger.Debug("Deleted the service in zookeeper")
	return nil
}
675543
func RemoveAllocs(alloc []*Allocation, remove []*Allocation) []*Allocation {
	// Convert remove into a set
	removeSet := make(map[string]struct{})
	for _, remove := range remove {
		removeSet[remove.ID] = struct{}{}
	}

	n := len(alloc)
	for i := 0; i < n; i++ {
		if _, ok := removeSet[alloc[i].ID]; ok {
			alloc[i], alloc[n-1] = alloc[n-1], nil
			i--
			n--
		}
	}

	alloc = alloc[:n]
	return alloc
}
21978
func (i *Instance) CleanUp() error {

	if err := i.cleanACLs(); err != nil {
		zap.L().Error("Failed to clean acls while stopping the supervisor", zap.Error(err))
	}

	if err := i.ipset.DestroyAll(chainPrefix); err != nil {
		zap.L().Error("Failed to clean up ipsets", zap.Error(err))
	}

	return nil
}