// AddMachineInsideMachine adds a machine inside a container of the
// given type on the existing machine with id=parentId.
549644
func (st *State) AddMachineInsideMachine(template MachineTemplate, parentId string, containerType instance.ContainerType) (*Machine, error) {
	mdoc, ops, err := st.addMachineInsideMachineOps(template, parentId, containerType)
	if err != nil {
		return nil, errors.Annotate(err, "cannot add a new machine")
	}
	return st.addMachine(mdoc, ops)
}
1002636
func ProvisionMachine(args manual.ProvisionMachineArgs) (machineId string, err error) {
	defer func() {
		if machineId != "" && err != nil {
			logger.Errorf("provisioning failed, removing machine %v: %v", machineId, err)
			if cleanupErr := args.Client.ForceDestroyMachines(machineId); cleanupErr != nil {
				logger.Errorf("error cleaning up machine: %s", cleanupErr)
			}
			machineId = ""
		}
	}()

	if err = InitAdministratorUser(&args); err != nil {
		return "", errors.Annotatef(err,
			"Cannot provision machine because no WinRM http/https standard listener is enabled for user %q, on host %q",
			args.User, args.Host)
	}

	machineParams, err := gatherMachineParams(args.Host, args.WinRM.Client)
	if err != nil {
		return "", err
	}

	machineId, err = manual.RecordMachineInState(args.Client, *machineParams)
	if err != nil {
		return "", err
	}

	provisioningScript, err := args.Client.ProvisioningScript(params.ProvisioningScriptParams{
		MachineId:              machineId,
		Nonce:                  machineParams.Nonce,
		DisablePackageCommands: true,
	})

	if err != nil {
		return "", err
	}

	// Finally, provision the machine agent.
	err = runProvisionScript(provisioningScript, args.WinRM.Client, args.Stdout, args.Stderr)
	if err != nil {
		return "", err
	}

	logger.Infof("Provisioned machine %v", machineId)
	return machineId, nil
}
464881
func (m *Manager) SetMachine(t interface{}) (err error) {
	machine, ok := t.(Machine)
	if !ok {
		return errors.New("supplied machine does not implement watchers.Machine")
	}

	m.machine = machine

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

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

	return fmt.Errorf("Machine %s not found", machineID)
}
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
}
1123154
func ProvideMachine(ctx context.Context, service iaas.Iaas) (client *docker.Client, machine *iaas.Machine, err error) {
	machine, err = service.CreateMachine()
	if err != nil {
		if machine != nil {
			cerr := service.DeleteMachine()
			if cerr != nil {
				log.Errorln(cerr)
			}
		}
		return
	}
	if machine.Port == 0 {
		machine.Port = dockerPort
	}
	addr := fmt.Sprintf("%s:%d", machine.IP, machine.Port)
	client, err = provision.FnClient(addr, machine.CertsDir)
	return
}
427284
func (c *Controller) updateMachine(ch MachineChange) {
	c.ensureModel(ch.ModelUUID).updateMachine(ch, c.manager)
}
1210134
func (v VirtualMachine) AddDevice(ctx context.Context, device ...types.BaseVirtualDevice) error {
	return v.configureDevice(ctx, types.VirtualDeviceConfigSpecOperationAdd, types.VirtualDeviceConfigSpecFileOperationCreate, device...)
}
74108
func (m *API) GetMachineProviderInterfaceInfo(machines params.Entities) params.ProviderInterfaceInfoResults {
	results := make([]params.ProviderInterfaceInfoResult, len(machines.Entities))
	for i, entity := range machines.Entities {
		results[i].MachineTag = entity.Tag

		interfaces, err := m.getInterfaceInfoForOneMachine(entity.Tag)
		if err != nil {
			results[i].Error = common.ServerError(err)
			continue
		}

		infos := make([]params.ProviderInterfaceInfo, len(interfaces))
		for i, info := range interfaces {
			infos[i].InterfaceName = info.InterfaceName
			infos[i].MACAddress = info.MACAddress
			infos[i].ProviderId = string(info.ProviderId)
		}

		results[i].Interfaces = infos
	}
	return params.ProviderInterfaceInfoResults{results}
}
1154708
func (m *Model) removeMachine(ch RemoveMachine) error {
	defer m.doLocked()()

	machine, ok := m.machines[ch.Id]
	if ok {
		m.hub.Publish(m.topic(modelAddRemoveMachine), []string{ch.Id})
		if err := machine.evict(); err != nil {
			return errors.Trace(err)
		}
		delete(m.machines, ch.Id)
	}
	return nil
}
1330426
func (u *Unit) assignToNewMachine(placement string) error {
	if u.doc.Principal != "" {
		return fmt.Errorf("unit is a subordinate")
	}
	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)
			}
		}
		cons, err := u.Constraints()
		if err != nil {
			return nil, err
		}
		var containerType instance.ContainerType
		if cons.HasContainer() {
			containerType = *cons.Container
		}
		storageParams, err := u.storageParams()
		if err != nil {
			return nil, errors.Trace(err)
		}
		template := MachineTemplate{
			Series:                u.doc.Series,
			Constraints:           *cons,
			Jobs:                  []MachineJob{JobHostUnits},
			Placement:             placement,
			Dirty:                 placement != "",
			Volumes:               storageParams.volumes,
			VolumeAttachments:     storageParams.volumeAttachments,
			Filesystems:           storageParams.filesystems,
			FilesystemAttachments: storageParams.filesystemAttachments,
		}
		// Get the ops necessary to create a new machine, and the
		// machine doc that will be added with those operations
		// (which includes the machine id).
		var ops []txn.Op
		m, ops, err = u.assignToNewMachineOps(template, "", containerType)
		return ops, err
	}
	if err := u.st.db().Run(buildTxn); err != nil {
		return errors.Trace(err)
	}
	u.doc.MachineId = m.doc.Id
	return nil
}
970757
func (p *Provider) DeleteMachine() (err error) {
	err = p.Host.Driver.Remove()
	defer p.Client.Close()
	return
}
164968
func (a *AAgent) ManageMachines(ctx context.Context, wg *sync.WaitGroup) error {
	wg.Add(1)
	go a.watchSource(ctx, wg)

	return nil
}
772168
func (h *bundleHandler) resolveMachine(placeholder string) (string, error) {
	logger.Debugf("resolveMachine(%q)", placeholder)
	machineOrUnit := resolve(placeholder, h.results)
	if !names.IsValidUnit(machineOrUnit) {
		return machineOrUnit, nil
	}
	for h.unitStatus[machineOrUnit] == "" {
		if err := h.updateUnitStatus(); err != nil {
			return "", errors.Annotate(err, "cannot resolve machine")
		}
	}
	return h.unitStatus[machineOrUnit], 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)
}
613277
func defaultMachineType(cluster *kops.Cluster, ig *kops.InstanceGroup) (string, error) {
	switch kops.CloudProviderID(cluster.Spec.CloudProvider) {
	case kops.CloudProviderAWS:
		cloud, err := BuildCloud(cluster)
		if err != nil {
			return "", fmt.Errorf("error building cloud for AWS cluster: %v", err)
		}

		instanceType, err := cloud.(awsup.AWSCloud).DefaultInstanceType(cluster, ig)
		if err != nil {
			return "", fmt.Errorf("error finding default machine type: %v", err)
		}
		return instanceType, nil

	case kops.CloudProviderGCE:
		switch ig.Spec.Role {
		case kops.InstanceGroupRoleMaster:
			return defaultMasterMachineTypeGCE, nil

		case kops.InstanceGroupRoleNode:
			return defaultNodeMachineTypeGCE, nil

		case kops.InstanceGroupRoleBastion:
			return defaultBastionMachineTypeGCE, nil
		}

	case kops.CloudProviderDO:
		switch ig.Spec.Role {
		case kops.InstanceGroupRoleMaster:
			return defaultMasterMachineTypeDO, nil

		case kops.InstanceGroupRoleNode:
			return defaultNodeMachineTypeDO, nil

		}

	case kops.CloudProviderVSphere:
		switch ig.Spec.Role {
		case kops.InstanceGroupRoleMaster:
			return defaultMasterMachineTypeVSphere, nil

		case kops.InstanceGroupRoleNode:
			return defaultNodeMachineTypeVSphere, nil

		case kops.InstanceGroupRoleBastion:
			return defaultBastionMachineTypeVSphere, nil
		}

	case kops.CloudProviderOpenstack:
		cloud, err := BuildCloud(cluster)
		if err != nil {
			return "", fmt.Errorf("error building cloud for Openstack cluster: %v", err)
		}

		instanceType, err := cloud.(openstack.OpenstackCloud).DefaultInstanceType(cluster, ig)
		if err != nil {
			return "", fmt.Errorf("error finding default machine type: %v", err)
		}
		return instanceType, nil

	case kops.CloudProviderALI:
		switch ig.Spec.Role {
		case kops.InstanceGroupRoleMaster:
			return defaultMasterMachineTypeALI, nil

		case kops.InstanceGroupRoleNode:
			return defaultNodeMachineTypeALI, nil

		case kops.InstanceGroupRoleBastion:
			return defaultBastionMachineTypeALI, nil
		}
	}

	glog.V(2).Infof("Cannot set default MachineType for CloudProvider=%q, Role=%q", cluster.Spec.CloudProvider, ig.Spec.Role)
	return "", nil
}
279562
func createMachine(c context.Context, m *crimson.Machine) error {
	if err := validateMachineForCreation(m); err != nil {
		return err
	}

	db := database.Get(c)
	// By setting machines.platform_id and machines.rack_id NOT NULL when setting up the database, we can avoid checking if the given
	// platform and rack are valid. MySQL will turn up NULL for their column values which will be rejected as an error.
	_, err := db.ExecContext(c, `
		INSERT INTO machines (name, platform_id, rack_id, description, asset_tag, service_tag, deployment_ticket, drac_password, state)
		VALUES (?, (SELECT id FROM platforms WHERE name = ?), (SELECT id FROM racks WHERE name = ?), ?, ?, ?, ?, ?, ?)
	`, m.Name, m.Platform, m.Rack, m.Description, m.AssetTag, m.ServiceTag, m.DeploymentTicket, m.DracPassword, m.State)
	if err != nil {
		switch e, ok := err.(*mysql.MySQLError); {
		case !ok:
			// Type assertion failed.
		case e.Number == mysqlerr.ER_DUP_ENTRY:
			// e.g. "Error 1062: Duplicate entry 'machine-name' for key 'name'".
			// Name is the only required unique field (ID is required unique, but it's auto-incremented).
			return status.Errorf(codes.AlreadyExists, "duplicate machine %q", m.Name)
		case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'platform_id'"):
			// e.g. "Error 1048: Column 'platform_id' cannot be null".
			return status.Errorf(codes.NotFound, "platform %q does not exist", m.Platform)
		case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'rack_id'"):
			// e.g. "Error 1048: Column 'rack_id' cannot be null".
			return status.Errorf(codes.NotFound, "rack %q does not exist", m.Rack)
		}
		return errors.Annotate(err, "failed to create machine").Err()
	}
	return nil
}