// AddMachines adds new machines with the supplied parameters, creating any requested disks.
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
}
946706
func ApplicationMachines(st *State, application string) ([]string, error) {
	machines, err := st.AllMachines()
	if err != nil {
		return nil, err
	}
	applicationName := unitAppName(application)
	var machineIds []string
	for _, machine := range machines {
		principalSet := set.NewStrings()
		for _, principal := range machine.Principals() {
			principalSet.Add(unitAppName(principal))
		}
		if principalSet.Contains(applicationName) {
			machineIds = append(machineIds, machine.Id())
		}
	}
	return machineIds, nil
}
500510
func (c *Client) CountMachines() (int, error) {
	var resp int
	req := request{
		method: client.HEAD,
		url:    apiMachines,
		resp:   &resp,
	}
	if _, err := c.sendRequest(req); err != nil {
		return -1, errors.Newf(err, "failed to get count of machines")
	}
	return resp, nil
}
875620
func (c *Client) CheckMachines(modelUUID string) ([]error, error) {
	var result params.ErrorResults
	args := params.ModelArgs{names.NewModelTag(modelUUID).String()}
	err := c.caller.FacadeCall("CheckMachines", args, &result)
	if err != nil {
		return nil, errors.Trace(err)
	}
	var results []error
	for _, res := range result.Results {
		results = append(results, errors.Errorf(res.Error.Message))
	}
	return results, nil
}
547852
func (api *MetricsManagerAPI) AddJujuMachineMetrics() error {
	sla, err := api.state.SLACredential()
	if err != nil {
		return errors.Trace(err)
	}
	if len(sla) == 0 {
		return nil
	}
	allMachines, err := api.state.AllMachines()
	if err != nil {
		return errors.Trace(err)
	}
	machineCount := 0
	osMachineCount := map[os.OSType]int{}
	for _, machine := range allMachines {
		ct := machine.ContainerType()
		if ct == instance.NONE || ct == "" {
			machineCount++
			osType, err := series.GetOSFromSeries(machine.Series())
			if err != nil {
				logger.Warningf("failed to resolve OS name for series %q: %v", machine.Series(), err)
				osType = os.Unknown
			}
			osMachineCount[osType] = osMachineCount[osType] + 1
		}
	}
	t := clock.WallClock.Now()
	metrics := []state.Metric{{
		Key:   "juju-machines",
		Value: fmt.Sprintf("%d", machineCount),
		Time:  t,
	}}
	for osType, osMachineCount := range osMachineCount {
		osName := strings.ToLower(osType.String())
		metrics = append(metrics, state.Metric{
			Key:   "juju-" + osName + "-machines",
			Value: fmt.Sprintf("%d", osMachineCount),
			Time:  t,
		})
	}
	metricUUID, err := utils.NewUUID()
	if err != nil {
		return errors.Trace(err)
	}
	_, err = api.state.AddModelMetrics(state.ModelBatchParam{
		UUID:    metricUUID.String(),
		Created: t,
		Metrics: metrics,
	})
	return err
}
583972
func (task *provisionerTask) populateMachineMaps(ids []string) error {
	task.instances = make(map[instance.Id]instances.Instance)

	instances, err := task.broker.AllInstances(task.cloudCallCtx)
	if err != nil {
		return errors.Annotate(err, "failed to get all instances from broker")
	}
	for _, i := range instances {
		task.instances[i.Id()] = i
	}

	// Update the machines map with new data for each of the machines in the
	// change list.
	machineTags := make([]names.MachineTag, len(ids))
	for i, id := range ids {
		machineTags[i] = names.NewMachineTag(id)
	}
	machines, err := task.machineGetter.Machines(machineTags...)
	if err != nil {
		return errors.Annotatef(err, "failed to get machines %v", ids)
	}
	task.machinesMutex.Lock()
	defer task.machinesMutex.Unlock()
	for i, result := range machines {
		switch {
		case result.Err == nil:
			task.machines[result.Machine.Id()] = result.Machine
		case params.IsCodeNotFoundOrCodeUnauthorized(result.Err):
			logger.Debugf("machine %q not found in state", ids[i])
			delete(task.machines, ids[i])
		default:
			return errors.Annotatef(result.Err, "failed to get machine %v", ids[i])
		}
	}
	return nil
}
263235
func (c *CloudAPI) AddMachineTags(machineID string, tags map[string]string) (map[string]string, error) {
	machine, err := c.GetMachine(machineID)
	if err != nil {
		return nil, err
	}

	for tag, value := range tags {
		if _, present := machine.Tags[tag]; !present {
			machine.Tags[tag] = value
		}
	}

	return machine.Tags, nil
}
118419
func (m *Machine) SetMachineBlockDevices(info ...BlockDeviceInfo) error {
	return setMachineBlockDevices(m.st, m.Id(), info)
}
799447
func (rc *rawConn) ListMachineTypes(projectID, zone string) (*compute.MachineTypeList, error) {
	op := rc.MachineTypes.List(projectID, zone)
	machines, err := op.Do()
	if err != nil {
		return nil, errors.Annotatef(err, "listing machine types for project %q and zone %q", projectID, zone)
	}
	return machines, nil
}
99066
func (s *VirtualMachineService) AddNicToVirtualMachine(p *AddNicToVirtualMachineParams) (*AddNicToVirtualMachineResponse, error) {
	resp, err := s.cs.newRequest("addNicToVirtualMachine", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r AddNicToVirtualMachineResponse
	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
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

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

	return &r, nil
}
329673
func (st *State) addMachineInsideMachineOps(template MachineTemplate, parentId string, containerType instance.ContainerType) (*machineDoc, []txn.Op, error) {
	if template.InstanceId != "" {
		return nil, nil, errors.New("cannot specify instance id for a new container")
	}
	template, err := st.effectiveMachineTemplate(template, false)
	if err != nil {
		return nil, nil, err
	}
	if containerType == "" {
		return nil, nil, errors.New("no container type specified")
	}

	// If a parent machine is specified, make sure it exists
	// and can support the requested container type.
	parent, err := st.Machine(parentId)
	if err != nil {
		return nil, nil, err
	}
	if !parent.supportsContainerType(containerType) {
		return nil, nil, errors.Errorf("machine %s cannot host %s containers", parentId, containerType)
	}

	// Ensure that the machine is not locked for series-upgrade.
	locked, err := parent.IsLockedForSeriesUpgrade()
	if err != nil {
		return nil, nil, err
	}
	if locked {
		return nil, nil, errors.Errorf("machine %s is locked for series upgrade", parentId)
	}

	newId, err := st.newContainerId(parentId, containerType)
	if err != nil {
		return nil, nil, err
	}
	mdoc := st.machineDocForTemplate(template, newId)
	mdoc.ContainerType = string(containerType)
	prereqOps, machineOp, err := st.insertNewMachineOps(mdoc, template)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}
	prereqOps = append(prereqOps,
		// Update containers record for host machine.
		addChildToContainerRefOp(st, parentId, mdoc.Id),
		// Create a containers reference document for the container itself.
		insertNewContainerRefOp(st, mdoc.Id),
	)
	return mdoc, append(prereqOps, machineOp), nil
}
600286
func (api *API) AllMachineRemovals() ([]names.MachineTag, error) {
	var results params.EntitiesResults
	args := wrapEntities(api.modelTag)
	err := api.facade.FacadeCall("AllMachineRemovals", &args, &results)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if len(results.Results) != 1 {
		return nil, errors.Errorf("expected one result, got %d", len(results.Results))
	}
	result := results.Results[0]
	if result.Error != nil {
		return nil, errors.Trace(result.Error)
	}
	machines := make([]names.MachineTag, len(result.Entities))
	for i, entity := range result.Entities {
		tag, err := names.ParseMachineTag(entity.Tag)
		if err != nil {
			return nil, errors.Trace(err)
		}
		machines[i] = tag
	}
	return machines, 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
}
1066717
func (gce *Connection) ListMachineTypes(zone string) ([]MachineType, error) {
	machines, err := gce.raw.ListMachineTypes(gce.projectID, zone)
	if err != nil {
		return nil, errors.Trace(err)
	}
	res := make([]MachineType, len(machines.Items))
	for i, machine := range machines.Items {
		deprecated := false
		if machine.Deprecated != nil {
			deprecated = machine.Deprecated.State != ""
		}
		res[i] = MachineType{
			CreationTimestamp:            machine.CreationTimestamp,
			Deprecated:                   deprecated,
			Description:                  machine.Description,
			GuestCpus:                    machine.GuestCpus,
			Id:                           machine.Id,
			ImageSpaceGb:                 machine.ImageSpaceGb,
			Kind:                         machine.Kind,
			MaximumPersistentDisks:       machine.MaximumPersistentDisks,
			MaximumPersistentDisksSizeGb: machine.MaximumPersistentDisksSizeGb,
			MemoryMb:                     machine.MemoryMb,
			Name:                         machine.Name,
		}
	}
	return res, nil
}
239313
func (st *State) insertNewMachineOps(mdoc *machineDoc, template MachineTemplate) (prereqOps []txn.Op, machineOp txn.Op, err error) {
	now := st.clock().Now()
	machineStatusDoc := statusDoc{
		Status:    status.Pending,
		ModelUUID: st.ModelUUID(),
		Updated:   now.UnixNano(),
	}
	instanceStatusDoc := statusDoc{
		Status:    status.Pending,
		ModelUUID: st.ModelUUID(),
		Updated:   now.UnixNano(),
	}
	modificationStatusDoc := statusDoc{
		Status:    status.Idle,
		ModelUUID: st.ModelUUID(),
		Updated:   now.UnixNano(),
	}

	prereqOps, machineOp = st.baseNewMachineOps(
		mdoc,
		machineStatusDoc,
		instanceStatusDoc,
		modificationStatusDoc,
		template.Constraints,
	)

	sb, err := NewStorageBackend(st)
	if err != nil {
		return nil, txn.Op{}, errors.Trace(err)
	}
	storageOps, volumeAttachments, filesystemAttachments, err := sb.hostStorageOps(
		mdoc.Id, &storageParams{
			filesystems:           template.Filesystems,
			filesystemAttachments: template.FilesystemAttachments,
			volumes:               template.Volumes,
			volumeAttachments:     template.VolumeAttachments,
		},
	)
	if err != nil {
		return nil, txn.Op{}, errors.Trace(err)
	}
	for _, a := range volumeAttachments {
		mdoc.Volumes = append(mdoc.Volumes, a.tag.Id())
	}
	for _, a := range filesystemAttachments {
		mdoc.Filesystems = append(mdoc.Filesystems, a.tag.Id())
	}
	prereqOps = append(prereqOps, storageOps...)

	// At the last moment we still have statusDoc in scope, set the initial
	// history entry. This is risky, and may lead to extra entries, but that's
	// an intrinsic problem with mixing txn and non-txn ops -- we can't sync
	// them cleanly.
	probablyUpdateStatusHistory(st.db(), machineGlobalKey(mdoc.Id), machineStatusDoc)
	probablyUpdateStatusHistory(st.db(), machineGlobalInstanceKey(mdoc.Id), instanceStatusDoc)
	probablyUpdateStatusHistory(st.db(), machineGlobalModificationKey(mdoc.Id), modificationStatusDoc)
	return prereqOps, machineOp, nil
}
1103
func (client *Client) DestroyMachines(machines ...string) ([]params.DestroyMachineResult, error) {
	return client.destroyMachines("DestroyMachine", machines)
}
612550
func setMachineBlockDevices(st modelBackend, machineId string, newInfo []BlockDeviceInfo) error {
	db := st.db()
	buildTxn := func(attempt int) ([]txn.Op, error) {
		oldInfo, err := getBlockDevices(db, machineId)
		if err != nil {
			return nil, errors.Trace(err)
		}
		if !blockDevicesChanged(oldInfo, newInfo) {
			return nil, jujutxn.ErrNoOperations
		}
		ops := []txn.Op{{
			C:      machinesC,
			Id:     machineId,
			Assert: notDeadDoc,
		}, {
			C:      blockDevicesC,
			Id:     machineId,
			Assert: txn.DocExists,
			Update: bson.D{{"$set", bson.D{{"blockdevices", newInfo}}}},
		}}
		return ops, nil
	}
	return db.Run(buildTxn)
}