// DeleteMachine Shutdown and Delete a droplet
970757
func (p *Provider) DeleteMachine() (err error) {
	err = p.Host.Driver.Remove()
	defer p.Client.Close()
	return
}
1325177
func (c *Client) DeleteMacro(ctx context.Context, id platform.ID) error {
	op := getOp(platform.OpDeleteMacro)
	return c.db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket(macroBucket)

		encID, err := id.Encode()
		if err != nil {
			return &platform.Error{
				Code: platform.EInvalid,
				Op:   op,
				Err:  err,
			}
		}

		d := b.Get(encID)
		if d == nil {
			return &platform.Error{
				Code: platform.ENotFound,
				Op:   op,
				Msg:  "macro not found",
			}
		}

		if err := b.Delete(encID); err != nil {
			return &platform.Error{
				Op:  op,
				Err: err,
			}
		}

		return nil
	})
}
1061995
func (c *CloudAPI) DeleteMachine(machineID string) error {
	if err := c.ProcessFunctionHook(c, machineID); err != nil {
		return err
	}

	for i, machine := range c.machines {
		if machine.Id == machineID {
			if machine.State == "stopped" {
				c.machines = append(c.machines[:i], c.machines[i+1:]...)
				return nil
			}

			return fmt.Errorf("Cannot Delete machine %s, machine is not stopped.", machineID)
		}
	}

	return fmt.Errorf("Machine %s not found", machineID)
}
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
}
286427
func DestroyMachine(c *kvmContainer) error {
	if c.runCmd == nil {
		c.runCmd = run
	}
	if c.pathfinder == nil {
		c.pathfinder = paths.DataDir
	}

	// We don't return errors for virsh commands because it is possible that we
	// didn't succeed in creating the domain. Additionally, we want all the
	// commands to run. If any fail it is certainly because the thing we're
	// trying to remove wasn't created. However, we still want to try removing
	// all the parts. The exception here is getting the guestBase, if that
	// fails we return the error because we cannot continue without it.

	_, err := c.runCmd("", virsh, "destroy", c.Name())
	if err != nil {
		logger.Infof("`%s destroy %s` failed: %q", virsh, c.Name(), err)
	}

	// The nvram flag here removes the pflash drive for us. There is also a
	// `remove-all-storage` flag, but it is unclear if that would also remove
	// the backing store which we don't want to do. So we remove those manually
	// after undefining.
	_, err = c.runCmd("", virsh, "undefine", "--nvram", c.Name())
	if err != nil {
		logger.Infof("`%s undefine --nvram %s` failed: %q", virsh, c.Name(), err)
	}
	guestBase, err := guestPath(c.pathfinder)
	if err != nil {
		return errors.Trace(err)
	}
	err = os.Remove(filepath.Join(guestBase, fmt.Sprintf("%s.qcow", c.Name())))
	if err != nil {
		logger.Errorf("failed to remove system disk for %q: %s", c.Name(), err)
	}
	err = os.Remove(filepath.Join(guestBase, fmt.Sprintf("%s-ds.iso", c.Name())))
	if err != nil {
		logger.Errorf("failed to remove cloud-init data disk for %q: %s", c.Name(), err)
	}

	return nil
}
764135
func (s *Service) DeleteMacro(ctx context.Context, id platform.ID) error {
	op := OpPrefix + platform.OpDeleteMacro
	_, err := s.FindMacroByID(ctx, id)
	if err != nil {
		return &platform.Error{
			Op:   op,
			Code: platform.ENotFound,
			Msg:  "macro not found",
			Err:  err,
		}
	}

	s.macroKV.Delete(id.String())

	return nil
}
48644
func (c *CloudAPI) CreateMachine(name, pkg, image string, networks []string, metadata, tags map[string]string) (*cloudapi.Machine, error) {
	if err := c.ProcessFunctionHook(c, name, pkg, image); err != nil {
		return nil, err
	}

	machineID, err := localservices.NewUUID()
	if err != nil {
		return nil, err
	}

	mPkg, err := c.GetPackage(pkg)
	if err != nil {
		return nil, err
	}

	mImg, err := c.GetImage(image)
	if err != nil {
		return nil, err
	}

	mNetworks := []string{}
	for _, network := range networks {
		mNetwork, err := c.GetNetwork(network)
		if err != nil {
			return nil, err
		}

		mNetworks = append(mNetworks, mNetwork.Id)
	}

	publicIP := generatePublicIPAddress()

	newMachine := cloudapi.Machine{
		Id:        machineID,
		Name:      name,
		Type:      mImg.Type,
		State:     "running",
		Memory:    mPkg.Memory,
		Disk:      mPkg.Disk,
		IPs:       []string{publicIP, generatePrivateIPAddress()},
		Created:   time.Now().Format("2013-11-26T19:47:13.448Z"),
		Package:   pkg,
		Image:     image,
		Metadata:  metadata,
		Tags:      tags,
		PrimaryIP: publicIP,
		Networks:  mNetworks,
	}

	nics := map[string]*cloudapi.NIC{}
	nicNetworks := map[string]string{}
	for i, network := range mNetworks {
		mac, err := localservices.NewMAC()
		if err != nil {
			return nil, err
		}

		nics[mac] = &cloudapi.NIC{
			IP:      fmt.Sprintf("10.88.88.%d", i),
			MAC:     mac,
			Primary: i == 0,
			Netmask: "255.255.255.0",
			Gateway: "10.88.88.2",
			State:   cloudapi.NICStateRunning,
			Network: network,
		}
		nicNetworks[mac] = network
	}

	c.machines = append(c.machines, &machine{newMachine, nics, nicNetworks})

	return &newMachine, nil
}
820201
func (*Service) UpdateMachine(c context.Context, req *crimson.UpdateMachineRequest) (*crimson.Machine, error) {
	return updateMachine(c, req.Machine, req.UpdateMask)
}
1250663
func (st *State) AddOneMachine(template MachineTemplate) (*Machine, error) {
	ms, err := st.AddMachines(template)
	if err != nil {
		return nil, err
	}
	return ms[0], nil
}
764643
func (s *Service) AddMachine(componentsmachineproviderrpcmessagescatalogmachineadditionrequest *ComponentsMachineProviderRpcMessagesCatalogMachineAdditionRequest) *AddMachineCall {
	c := &AddMachineCall{s: s, urlParams_: make(gensupport.URLParams)}
	c.componentsmachineproviderrpcmessagescatalogmachineadditionrequest = componentsmachineproviderrpcmessagescatalogmachineadditionrequest
	return c
}
693005
func controllerMachineIds(st *state.State, m *state.Machine) ([]string, error) {
	info, err := st.ControllerInfo()
	if err != nil {
		return nil, err
	}
	result := set.NewStrings(info.MachineIds...)
	result.Remove(m.Id())
	return result.SortedValues(), nil
}
1133842
func (c *CloudAPI) DisableFirewallMachine(machineID string) error {
	if err := c.ProcessFunctionHook(c, machineID); err != nil {
		return err
	}

	machine, err := c.GetMachine(machineID)
	if err != nil {
		return err
	}

	machine.FirewallEnabled = false

	return nil
}
699621
func (c *MemStore) RemoveModel(controller, model string) error {
	c.mu.Lock()
	defer c.mu.Unlock()

	if err := ValidateControllerName(controller); err != nil {
		return err
	}
	if err := ValidateModelName(model); err != nil {
		return err
	}
	controllerModels, ok := c.Models[controller]
	if !ok {
		return errors.NotFoundf("models for controller %s", controller)
	}
	if _, ok := controllerModels.Models[model]; !ok {
		return errors.NotFoundf("model %s:%s", controller, model)
	}
	delete(controllerModels.Models, model)
	return nil
}
671922
func (env *sessionEnviron) finishMachineConfig(args environs.StartInstanceParams, img *OvaFileMetadata) error {
	envTools, err := args.Tools.Match(tools.Filter{Arch: img.Arch})
	if err != nil {
		return err
	}
	if err := args.InstanceConfig.SetTools(envTools); err != nil {
		return errors.Trace(err)
	}
	return FinishInstanceConfig(args.InstanceConfig, env.Config())
}
164968
func (a *AAgent) ManageMachines(ctx context.Context, wg *sync.WaitGroup) error {
	wg.Add(1)
	go a.watchSource(ctx, wg)

	return nil
}
46735
func (c *Client) StopMachine(machineID string) error {
	req := request{
		method:         client.POST,
		url:            fmt.Sprintf("%s/%s?action=%s", apiMachines, machineID, actionStop),
		expectedStatus: http.StatusAccepted,
	}
	if _, err := c.sendRequest(req); err != nil {
		return errors.Newf(err, "failed to stop machine with id: %s", machineID)
	}
	return nil
}
393243
func (st *State) cleanupMachinesForDyingModel(cleanupArgs []bson.Raw) (err error) {
	var args DestroyModelParams
	switch n := len(cleanupArgs); n {
	case 0:
	// Old cleanups have no args, so follow the old behaviour.
	case 1:
		if err := cleanupArgs[0].Unmarshal(&args); err != nil {
			return errors.Annotate(err, "unmarshalling cleanup 'destroy model' args")
		}
	default:
		return errors.Errorf("expected 0-1 arguments, got %d", n)
	}
	// This won't miss machines, because a Dying model cannot have
	// machines added to it. But we do have to remove the machines themselves
	// via individual transactions, because they could be in any state at all.
	machines, err := st.AllMachines()
	if err != nil {
		return errors.Trace(err)
	}
	force := args.Force != nil && *args.Force
	for _, m := range machines {
		if m.IsManager() {
			continue
		}
		if _, isContainer := m.ParentId(); isContainer {
			continue
		}
		manual, err := m.IsManual()
		if err != nil {
			// TODO (force 2019-4-24) we should not break out here but continue with other machines.
			return errors.Trace(err)
		}
		if manual {
			// Manually added machines should never be force-
			// destroyed automatically. That should be a user-
			// driven decision, since it may leak applications
			// and resources on the machine. If something is
			// stuck, then the user can still force-destroy
			// the manual machines.
			if err := m.Destroy(); err != nil {
				// Since we cannot delete a manual machine, we cannot proceed with model destruction even if it is forced.
				// TODO (force 2019-4-24) However, we should not break out here but continue with other machines.
				return errors.Trace(errors.Annotatef(err, "could not destroy manual machine %v", m.Id()))
			}
			return nil
		}
		// TODO (force 2019-04-26) Should this always be ForceDestroy or only when
		// 'destroy-model --force' is specified?...
		if err := m.ForceDestroy(args.MaxWait); err != nil {
			err = errors.Annotatef(err, "while destroying machine %v is", m.Id())
			// TODO (force 2019-4-24) we should not break out here but continue with other machines.
			if !force {
				return errors.Trace(err)
			}
			logger.Warningf("%v", err)
		}
	}
	return nil
}