// GetMachine gets a specific container with systemd-machined
544591
func (c *Conn) GetMachine(name string) (dbus.ObjectPath, error) {
	return c.getPath("GetMachine", name)
}
562803
func (fw *Firewaller) flushMachine(machined *machineData) error {
	want, err := fw.gatherIngressRules(machined)
	if err != nil {
		return errors.Trace(err)
	}
	toOpen, toClose := diffRanges(machined.ingressRules, want)
	machined.ingressRules = want
	if fw.globalMode {
		return fw.flushGlobalPorts(toOpen, toClose)
	}
	return fw.flushInstancePorts(machined, toOpen, toClose)
}
343256
func (f *FirewallerAPIV3) GetMachineActiveSubnets(args params.Entities) (params.StringsResults, error) {
	result := params.StringsResults{
		Results: make([]params.StringsResult, len(args.Entities)),
	}
	canAccess, err := f.accessMachine()
	if err != nil {
		return params.StringsResults{}, err
	}
	for i, entity := range args.Entities {
		machineTag, err := names.ParseMachineTag(entity.Tag)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		machine, err := f.getMachine(canAccess, machineTag)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		ports, err := machine.AllPorts()
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		for _, port := range ports {
			subnetID := port.SubnetID()
			if subnetID != "" && !names.IsValidSubnet(subnetID) {
				// The error message below will look like e.g. `ports for
				// machine "0", subnet "bad" not valid`.
				err = errors.NotValidf("%s", ports)
				result.Results[i].Error = common.ServerError(err)
				continue
			} else if subnetID != "" && names.IsValidSubnet(subnetID) {
				subnetTag := names.NewSubnetTag(subnetID).String()
				result.Results[i].Result = append(result.Results[i].Result, subnetTag)
				continue
			}
			// TODO(dimitern): Empty subnet CIDRs for ports are still OK until
			// we can enforce it across all providers.
			result.Results[i].Result = append(result.Results[i].Result, "")
		}
	}
	return result, 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)
}
196865
func (u *Unit) findCleanMachineQuery(requireEmpty bool, cons *constraints.Value) (bson.D, error) {
	db, closer := u.st.newDB()
	defer closer()

	// Select all machines that can accept principal units and are clean.
	var containerRefs []machineContainers
	// If we need empty machines, first build up a list of machine ids which
	// have containers so we can exclude those.
	if requireEmpty {
		containerRefsCollection, closer := db.GetCollection(containerRefsC)
		defer closer()

		err := containerRefsCollection.Find(bson.D{hasContainerTerm}).All(&containerRefs)
		if err != nil {
			return nil, errors.Trace(err)
		}
	}
	omitMachineIds := make([]string, len(containerRefs))
	for i, cref := range containerRefs {
		omitMachineIds[i] = cref.Id
	}

	// Exclude machines that are locked for series upgrade.
	locked, err := u.st.upgradeSeriesMachineIds()
	if err != nil {
		return nil, errors.Trace(err)
	}
	omitMachineIds = append(omitMachineIds, locked...)

	// Also exclude containers on machines locked for series upgrade.
	for _, id := range locked {
		m, err := u.st.Machine(id)
		if err != nil {
			return nil, errors.Trace(err)
		}
		cIds, err := m.Containers()
		if err != nil && !errors.IsNotFound(err) {
			return nil, errors.Trace(err)
		}
		omitMachineIds = append(omitMachineIds, cIds...)
	}

	terms := bson.D{
		{"life", Alive},
		{"series", u.doc.Series},
		{"jobs", []MachineJob{JobHostUnits}},
		{"clean", true},
		{"machineid", bson.D{{"$nin", omitMachineIds}}},
	}
	// Add the container filter term if necessary.
	var containerType instance.ContainerType
	if cons.Container != nil {
		containerType = *cons.Container
	}
	if containerType == instance.NONE {
		terms = append(terms, bson.DocElem{"containertype", ""})
	} else if containerType != "" {
		terms = append(terms, bson.DocElem{"containertype", string(containerType)})
	}

	// Find the ids of machines which satisfy any required hardware
	// constraints. If there is no instanceData for a machine, that
	// machine is not considered as suitable for deploying the unit.
	// This can happen if the machine is not yet provisioned. It may
	// be that when the machine is provisioned it will be found to
	// be suitable, but we don't know that right now and it's best
	// to err on the side of caution and exclude such machines.
	var suitableInstanceData []instanceData
	var suitableTerms bson.D
	if cons.HasArch() {
		suitableTerms = append(suitableTerms, bson.DocElem{"arch", *cons.Arch})
	}
	if cons.HasMem() {
		suitableTerms = append(suitableTerms, bson.DocElem{"mem", bson.D{{"$gte", *cons.Mem}}})
	}
	if cons.RootDisk != nil && *cons.RootDisk > 0 {
		suitableTerms = append(suitableTerms, bson.DocElem{"rootdisk", bson.D{{"$gte", *cons.RootDisk}}})
	}
	if cons.RootDiskSource != nil && *cons.RootDiskSource != "" {
		suitableTerms = append(suitableTerms, bson.DocElem{"rootdisksource", *cons.RootDiskSource})
	}
	if cons.HasCpuCores() {
		suitableTerms = append(suitableTerms, bson.DocElem{"cpucores", bson.D{{"$gte", *cons.CpuCores}}})
	}
	if cons.HasCpuPower() {
		suitableTerms = append(suitableTerms, bson.DocElem{"cpupower", bson.D{{"$gte", *cons.CpuPower}}})
	}
	if cons.Tags != nil && len(*cons.Tags) > 0 {
		suitableTerms = append(suitableTerms, bson.DocElem{"tags", bson.D{{"$all", *cons.Tags}}})
	}
	if cons.HasZones() {
		suitableTerms = append(suitableTerms, bson.DocElem{"availzone", bson.D{{"$in", *cons.Zones}}})
	}
	if len(suitableTerms) > 0 {
		instanceDataCollection, closer := db.GetCollection(instanceDataC)
		defer closer()
		err := instanceDataCollection.Find(suitableTerms).Select(bson.M{"_id": 1}).All(&suitableInstanceData)
		if err != nil {
			return nil, err
		}
		var suitableIds = make([]string, len(suitableInstanceData))
		for i, m := range suitableInstanceData {
			suitableIds[i] = m.DocID
		}
		terms = append(terms, bson.DocElem{"_id", bson.D{{"$in", suitableIds}}})
	}
	return terms, nil
}
793270
func (fw *Firewaller) forgetMachine(machined *machineData) error {
	for _, unitd := range machined.unitds {
		fw.forgetUnit(unitd)
	}
	if err := fw.flushMachine(machined); err != nil {
		return errors.Trace(err)
	}

	// Unusually, it's fine to ignore this error, because we know the machined
	// is being tracked in fw.catacomb. But we do still want to wait until the
	// watch loop has stopped before we nuke the last data and return.
	_ = worker.Stop(machined)
	delete(fw.machineds, machined.tag)
	logger.Debugf("stopped watching %q", machined.tag)
	return nil
}
1005183
func ModelMachineInfo(st ModelManagerBackend) (machineInfo []params.ModelMachineInfo, _ error) {
	machines, err := st.AllMachines()
	if err != nil {
		return nil, errors.Trace(err)
	}
	for _, m := range machines {
		if m.Life() != state.Alive {
			continue
		}
		var status string
		// This is suboptimal as if there are many machines,
		// we are making many calls into the DB for each machine.
		statusInfo, err := m.Status()
		if err == nil {
			status = string(statusInfo.Status)
		} else {
			status = err.Error()
		}
		mInfo := params.ModelMachineInfo{
			Id:        m.Id(),
			HasVote:   m.HasVote(),
			WantsVote: m.WantsVote(),
			Status:    status,
			Message:   statusInfo.Message,
		}
		instId, displayName, err := m.InstanceNames()
		switch {
		case err == nil:
			mInfo.InstanceId = string(instId)
			mInfo.DisplayName = displayName
		case errors.IsNotProvisioned(err):
			// ok, but no instance ID to get.
		default:
			return nil, errors.Trace(err)
		}
		if m.ContainerType() != "" && m.ContainerType() != instance.NONE {
			machineInfo = append(machineInfo, mInfo)
			continue
		}
		// Only include cores for physical machines.
		hw, err := m.HardwareCharacteristics()
		if err != nil && !errors.IsNotFound(err) {
			return nil, errors.Trace(err)
		}
		if hw != nil && hw.String() != "" {
			hwParams := &params.MachineHardware{
				Cores:            hw.CpuCores,
				Arch:             hw.Arch,
				Mem:              hw.Mem,
				RootDisk:         hw.RootDisk,
				CpuPower:         hw.CpuPower,
				Tags:             hw.Tags,
				AvailabilityZone: hw.AvailabilityZone,
			}
			mInfo.Hardware = hwParams
		}
		machineInfo = append(machineInfo, mInfo)
	}
	return machineInfo, nil
}
410106
func (soc *Socket) GetMechanism() (Mechanism, error) {
	v, err := soc.getInt(C.ZMQ_MECHANISM)
	return Mechanism(v), err
}
646135
func (r *MachineInitReader) getMachineCloudCfgDirData() (map[string]interface{}, error) {
	dir := r.config.CloudInitConfigDir

	files, err := ioutil.ReadDir(dir)
	if err != nil {
		return nil, errors.Annotate(err, "determining files in CloudInitCfgDir for the machine")
	}
	sortedFiles := sortableFileInfos(files)
	sort.Sort(sortedFiles)

	cloudInit := make(map[string]interface{})
	for _, file := range files {
		name := file.Name()
		if !strings.HasSuffix(name, ".cfg") {
			continue
		}
		_, cloudCfgData, err := fileAsConfigMap(filepath.Join(dir, name))
		if err != nil {
			return nil, errors.Trace(err)
		}
		for k, v := range cloudCfgData {
			cloudInit[k] = v
		}
	}
	return cloudInit, nil
}
1250663
func (st *State) AddOneMachine(template MachineTemplate) (*Machine, error) {
	ms, err := st.AddMachines(template)
	if err != nil {
		return nil, err
	}
	return ms[0], nil
}
1340968
func NewMachineManagerAPI(
	backend Backend,
	storageAccess storageInterface,
	pool Pool,
	auth facade.Authorizer,
	modelTag names.ModelTag,
	callCtx context.ProviderCallContext,
	resources facade.Resources,
) (*MachineManagerAPI, error) {
	if !auth.AuthClient() {
		return nil, common.ErrPerm
	}
	return &MachineManagerAPI{
		st:            backend,
		storageAccess: storageAccess,
		pool:          pool,
		authorizer:    auth,
		check:         common.NewBlockChecker(backend),
		modelTag:      modelTag,
		callContext:   callCtx,
		resources:     resources,
	}, nil
}
520519
func (s *VirtualMachineService) GetVirtualMachineByName(name string, opts ...OptionFunc) (*VirtualMachine, int, error) {
	id, count, err := s.GetVirtualMachineID(name, opts...)
	if err != nil {
		return nil, count, err
	}

	r, count, err := s.GetVirtualMachineByID(id, opts...)
	if err != nil {
		return nil, count, err
	}
	return r, count, nil
}
427284
func (c *Controller) updateMachine(ch MachineChange) {
	c.ensureModel(ch.ModelUUID).updateMachine(ch, c.manager)
}
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
}
1374084
func (p *Provider) CreateMachine() (machine *iaas.Machine, err error) {
	err = p.Client.Create(p.Host)
	if err != nil {
		return
	}
	config, err := getConfig(p.Client.GetMachinesDir(), p.Name)
	if err != nil {
		return
	}

	machine = &iaas.Machine{
		ID:        config.Driver.InstanceID,
		IP:        config.Driver.IPAddress,
		Image:     config.Driver.AMI,
		Kind:      config.DriverName,
		Name:      p.Name,
		SSHKeysID: []int{config.Driver.SSHKeyID},
		CertsDir:  p.ClientPath + "/certs",
	}
	return
}
1051174
func (do *Provider) DeleteMachine() (err error) {
	err = do.Host.Driver.Remove()
	defer do.Client.Close()
	if err != nil {
		return
	}
	return
}
988596
func (c *Client) GetMachineTag(machineID, tagKey string) (string, error) {
	var resp []byte
	requestHeaders := make(http.Header)
	requestHeaders.Set("Accept", "text/plain")
	req := request{
		method:    client.GET,
		url:       makeURL(apiMachines, machineID, apiTags, tagKey),
		resp:      &resp,
		reqHeader: requestHeaders,
	}
	if _, err := c.sendRequest(req); err != nil {
		return "", errors.Newf(err, "failed to get tag %s for machine with id %s", tagKey, machineID)
	}
	return string(resp), nil
}