// RemoveVirtualMachines removes VMs matching the given path from the
// system. The path may include wildcards, to match multiple VMs.
967668
func (c *Client) RemoveVirtualMachines(ctx context.Context, path string) error {
	finder, _, err := c.finder(ctx)
	if err != nil {
		return errors.Trace(err)
	}

	vms, err := finder.VirtualMachineList(ctx, path)
	if err != nil {
		if _, ok := err.(*find.NotFoundError); ok {
			c.logger.Debugf("no VMs matching path %q", path)
			return nil
		}
		return errors.Annotatef(err, "listing VMs at %q", path)
	}

	// Retrieve VM details so we know which ones to power off.
	refs := make([]types.ManagedObjectReference, len(vms))
	for i, vm := range vms {
		refs[i] = vm.Reference()
	}
	var mos []mo.VirtualMachine
	if err := c.client.Retrieve(ctx, refs, nil, &mos); err != nil {
		return errors.Annotate(err, "retrieving VM details")
	}

	// We run all tasks in parallel, and wait for them below.
	var lastError error
	tasks := make([]*object.Task, 0, len(vms)*2)
	for i, vm := range vms {
		if mos[i].Runtime.PowerState == types.VirtualMachinePowerStatePoweredOn {
			c.logger.Debugf("powering off %q", vm.Name())
			task, err := vm.PowerOff(ctx)
			if err != nil {
				lastError = errors.Annotatef(err, "powering off %q", vm.Name())
				c.logger.Errorf(err.Error())
				continue
			}
			tasks = append(tasks, task)
		}
		c.logger.Debugf("destroying %q", vm.Name())
		task, err := vm.Destroy(ctx)
		if err != nil {
			lastError = errors.Annotatef(err, "destroying %q", vm.Name())
			c.logger.Errorf(err.Error())
			continue
		}
		tasks = append(tasks, task)
	}

	for _, task := range tasks {
		_, err := task.WaitForResult(ctx, nil)
		if err != nil && !isManagedObjectNotFound(err) {
			lastError = err
			c.logger.Errorf(err.Error())
		}
	}
	return errors.Annotate(lastError, "failed to remove instances")
}
915226
func (s *StorageProvisionerAPIv4) RemoveFilesystemParams(args params.Entities) (params.RemoveFilesystemParamsResults, error) {
	canAccess, err := s.getStorageEntityAuthFunc()
	if err != nil {
		return params.RemoveFilesystemParamsResults{}, err
	}
	results := params.RemoveFilesystemParamsResults{
		Results: make([]params.RemoveFilesystemParamsResult, len(args.Entities)),
	}
	one := func(arg params.Entity) (params.RemoveFilesystemParams, error) {
		tag, err := names.ParseFilesystemTag(arg.Tag)
		if err != nil || !canAccess(tag) {
			return params.RemoveFilesystemParams{}, common.ErrPerm
		}
		filesystem, err := s.sb.Filesystem(tag)
		if errors.IsNotFound(err) {
			return params.RemoveFilesystemParams{}, common.ErrPerm
		} else if err != nil {
			return params.RemoveFilesystemParams{}, err
		}
		if life := filesystem.Life(); life != state.Dead {
			return params.RemoveFilesystemParams{}, errors.Errorf(
				"%s is not dead (%s)",
				names.ReadableString(tag), life,
			)
		}
		filesystemInfo, err := filesystem.Info()
		if err != nil {
			return params.RemoveFilesystemParams{}, err
		}
		provider, _, err := storagecommon.StoragePoolConfig(
			filesystemInfo.Pool, s.poolManager, s.registry,
		)
		if err != nil {
			return params.RemoveFilesystemParams{}, err
		}
		return params.RemoveFilesystemParams{
			Provider:     string(provider),
			FilesystemId: filesystemInfo.FilesystemId,
			Destroy:      !filesystem.Releasing(),
		}, nil
	}
	for i, arg := range args.Entities {
		var result params.RemoveFilesystemParamsResult
		filesystemParams, err := one(arg)
		if err != nil {
			result.Error = common.ServerError(err)
		} else {
			result.Result = filesystemParams
		}
		results.Results[i] = result
	}
	return results, nil
}
1275981
func (c *Client) MigrateVirtualMachine(p *MigrateVirtualMachineParameter) (*VirtualMachine, error) {
	obj, err := c.Request("migrateVirtualMachine", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*VirtualMachine), err
}
779468
func (vm *VM) Destroy() error {
	s, err := vm.getService()
	if err != nil {
		return err
	}

	return s.delete()
}
746549
func (c *Server) RemoveVolume(volumePath string) error {
	c.Lock()
	defer c.Unlock()
	delete(c.volumes, volumePath)
	return nil
}
750906
func (s *VirtualMachineService) ExpungeVirtualMachine(p *ExpungeVirtualMachineParams) (*ExpungeVirtualMachineResponse, error) {
	resp, err := s.cs.newRequest("expungeVirtualMachine", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r ExpungeVirtualMachineResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
1310512
func (az *Cloud) ListVirtualMachines(resourceGroup string) ([]compute.VirtualMachine, error) {
	if az.Config.shouldOmitCloudProviderBackoff() {
		ctx, cancel := getContextWithCancel()
		defer cancel()

		allNodes, err := az.VirtualMachinesClient.List(ctx, resourceGroup)
		if err != nil {
			klog.Errorf("VirtualMachinesClient.List(%v) failure with err=%v", resourceGroup, err)
			return nil, err
		}
		klog.V(2).Infof("VirtualMachinesClient.List(%v) success", resourceGroup)
		return allNodes, nil
	}

	return az.ListVirtualMachinesWithRetry(resourceGroup)
}
277119
func (uvm *UtilityVM) RemoveVSMB(hostPath string) (err error) {
	op := "uvm::RemoveVSMB"
	log := logrus.WithFields(logrus.Fields{
		logfields.UVMID: uvm.id,
		"host-path":     hostPath,
	})
	log.Debug(op + " - Begin Operation")
	defer func() {
		if err != nil {
			log.Data[logrus.ErrorKey] = err
			log.Error(op + " - End Operation - Error")
		} else {
			log.Debug(op + " - End Operation - Success")
		}
	}()

	if uvm.operatingSystem != "windows" {
		return errNotSupported
	}

	uvm.m.Lock()
	defer uvm.m.Unlock()
	share, err := uvm.findVSMBShare(hostPath)
	if err != nil {
		return fmt.Errorf("%s is not present as a VSMB share in %s, cannot remove", hostPath, uvm.id)
	}

	share.refCount--
	if share.refCount > 0 {
		return nil
	}

	modification := &hcsschema.ModifySettingRequest{
		RequestType:  requesttype.Remove,
		Settings:     hcsschema.VirtualSmbShare{Name: share.name},
		ResourcePath: "VirtualMachine/Devices/VirtualSmb/Shares",
	}
	if err := uvm.Modify(modification); err != nil {
		return fmt.Errorf("failed to remove vsmb share %s from %s: %+v: %s", hostPath, uvm.id, modification, err)
	}

	delete(uvm.vsmbShares, hostPath)
	return nil
}
50428
func removeAll(path string) error {
	// Only need special handling for windows
	if runtime.GOOS != "windows" {
		return os.RemoveAll(path)
	}

	// Simple case: if Remove works, we're done.
	err := os.Remove(path)
	if err == nil || os.IsNotExist(err) {
		return nil
	}

	// make sure all files are writable so we can delete them
	err = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
		if err != nil && err != filepath.SkipDir {
			// walk gave us some error, give it back.
			return err
		}
		mode := info.Mode()
		if mode|0200 == mode {
			return nil
		}

		return os.Chmod(path, mode|0200)
	})
	if err != nil {
		return err
	}

	return os.Remove(path)
}
679137
func (s *VirtualMachineService) NewDestroyVirtualMachineParams(id string) *DestroyVirtualMachineParams {
	p := &DestroyVirtualMachineParams{}
	p.p = make(map[string]interface{})
	p.p["id"] = id
	return p
}
620955
func (v *azureVolumeSource) updateVirtualMachines(
	ctx context.ProviderCallContext,
	virtualMachines map[instance.Id]*maybeVirtualMachine, instanceIds []instance.Id,
) ([]error, error) {
	results := make([]error, len(instanceIds))
	vmsClient := compute.VirtualMachinesClient{v.env.compute}
	for i, instanceId := range instanceIds {
		vm, ok := virtualMachines[instanceId]
		if !ok {
			continue
		}
		if vm.err != nil {
			results[i] = vm.err
			continue
		}
		sdkCtx := stdcontext.Background()
		future, err := vmsClient.CreateOrUpdate(
			sdkCtx,
			v.env.resourceGroup, to.String(vm.vm.Name), *vm.vm,
		)
		if err != nil {
			if errorutils.MaybeInvalidateCredential(err, ctx) {
				return nil, errors.Trace(err)
			}
			results[i] = err
			vm.err = err
			continue
		}
		err = future.WaitForCompletionRef(sdkCtx, vmsClient.Client)
		if err != nil {
			results[i] = err
			vm.err = err
			continue
		}
		_, err = future.Result(vmsClient)
		if err != nil {
			results[i] = err
			vm.err = err
			continue
		}
		// successfully updated, don't update again
		delete(virtualMachines, instanceId)
	}
	return results, nil
}
310910
func (sb *storageBackend) removeMachineFilesystemsOps(m *Machine) ([]txn.Op, error) {
	// A machine cannot transition to Dead if it has any detachable storage
	// attached, so any attachments are for machine-bound storage.
	//
	// Even if a filesystem is "non-detachable", there still exist filesystem
	// attachments, and they may be removed independently of the filesystem.
	// For example, the user may request that the filesystem be destroyed.
	// This will cause the filesystem to become Dying, and the attachment
	// to be Dying, then Dead, and finally removed. Only once the attachment
	// is removed will the filesystem transition to Dead and then be removed.
	// Therefore, there may be filesystems that are bound, but not attached,
	// to the machine.
	machineFilesystems, err := sb.filesystems(bson.D{{"hostid", m.Id()}})
	if err != nil {
		return nil, errors.Trace(err)
	}
	ops := make([]txn.Op, 0, 2*len(machineFilesystems)+len(m.doc.Filesystems))
	for _, filesystemId := range m.doc.Filesystems {
		ops = append(ops, txn.Op{
			C:      filesystemAttachmentsC,
			Id:     filesystemAttachmentId(m.Id(), filesystemId),
			Assert: txn.DocExists,
			Remove: true,
		})
	}
	for _, f := range machineFilesystems {
		if f.doc.StorageId != "" {
			// The volume is assigned to a storage instance;
			// make sure we also remove the storage instance.
			// There should be no storage attachments remaining,
			// as the units must have been removed before the
			// machine can be; and the storage attachments must
			// have been removed before the unit can be.
			ops = append(ops,
				txn.Op{
					C:      storageInstancesC,
					Id:     f.doc.StorageId,
					Assert: txn.DocExists,
					Remove: true,
				},
			)
		}
		fsOps, err := removeFilesystemOps(sb, f, f.doc.Releasing, nil)
		if err != nil {
			return nil, errors.Trace(err)
		}
		ops = append(ops, fsOps...)
	}
	return ops, nil
}
1023694
func (f *Facade) RemoveVirtualIP(ctx datastore.Context, vip pool.VirtualIP) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.RemoveVirtualIP"))
	alog := f.auditLogger.Message(ctx, "Removing VirtualIP").Action(audit.Update).
		WithField("virtualip", vip.IP)
	entity, err := f.GetResourcePool(ctx, vip.PoolID)
	if err != nil {
		return alog.Error(err)
	} else if entity == nil {
		return alog.Error(ErrPoolNotExists)
	}
	alog = alog.Entity(entity)
	if err := f.removeVirtualIP(ctx, vip.PoolID, vip.IP); err != nil {
		return alog.Error(err)
	}
	for i, currentVIP := range entity.VirtualIPs {
		if currentVIP.IP == vip.IP {
			entity.VirtualIPs = append(entity.VirtualIPs[:i], entity.VirtualIPs[i+1:]...)
			break
		}
	}

	// grab all services that are assigned to that virtual ip
	query := []string{fmt.Sprintf("Endpoints.AddressAssignment.IPAddr:%s", vip.IP)}
	services, err := f.GetTaggedServices(ctx, query)
	if err != nil {
		glog.Errorf("Failed to grab services with endpoints assigned to ip %s: %s", vip.IP, err)
		return alog.Error(err)
	}

	evtctx := newEventCtx()
	err = f.beforeEvent(beforePoolUpdate, evtctx, entity)
	defer f.afterEvent(afterPoolUpdate, evtctx, entity, err)
	if err != nil {
		return alog.Error(err)
	} else if err = f.poolStore.Put(ctx, pool.Key(entity.ID), entity); err != nil {
		return alog.Error(err)
	} else if err = f.zzk.UpdateResourcePool(entity); err != nil {
		return alog.Error(err)
	}

	// update address assignments
	for _, svc := range services {
		request := addressassignment.AssignmentRequest{
			ServiceID:      svc.ID,
			IPAddress:      "",
			AutoAssignment: true,
		}
		if err = f.AssignIPs(ctx, request); err != nil {
			glog.Warningf("Failed assigning another ip to service %s: %s", svc.ID, err)
			alog.Error(err)
		}
	}
	alog.Succeeded()
	return nil
}
252176
func (vm *VM) Destroy() (err error) {
	err = vm.haltWithFlag(true)
	if err != nil {
		return err
	}
	if vm.Dst != "" {
		err = os.RemoveAll(vm.Dst)
		if err != nil {
			err = lvm.ErrDeletingVM
			return
		}
	}
	return
}
968902
func removeAll(dirPath string) (err error) {
	if dirPath == "" {
		return errInvalidArgument
	}

	if err = checkPathLength(dirPath); err != nil {
		return err
	}

	if err = reliableRemoveAll(dirPath); err != nil {
		switch {
		case isSysErrNotDir(err):
			// File path cannot be verified since one of
			// the parents is a file.
			return errFileAccessDenied
		case isSysErrPathNotFound(err):
			// This is a special case should be handled only for
			// windows, because windows API does not return "not a
			// directory" error message. Handle this specifically
			// here.
			return errFileAccessDenied
		}
	}
	return err
}
120142
func removeFilesystems(ctx *context, ops map[names.FilesystemTag]*removeFilesystemOp) error {
	tags := make([]names.FilesystemTag, 0, len(ops))
	for tag := range ops {
		tags = append(tags, tag)
	}
	removeFilesystemParams, err := removeFilesystemParams(ctx, tags)
	if err != nil {
		return errors.Trace(err)
	}
	filesystemParams := make([]storage.FilesystemParams, len(tags))
	removeFilesystemParamsByTag := make(map[names.FilesystemTag]params.RemoveFilesystemParams)
	for i, args := range removeFilesystemParams {
		removeFilesystemParamsByTag[tags[i]] = args
		filesystemParams[i] = storage.FilesystemParams{
			Tag:      tags[i],
			Provider: storage.ProviderType(args.Provider),
		}
	}
	paramsBySource, filesystemSources, err := filesystemParamsBySource(
		ctx.config.StorageDir,
		filesystemParams,
		ctx.managedFilesystemSource,
		ctx.config.Registry,
	)
	if err != nil {
		return errors.Trace(err)
	}
	var remove []names.Tag
	var reschedule []scheduleOp
	var statuses []params.EntityStatusArgs
	removeFilesystems := func(tags []names.FilesystemTag, 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 filesystem; 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, "removing filesystem").Error(),
			})
		}
		return nil
	}
	for sourceName, filesystemParams := range paramsBySource {
		logger.Debugf("removing filesystems from %q: %v", sourceName, filesystemParams)
		filesystemSource := filesystemSources[sourceName]
		removeTags := make([]names.FilesystemTag, len(filesystemParams))
		removeParams := make([]params.RemoveFilesystemParams, len(filesystemParams))
		for i, args := range filesystemParams {
			removeTags[i] = args.Tag
			removeParams[i] = removeFilesystemParamsByTag[args.Tag]
		}
		destroyTags, destroyIds, releaseTags, releaseIds := partitionRemoveFilesystemParams(removeTags, removeParams)
		if err := removeFilesystems(destroyTags, destroyIds, filesystemSource.DestroyFilesystems); err != nil {
			return errors.Trace(err)
		}
		if err := removeFilesystems(releaseTags, releaseIds, filesystemSource.ReleaseFilesystems); err != nil {
			return errors.Trace(err)
		}
	}
	scheduleOperations(ctx, reschedule...)
	setStatus(ctx, statuses)
	if err := removeEntities(ctx, remove); err != nil {
		return errors.Annotate(err, "removing filesystems from state")
	}
	return nil
}
1271807
func restRemoveVirtualHost(w *rest.ResponseWriter, r *rest.Request, ctx *requestContext) {
	serviceid, application, vhost, err := getVHostContext(r)
	if err != nil {
		restServerError(w, err)
		return
	}

	glog.V(2).Info("Removing vhost %d from service (%s)", vhost, serviceid)

	facade := ctx.getFacade()
	dataCtx := ctx.getDatastoreContext()

	err = facade.RemovePublicEndpointVHost(dataCtx, serviceid, application, vhost)
	if err != nil {
		glog.Error(err)
		restServerError(w, err)
		return
	}

	restSuccess(w)
}