// cleanupStage1 is meant to be executed in stage1 context. It inspects pod systemd-pid1 mountinfo to
// find all remaining mountpoints for appName and proceed to clean them up.
487941
func cleanupStage1(appName *types.ACName, enterCmd []string) error {
	// TODO(lucab): re-evaluate once/if we support systemd as non-pid1 (eg. host pid-ns inheriting)
	mnts, err := mountinfo.ParseMounts(1)
	if err != nil {
		return err
	}
	appRootFs := filepath.Join("/opt/stage2", appName.String(), "rootfs")
	mnts = mnts.Filter(mountinfo.HasPrefix(appRootFs))

	// soft-errors here, stage0 may still be able to continue with the removal anyway
	for _, m := range mnts {
		// unlink first to avoid back-propagation
		_ = syscall.Mount("", m.MountPoint, "", syscall.MS_PRIVATE|syscall.MS_REC, "")
		// simple unmount, it may fail if the target is busy (eg. overlapping children)
		if e := syscall.Unmount(m.MountPoint, 0); e != nil {
			// if busy, just detach here and let the kernel clean it once free
			_ = syscall.Unmount(m.MountPoint, syscall.MNT_DETACH)
		}
	}

	return nil
}
1142041
func (w *HTTPProvider) CleanUp(domain, token, keyAuth string) error {
	err := os.Remove(filepath.Join(w.path, http01.ChallengePath(token)))
	if err != nil {
		return fmt.Errorf("could not remove file in webroot after HTTP challenge -> %v", err)
	}

	return nil
}
1155923
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
	fqdn, _ := dns01.GetRecord(domain, keyAuth)

	records, err := d.findTxtRecords(domain, fqdn)
	if err != nil {
		return fmt.Errorf("alicloud: %v", err)
	}

	_, _, err = d.getHostedZone(domain)
	if err != nil {
		return fmt.Errorf("alicloud: %v", err)
	}

	for _, rec := range records {
		request := alidns.CreateDeleteDomainRecordRequest()
		request.RecordId = rec.RecordId
		_, err = d.client.DeleteDomainRecord(request)
		if err != nil {
			return fmt.Errorf("alicloud: %v", err)
		}
	}
	return nil
}
197206
func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error {
	fqdn, _ := dns01.GetRecord(domain, keyAuth)

	zone, err := d.getHostedZone(fqdn)
	if err != nil {
		return fmt.Errorf("googlecloud: %v", err)
	}

	records, err := d.findTxtRecords(zone, fqdn)
	if err != nil {
		return fmt.Errorf("googlecloud: %v", err)
	}

	if len(records) == 0 {
		return nil
	}

	_, err = d.client.Changes.Create(d.config.Project, zone, &dns.Change{Deletions: records}).Do()
	if err != nil {
		return fmt.Errorf("googlecloud: %v", err)
	}
	return nil
}
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:
	}
}
1112422
func (d *Driver) Cleanup() error {
	title := "lcowdriver: cleanup"

	items, err := ioutil.ReadDir(d.dataRoot)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}

	// Note we don't return an error below - it's possible the files
	// are locked. However, next time around after the daemon exits,
	// we likely will be able to cleanup successfully. Instead we log
	// warnings if there are errors.
	for _, item := range items {
		if item.IsDir() && strings.HasSuffix(item.Name(), "-removing") {
			if err := os.RemoveAll(filepath.Join(d.dataRoot, item.Name())); err != nil {
				logrus.Warnf("%s failed to cleanup %s: %s", title, item.Name(), err)
			} else {
				logrus.Infof("%s cleaned up %s", title, item.Name())
			}
		}
	}

	// Cleanup any service VMs we have running, along with their scratch spaces.
	// We don't take the lock for this as it's taken in terminateServiceVm.
	for k, v := range d.serviceVms.svms {
		logrus.Debugf("%s svm entry: %s: %+v", title, k, v)
		d.terminateServiceVM(k, "cleanup", true)
	}

	return nil
}
245217
func (daemon *Daemon) Cleanup(container *container.Container) {
	daemon.releaseNetwork(container)

	if err := container.UnmountIpcMount(); err != nil {
		logrus.Warnf("%s cleanup: failed to unmount IPC: %s", container.ID, err)
	}

	if err := daemon.conditionalUnmountOnCleanup(container); err != nil {
		// FIXME: remove once reference counting for graphdrivers has been refactored
		// Ensure that all the mounts are gone
		if mountid, err := daemon.imageService.GetLayerMountID(container.ID, container.OS); err == nil {
			daemon.cleanupMountsByID(mountid)
		}
	}

	if err := container.UnmountSecrets(); err != nil {
		logrus.Warnf("%s cleanup: failed to unmount secrets: %s", container.ID, err)
	}

	if err := mount.RecursiveUnmount(container.Root); err != nil {
		logrus.WithError(err).WithField("container", container.ID).Warn("Error while cleaning up container resource mounts.")
	}

	for _, eConfig := range container.ExecCommands.Commands() {
		daemon.unregisterExecCommand(container, eConfig)
	}

	if container.BaseFS != nil && container.BaseFS.Path() != "" {
		if err := container.UnmountVolumes(daemon.LogVolumeEvent); err != nil {
			logrus.Warnf("%s cleanup: Failed to umount volumes: %v", container.ID, err)
		}
	}

	container.CancelAttachContext()

	if err := daemon.containerd.Delete(context.Background(), container.ID); err != nil {
		logrus.Errorf("%s cleanup: failed to delete container from containerd: %v", container.ID, err)
	}
}
472664
func (s *StepAttachFloppy) Cleanup(state multistep.StateBag) {
	driver := state.Get("driver").(Driver)
	vmName := state.Get("vmName").(string)

	if s.floppyPath == "" {
		return
	}

	log.Println("Detaching floppy disk...")
	command := []string{
		"set", vmName,
		"--device-del", "fdd0",
	}
	driver.Prlctl(command...)
}
92733
func (st *State) Cleanup() (err error) {
	var doc cleanupDoc
	cleanups, closer := st.db().GetCollection(cleanupsC)
	defer closer()

	modelUUID := st.ModelUUID()
	modelId := modelUUID[:6]

	// Only look at cleanups that should be run now.
	query := bson.M{"$or": []bson.M{
		{"when": bson.M{"$lte": st.stateClock.Now()}},
		{"when": bson.M{"$exists": false}},
	}}
	// TODO(jam): 2019-05-01 We used to just query in any order, but that turned
	//  out to *normally* be in sorted order, and some cleanups ended up depending
	//  on that ordering. We shouldn't, but until we can fix the cleanups,
	//  enforce the sort ordering.
	iter := cleanups.Find(query).Sort("_id").Iter()
	defer closeIter(iter, &err, "reading cleanup document")
	for iter.Next(&doc) {
		var err error
		logger.Debugf("model %v cleanup: %v(%q)", modelId, doc.Kind, doc.Prefix)
		args := make([]bson.Raw, len(doc.Args))
		for i, arg := range doc.Args {
			args[i] = arg.Value.(bson.Raw)
		}
		switch doc.Kind {
		case cleanupRelationSettings:
			err = st.cleanupRelationSettings(doc.Prefix)
		case cleanupCharm:
			err = st.cleanupCharm(doc.Prefix)
		case cleanupApplication:
			err = st.cleanupApplication(doc.Prefix, args)
		case cleanupUnitsForDyingApplication:
			err = st.cleanupUnitsForDyingApplication(doc.Prefix, args)
		case cleanupDyingUnit:
			err = st.cleanupDyingUnit(doc.Prefix, args)
		case cleanupForceDestroyedUnit:
			err = st.cleanupForceDestroyedUnit(doc.Prefix, args)
		case cleanupForceRemoveUnit:
			err = st.cleanupForceRemoveUnit(doc.Prefix, args)
		case cleanupDyingUnitResources:
			err = st.cleanupDyingUnitResources(doc.Prefix, args)
		case cleanupRemovedUnit:
			err = st.cleanupRemovedUnit(doc.Prefix, args)
		case cleanupApplicationsForDyingModel:
			err = st.cleanupApplicationsForDyingModel(args)
		case cleanupDyingMachine:
			err = st.cleanupDyingMachine(doc.Prefix, args)
		case cleanupForceDestroyedMachine:
			err = st.cleanupForceDestroyedMachine(doc.Prefix, args)
		case cleanupAttachmentsForDyingStorage:
			err = st.cleanupAttachmentsForDyingStorage(doc.Prefix, args)
		case cleanupAttachmentsForDyingVolume:
			err = st.cleanupAttachmentsForDyingVolume(doc.Prefix)
		case cleanupAttachmentsForDyingFilesystem:
			err = st.cleanupAttachmentsForDyingFilesystem(doc.Prefix)
		case cleanupModelsForDyingController:
			err = st.cleanupModelsForDyingController(args)
		case cleanupMachinesForDyingModel: // IAAS models only
			err = st.cleanupMachinesForDyingModel(args)
		case cleanupResourceBlob:
			err = st.cleanupResourceBlob(doc.Prefix)
		case cleanupStorageForDyingModel:
			err = st.cleanupStorageForDyingModel(args)
		default:
			err = errors.Errorf("unknown cleanup kind %q", doc.Kind)
		}
		if err != nil {
			logger.Warningf(
				"cleanup failed in model %v for %v(%q): %v",
				modelUUID, doc.Kind, doc.Prefix, err,
			)
			continue
		}
		ops := []txn.Op{{
			C:      cleanupsC,
			Id:     doc.DocID,
			Remove: true,
		}}
		if err := st.db().RunTransaction(ops); err != nil {
			return errors.Annotate(err, "cannot remove empty cleanup document")
		}
	}
	return nil
}
658573
func (d *Driver) Cleanup() error {
	logrus.Infof("Stopping libchainfs at %s", virtPath)
	C.stop_chainfs()
	return nil
}
1062058
func (mt *MultiplexTransport) Cleanup(p Peer) {
	mt.conns.RemoveAddr(p.RemoteAddr())
	_ = p.CloseConn()
}
539886
func main() {
	flag.Parse()

	stage1initcommon.InitDebug(debug)

	log, diag, _ = rktlog.NewLogSet("app-rm", debug)
	if !debug {
		diag.SetOutput(ioutil.Discard)
	}

	appName, err := types.NewACName(flagApp)
	if err != nil {
		log.FatalE("invalid app name", err)
	}

	enterCmd := stage1common.PrepareEnterCmd(false)
	switch flagStage {
	case 0:
		// clean resources in stage0
		err = cleanupStage0(appName, enterCmd)
	case 1:
		// clean resources in stage1
		err = cleanupStage1(appName, enterCmd)
	default:
		// unknown step
		err = fmt.Errorf("unsupported cleaning step %d", flagStage)
	}
	if err != nil {
		log.FatalE("cleanup error", err)
	}

	os.Exit(0)
}
185944
func (s *scene) cleanupAllProps() error {
	for _, box := range s.props {
		if box.cleanup != nil {
			err := box.cleanup(box.key, box.prop)
			if err != nil {
				return errors.Annotate(err, ErrCleanupFailed, errorMessages, box.key)
			}
		}
	}
	return nil
}
1319663
func (s *Config) CleanUp() error {
	s.Lock()
	defer s.Unlock()

	return s.impl.CleanUp()
}
256492
func (e *UniversalExecutor) cleanupChildProcesses(proc *os.Process) error {
	// If new process group was created upon command execution
	// we can kill the whole process group now to cleanup any leftovers.
	if e.childCmd.SysProcAttr != nil && e.childCmd.SysProcAttr.Setpgid {
		if err := syscall.Kill(-proc.Pid, syscall.SIGKILL); err != nil && err.Error() != noSuchProcessErr {
			return err
		}
		return nil
	}
	return proc.Kill()
}
494272
func (d *DeviceMapperDriver) Cleanup() error {
	glog.V(2).Infof("Cleanup() START")
	defer glog.V(2).Infof("Cleanup() END")
	if d.DeviceSet == nil {
		return nil
	}
	glog.V(1).Infof("Cleaning up devicemapper driver at %s", d.root)
	for _, volname := range d.List() {
		_, err := d.getVolume(volname, false)
		if err != nil {
			glog.V(1).Infof("Unable to get volume %s; skipping", volname)
			continue
		}
		if err := d.Release(volname); err != nil {
			return err
		}
	}
	return d.DeviceSet.Shutdown()
}
411254
func (i *instanceManager) cleanup() {
	i.shutdownLock.Lock()
	i.pluginLock.Lock()
	defer i.pluginLock.Unlock()
	defer i.shutdownLock.Unlock()

	if i.plugin != nil && !i.plugin.Exited() {
		i.plugin.Kill()
		i.storeReattach(nil)
	}
}