// findCleanMachineQuery returns a Mongo query to find clean (and maybe empty)
// machines with characteristics matching the specified constraints.
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
}
428275
func (adapter *PostgresAdapter) FindTableQuery() string {
	query := "SELECT COUNT(*) found FROM %s.%s WHERE %s = $1;"

	return Cleanf(query,
		adapter.Schema, types.SQLDictionaryTableName, // from
		types.SQLColumnLabelTableName) // where
}
909341
func (c *CloudAPI) StopMachine(machineID string) error {
	if err := c.ProcessFunctionHook(c, machineID); err != nil {
		return err
	}

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

	return fmt.Errorf("Machine %s not found", machineID)
}
358139
func (cw collectionWrapper) Find(query interface{}) Query {
	return queryWrapper{cw.Collection.Find(query)}
}
1215232
func getMachinesCmd(params *Parameters) *subcommands.Command {
	return &subcommands.Command{
		UsageLine: "get-machines [-name <name>]... [-plat <plat>]... [-rack <rack>]... [-dc <dc>]... [-state <state>]...",
		ShortDesc: "retrieves machines",
		LongDesc:  "Retrieves machines matching the given names, platforms, racks, and states, or all machines if names are omitted.\n\nExample to get all machines:\ncrimson get-machines\nExample to get all machines in rack xx1 that are in repair state:\ncrimson get-machines -rack xx1 -state repair",
		CommandRun: func() subcommands.CommandRun {
			cmd := &GetMachinesCmd{}
			cmd.Initialize(params)
			cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a machine to filter by. Can be specified multiple times.")
			cmd.Flags.Var(flag.StringSlice(&cmd.req.Platforms), "plat", "Name of a platform to filter by. Can be specified multiple times.")
			cmd.Flags.Var(flag.StringSlice(&cmd.req.Racks), "rack", "Name of a rack to filter by. Can be specified multiple times.")
			cmd.Flags.Var(flag.StringSlice(&cmd.req.Datacenters), "dc", "Name of a datacenter to filter by. Can be specified multiple times.")
			cmd.Flags.Var(StateSliceFlag(&cmd.req.States), "state", "State to filter by. Can be specified multiple times.")
			return cmd
		},
	}
}
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
}
949096
func (st *State) CompleteMachineRemovals(ids ...string) error {
	if err := checkValidMachineIds(ids); err != nil {
		return errors.Trace(err)
	}

	buildTxn := func(int) ([]txn.Op, error) {
		// We don't need to reget state for subsequent attempts since
		// completeMachineRemovalsOps gets the removals and the
		// machines each time anyway.
		ops, err := st.completeMachineRemovalsOps(ids)
		if err != nil {
			return nil, errors.Trace(err)
		}
		return ops, nil
	}
	return st.db().Run(buildTxn)
}
412921
func (m *Model) Machine(machineId string) (*Machine, error) {
	defer m.doLocked()()

	machine, found := m.machines[machineId]
	if !found {
		return nil, errors.NotFoundf("machine %q", machineId)
	}
	return machine, nil
}
805039
func (st *State) AllMachineRemovals() ([]string, error) {
	removals, close := st.db().GetCollection(machineRemovalsC)
	defer close()

	var docs []machineRemovalDoc
	err := removals.Find(nil).All(&docs)
	if err != nil {
		return nil, errors.Trace(err)
	}
	results := make([]string, len(docs))
	for i := range docs {
		results[i] = docs[i].MachineID
	}
	return results, nil
}
1209185
func (f *FirewallerAPIV3) GetMachinePorts(args params.MachinePortsParams) (params.MachinePortsResults, error) {
	result := params.MachinePortsResults{
		Results: make([]params.MachinePortsResult, len(args.Params)),
	}
	canAccess, err := f.accessMachine()
	if err != nil {
		return params.MachinePortsResults{}, err
	}
	for i, param := range args.Params {
		machineTag, err := names.ParseMachineTag(param.MachineTag)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		var subnetTag names.SubnetTag
		if param.SubnetTag != "" {
			subnetTag, err = names.ParseSubnetTag(param.SubnetTag)
			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.OpenedPorts(subnetTag.Id())
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		if ports != nil {
			portRangeMap := ports.AllPortRanges()
			var portRanges []network.PortRange
			for portRange := range portRangeMap {
				portRanges = append(portRanges, portRange)
			}
			network.SortPortRanges(portRanges)

			for _, portRange := range portRanges {
				unitTag := names.NewUnitTag(portRangeMap[portRange]).String()
				result.Results[i].Ports = append(result.Results[i].Ports,
					params.MachinePortRange{
						UnitTag:   unitTag,
						PortRange: params.FromNetworkPortRange(portRange),
					})
			}
		}
	}
	return result, nil
}
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
}
824412
func FindReference(refs []types.ManagedObjectReference, match ...types.ManagedObjectReference) *types.ManagedObjectReference {
	for _, ref := range refs {
		for _, m := range match {
			if ref == m {
				return &ref
			}
		}
	}

	return nil
}
498922
func (c *Controller) removeMachine(ch RemoveMachine) error {
	return errors.Trace(c.removeResident(ch.ModelUUID, func(m *Model) error { return m.removeMachine(ch) }))
}
1044304
func (c *CloudAPI) GetMachine(machineID string) (*cloudapi.Machine, error) {
	wrapper, err := c.getMachineWrapper(machineID)
	if err != nil {
		return nil, err
	}

	return &wrapper.Machine, nil
}
258611
func (*Service) ListMachines(c context.Context, req *crimson.ListMachinesRequest) (*crimson.ListMachinesResponse, error) {
	machines, err := listMachines(c, database.Get(c), req)
	if err != nil {
		return nil, err
	}
	return &crimson.ListMachinesResponse{
		Machines: machines,
	}, nil
}
562106
func (c context) DeepClean() {
	i := &ComponentsChecker{context: c, RegAccess: registry.SET_VALUE}
	i.PerComponent = i.deleteProductsFunc
	i.checkRegistryComponents()
	i.RegWow = registry.WOW64_32KEY
	i.checkRegistryComponents()
	c.deleteProductFiles()
}
1222765
func (api *API) CheckMachines(args params.ModelArgs) (params.ErrorResults, error) {
	tag, err := names.ParseModelTag(args.ModelTag)
	if err != nil {
		return params.ErrorResults{}, errors.Trace(err)
	}
	st, err := api.pool.Get(tag.Id())
	if err != nil {
		return params.ErrorResults{}, errors.Trace(err)
	}
	defer st.Release()

	return credentialcommon.ValidateExistingModelCredential(
		credentialcommon.NewPersistentBackend(st.State),
		api.callContext,
	)
}