// AssignToNewMachine assigns the unit to a new machine, with constraints
// determined according to the application and model constraints at the
// time of unit creation.
325761
func (u *Unit) AssignToNewMachine() (err error) {
	defer assignContextf(&err, u.Name(), "new machine")
	return u.assignToNewMachine("")
}
684405
func (st *State) AssignUnit(u *Unit, policy AssignmentPolicy) (err error) {
	if !u.IsPrincipal() {
		return errors.Errorf("subordinate unit %q cannot be assigned directly to a machine", u)
	}
	defer errors.DeferredAnnotatef(&err, "cannot assign unit %q to machine", u)
	var m *Machine
	switch policy {
	case AssignLocal:
		m, err = st.Machine("0")
		if err != nil {
			return errors.Trace(err)
		}
		return u.AssignToMachine(m)
	case AssignClean:
		if _, err = u.AssignToCleanMachine(); errors.Cause(err) != noCleanMachines {
			return errors.Trace(err)
		}
		return u.AssignToNewMachineOrContainer()
	case AssignCleanEmpty:
		if _, err = u.AssignToCleanEmptyMachine(); errors.Cause(err) != noCleanMachines {
			return errors.Trace(err)
		}
		return u.AssignToNewMachineOrContainer()
	case AssignNew:
		return errors.Trace(u.AssignToNewMachine())
	}
	return errors.Errorf("unknown unit assignment policy: %q", policy)
}
185906
func (client *Client) AddMachines(machineParams []params.AddMachineParams) ([]params.AddMachinesResult, error) {
	args := params.AddMachines{
		MachineParams: machineParams,
	}
	results := new(params.AddMachinesResults)
	err := client.facade.FacadeCall("AddMachines", args, results)
	if len(results.Machines) != len(machineParams) {
		return nil, errors.Errorf("expected %d result, got %d", len(machineParams), len(results.Machines))
	}
	return results.Machines, err
}
544591
func (c *Conn) GetMachine(name string) (dbus.ObjectPath, error) {
	return c.getPath("GetMachine", name)
}
1187813
func (h *bundleHandler) addMachine(change *bundlechanges.AddMachineChange) error {
	p := change.Params
	var verbose []string
	if p.Series != "" {
		verbose = append(verbose, fmt.Sprintf("with series %q", p.Series))
	}
	if p.Constraints != "" {
		verbose = append(verbose, fmt.Sprintf("with constraints %q", p.Constraints))
	}
	if output := strings.Join(verbose, ", "); output != "" {
		h.ctx.Verbosef("  %s", output)
	}
	if h.dryRun {
		return nil
	}

	deployedApps := func() string {
		apps := h.applicationsForMachineChange(change.Id())
		// Note that we *should* always have at least one application
		// that justifies the creation of this machine. But just in
		// case, check (see https://pad.lv/1773357).
		if len(apps) == 0 {
			h.ctx.Warningf("no applications found for machine change %q", change.Id())
			return "nothing"
		}
		msg := apps[0] + " unit"

		if count := len(apps); count != 1 {
			msg = strings.Join(apps[:count-1], ", ") + " and " + apps[count-1] + " units"
		}
		return msg
	}

	cons, err := constraints.Parse(p.Constraints)
	if err != nil {
		// This should never happen, as the bundle is already verified.
		return errors.Annotate(err, "invalid constraints for machine")
	}
	machineParams := params.AddMachineParams{
		Constraints: cons,
		Series:      p.Series,
		Jobs:        []multiwatcher.MachineJob{multiwatcher.JobHostUnits},
	}
	if ct := p.ContainerType; ct != "" {
		// TODO(thumper): move the warning and translation into the bundle reading code.

		// for backwards compatibility with 1.x bundles, we treat lxc
		// placement directives as lxd.
		if ct == "lxc" {
			if !h.warnedLXC {
				h.ctx.Infof("Bundle has one or more containers specified as lxc. lxc containers are deprecated in Juju 2.0. lxd containers will be deployed instead.")
				h.warnedLXC = true
			}
			ct = string(instance.LXD)
		}
		containerType, err := instance.ParseContainerType(ct)
		if err != nil {
			return errors.Annotatef(err, "cannot create machine for holding %s", deployedApps())
		}
		machineParams.ContainerType = containerType
		if p.ParentId != "" {
			logger.Debugf("p.ParentId: %q", p.ParentId)
			id, err := h.resolveMachine(p.ParentId)
			if err != nil {
				return errors.Annotatef(err, "cannot retrieve parent placement for %s", deployedApps())
			}
			// Never create nested containers for deployment.
			machineParams.ParentId = h.topLevelMachine(id)
		}
	}
	logger.Debugf("machineParams: %s", pretty.Sprint(machineParams))
	r, err := h.api.AddMachines([]params.AddMachineParams{machineParams})
	if err != nil {
		return errors.Annotatef(err, "cannot create machine for holding %s", deployedApps())
	}
	if r[0].Error != nil {
		return errors.Annotatef(r[0].Error, "cannot create machine for holding %s", deployedApps())
	}
	machine := r[0].Machine
	if p.ContainerType == "" {
		logger.Debugf("created new machine %s for holding %s", machine, deployedApps())
	} else if p.ParentId == "" {
		logger.Debugf("created %s container in new machine for holding %s", machine, deployedApps())
	} else {
		logger.Debugf("created %s container in machine %s for holding %s", machine, machineParams.ParentId, deployedApps())
	}
	h.results[change.Id()] = machine
	return nil
}
1038448
func (vb *VirtualBox) FindMachine(nameOrID string) (*Machine, error) {
	if err := vb.assertMobRef(); err != nil {
		return nil, err
	}

	request := findMachineRequest{VbID: vb.mobref, NameOrID: nameOrID}
	response := new(findMachineResponse)
	err := vb.send(request, response)
	if err != nil {
		return nil, err
	}

	m := &Machine{mobref: response.Returnval, vb: vb}
	return m, nil
}
396713
func (*Service) CreateMachine(c context.Context, req *crimson.CreateMachineRequest) (*crimson.Machine, error) {
	if err := createMachine(c, req.Machine); err != nil {
		return nil, err
	}
	return req.Machine, nil
}
820201
func (*Service) UpdateMachine(c context.Context, req *crimson.UpdateMachineRequest) (*crimson.Machine, error) {
	return updateMachine(c, req.Machine, req.UpdateMask)
}
76989
func (u *Unit) machine() (*Machine, error) {
	id, err := u.AssignedMachineId()
	if err != nil {
		return nil, errors.Annotatef(err, "unit %v cannot get assigned machine", u)
	}
	m, err := u.st.Machine(id)
	if err != nil {
		return nil, errors.Annotatef(err, "unit %v misses machine id %v", u, id)
	}
	return m, nil
}
364306
func (st *State) addMachineOps(template MachineTemplate) (*machineDoc, []txn.Op, error) {
	template, err := st.effectiveMachineTemplate(template, st.IsController())
	if err != nil {
		return nil, nil, err
	}
	if template.InstanceId == "" {
		volumeAttachments, err := st.machineTemplateVolumeAttachmentParams(template)
		if err != nil {
			return nil, nil, err
		}
		if err := st.precheckInstance(
			template.Series,
			template.Constraints,
			template.Placement,
			volumeAttachments,
		); err != nil {
			return nil, nil, err
		}
	}
	seq, err := sequence(st, "machine")
	if err != nil {
		return nil, nil, err
	}
	mdoc := st.machineDocForTemplate(template, strconv.Itoa(seq))
	prereqOps, machineOp, err := st.insertNewMachineOps(mdoc, template)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}
	prereqOps = append(prereqOps, assertModelActiveOp(st.ModelUUID()))
	prereqOps = append(prereqOps, insertNewContainerRefOp(st, mdoc.Id))
	if template.InstanceId != "" {
		prereqOps = append(prereqOps, txn.Op{
			C:      instanceDataC,
			Id:     mdoc.DocID,
			Assert: txn.DocMissing,
			Insert: &instanceData{
				DocID:          mdoc.DocID,
				MachineId:      mdoc.Id,
				InstanceId:     template.InstanceId,
				ModelUUID:      mdoc.ModelUUID,
				Arch:           template.HardwareCharacteristics.Arch,
				Mem:            template.HardwareCharacteristics.Mem,
				RootDisk:       template.HardwareCharacteristics.RootDisk,
				RootDiskSource: template.HardwareCharacteristics.RootDiskSource,
				CpuCores:       template.HardwareCharacteristics.CpuCores,
				CpuPower:       template.HardwareCharacteristics.CpuPower,
				Tags:           template.HardwareCharacteristics.Tags,
				AvailZone:      template.HardwareCharacteristics.AvailabilityZone,
			},
		})
	}

	return mdoc, append(prereqOps, machineOp), nil
}
229871
func (srv *Instance) StartMachine(ctx context.Context, wg *sync.WaitGroup) (err error) {
	if srv.cfg.Choria.MachineSourceDir == "" {
		return fmt.Errorf("Choria Autonomous Agent source directory not configured, skipping initialization")
	}

	srv.machines, err = aagent.New(srv.cfg.Choria.MachineSourceDir, srv)
	if err != nil {
		return err
	}

	return srv.machines.ManageMachines(ctx, wg)
}
893458
func (fw *Firewaller) startMachine(tag names.MachineTag) error {
	machined := &machineData{
		fw:           fw,
		tag:          tag,
		unitds:       make(map[names.UnitTag]*unitData),
		ingressRules: make([]network.IngressRule, 0),
		definedPorts: make(map[names.UnitTag]portRanges),
	}
	m, err := machined.machine()
	if params.IsCodeNotFound(err) {
		logger.Debugf("not watching %q", tag)
		return nil
	} else if err != nil {
		return errors.Annotate(err, "cannot watch machine units")
	}
	manual, err := m.IsManual()
	if err != nil {
		return errors.Trace(err)
	}
	if manual {
		// Don't track manual machines, we can't change their ports.
		logger.Debugf("not watching manual %q", tag)
		return nil
	}
	unitw, err := m.WatchUnits()
	if err != nil {
		return errors.Trace(err)
	}
	// XXX(fwereade): this is the best of a bunch of bad options. We've started
	// the watch, so we're responsible for it; but we (probably?) need to do this
	// little dance below to update the machined data on the fw loop goroutine,
	// whence it's usually accessed, before we start the machined watchLoop
	// below. That catacomb *should* be the only one responsible -- and it *is*
	// responsible -- but having it in the main fw catacomb as well does no harm,
	// and greatly simplifies the code below (which would otherwise have to
	// manage unitw lifetime and errors manually).
	if err := fw.catacomb.Add(unitw); err != nil {
		return errors.Trace(err)
	}
	select {
	case <-fw.catacomb.Dying():
		return fw.catacomb.ErrDying()
	case change, ok := <-unitw.Changes():
		if !ok {
			return errors.New("machine units watcher closed")
		}
		fw.machineds[tag] = machined
		err = fw.unitsChanged(&unitsChange{machined, change})
		if err != nil {
			delete(fw.machineds, tag)
			return errors.Annotatef(err, "cannot respond to units changes for %q", tag)
		}
	}

	err = catacomb.Invoke(catacomb.Plan{
		Site: &machined.catacomb,
		Work: func() error {
			return machined.watchLoop(unitw)
		},
	})
	if err != nil {
		delete(fw.machineds, tag)
		return errors.Trace(err)
	}

	// register the machined with the firewaller's catacomb.
	err = fw.catacomb.Add(machined)
	if err == nil {
		logger.Debugf("started watching %q", tag)
	}
	return err
}
251390
func (u *Unit) assignToCleanMaybeEmptyMachine(requireEmpty bool) (*Machine, error) {
	var m *Machine
	buildTxn := func(attempt int) ([]txn.Op, error) {
		var err error
		u := u // don't change outer var
		if attempt > 0 {
			u, err = u.st.Unit(u.Name())
			if err != nil {
				return nil, errors.Trace(err)
			}
		}
		var ops []txn.Op
		m, ops, err = u.assignToCleanMaybeEmptyMachineOps(requireEmpty)
		return ops, err
	}
	if err := u.st.db().Run(buildTxn); err != nil {
		return nil, errors.Trace(err)
	}
	u.doc.MachineId = m.doc.Id
	m.doc.Clean = false
	return m, nil
}
427284
func (c *Controller) updateMachine(ch MachineChange) {
	c.ensureModel(ch.ModelUUID).updateMachine(ch, c.manager)
}
118419
func (m *Machine) SetMachineBlockDevices(info ...BlockDeviceInfo) error {
	return setMachineBlockDevices(m.st, m.Id(), info)
}
127219
func (c *CloudAPI) ResizeMachine(machineID, packageName string) error {
	if err := c.ProcessFunctionHook(c, machineID, packageName); err != nil {
		return err
	}

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

	for _, machine := range c.machines {
		if machine.Id == machineID {
			machine.Package = packageName
			machine.Memory = mPkg.Memory
			machine.Disk = mPkg.Disk
			machine.Updated = time.Now().Format("2013-11-26T19:47:13.448Z")
			return nil
		}
	}

	return fmt.Errorf("Machine %s not found", machineID)
}
347298
func createMachine(orgID, teamID, creatorID *identity.ID, name string) (
	*envelope.Machine, []envelope.Membership, error) {

	machineBody := &primitive.Machine{
		Name:        name,
		OrgID:       orgID,
		CreatedBy:   creatorID,
		Created:     time.Now().UTC(),
		DestroyedBy: nil,
		Destroyed:   nil,
		State:       primitive.MachineActiveState,
	}
	machineID, err := identity.NewMutable(machineBody)
	if err != nil {
		return nil, nil, err
	}
	machine := envelope.Machine{
		ID:      &machineID,
		Version: 1,
		Body:    machineBody,
	}

	machineTeamID := identity.DeriveMutable(&primitive.Team{}, orgID, primitive.DerivableMachineTeamSymbol)
	teamIDList := []*identity.ID{&machineTeamID, teamID}
	var memberships []envelope.Membership
	for _, curTeamID := range teamIDList {
		body := primitive.Membership{
			OwnerID: &machineID,
			OrgID:   orgID,
			TeamID:  curTeamID,
		}

		ID, err := identity.NewMutable(&body)
		if err != nil {
			return nil, nil, err
		}

		membership := envelope.Membership{
			ID:      &ID,
			Version: 1,
			Body:    &body,
		}
		memberships = append(memberships, membership)
	}

	return &machine, memberships, nil
}