// instancesForDeadMachines returns a list of instances.Instance that represent
// the list of dead machines running in the provider. Missing machines are
// omitted from the list.
427045
func (task *provisionerTask) instancesForDeadMachines(deadMachines []apiprovisioner.MachineProvisioner) []instances.Instance {
	var instances []instances.Instance
	for _, machine := range deadMachines {
		instId, err := machine.InstanceId()
		if err == nil {
			keep, _ := machine.KeepInstance()
			if keep {
				logger.Debugf("machine %v is dead but keep-instance is true", instId)
				continue
			}
			inst, found := task.instances[instId]
			// If the instance is not found we can't stop it.
			if found {
				instances = append(instances, inst)
			}
		}
	}
	return instances
}
649118
func (m *metadata) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error) {
	return false, errors.New("InstanceExistsByProviderID not implemented")
}
1110532
func (ec2i *FakeEC2Impl) DescribeInstances(request *ec2.DescribeInstancesInput) ([]*ec2.Instance, error) {
	matches := []*ec2.Instance{}
	for _, instance := range ec2i.aws.instances {
		if request.InstanceIds != nil {
			if instance.InstanceId == nil {
				klog.Warning("Instance with no instance id: ", instance)
				continue
			}

			found := false
			for _, instanceID := range request.InstanceIds {
				if *instanceID == *instance.InstanceId {
					found = true
					break
				}
			}
			if !found {
				continue
			}
		}
		if request.Filters != nil {
			allMatch := true
			for _, filter := range request.Filters {
				if !instanceMatchesFilter(instance, filter) {
					allMatch = false
					break
				}
			}
			if !allMatch {
				continue
			}
		}
		matches = append(matches, instance)
	}

	return matches, 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
}
643558
func (vb *VirtualBox) GetMachines() ([]*Machine, error) {
	if err := vb.assertMobRef(); err != nil {
		return nil, err
	}

	request := getMachinesRequest{MobRef: vb.mobref}
	response := new(getMachinesResponse)
	err := vb.send(request, response)
	if err != nil {
		return nil, err
	}
	machines := make([]*Machine, len(response.Returnval))
	for i, machineID := range response.Returnval {
		machines[i] = NewMachine(vb, machineID)
	}
	return machines, nil
}
110604
func (s *ProxyStore) Instances(service string) ([]*discoverd.Instance, error) {
	host := s.Peers[rand.Intn(len(s.Peers))]
	client := discoverd.NewClientWithURL("http://" + host)
	return client.Service(service).Instances()
}
486973
func (env *environ) Instances(ctx context.ProviderCallContext, ids []instance.Id) (instances []instances.Instance, err error) {
	if len(ids) == 0 {
		return nil, environs.ErrNoInstances
	}
	err = env.withSession(ctx, func(env *sessionEnviron) error {
		instances, err = env.Instances(ctx, ids)
		return err
	})
	return instances, err
}
1148989
func (env *maasEnviron) instances1(ctx context.ProviderCallContext, filter url.Values) ([]instances.Instance, error) {
	nodeListing := env.getMAASClient().GetSubObject("nodes")
	listNodeObjects, err := nodeListing.CallGet("list", filter)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, err
	}
	listNodes, err := listNodeObjects.GetArray()
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, err
	}
	instances := make([]instances.Instance, len(listNodes))
	for index, nodeObj := range listNodes {
		node, err := nodeObj.GetMAASObject()
		if err != nil {
			return nil, err
		}
		instances[index] = &maas1Instance{
			maasObject:   &node,
			environ:      env,
			statusGetter: env.deploymentStatusOne,
		}
	}
	return instances, nil
}
315564
func (cs *CSCloud) Instances() (cloudprovider.Instances, bool) {
	if cs.metadata != nil {
		return cs.metadata, true
	}

	if cs.client == nil {
		return nil, false
	}

	return cs, true
}
377560
func (env *sessionEnviron) Instances(ctx context.ProviderCallContext, ids []instance.Id) ([]instances.Instance, error) {
	if len(ids) == 0 {
		return nil, environs.ErrNoInstances
	}

	allInstances, err := env.AllInstances(ctx)
	if err != nil {
		return nil, errors.Annotate(err, "failed to get instances")
	}
	findInst := func(id instance.Id) instances.Instance {
		for _, inst := range allInstances {
			if id == inst.Id() {
				return inst
			}
		}
		return nil
	}

	var numFound int
	results := make([]instances.Instance, len(ids))
	for i, id := range ids {
		if inst := findInst(id); inst != nil {
			results[i] = inst
			numFound++
		}
	}
	if numFound == 0 {
		return nil, environs.ErrNoInstances
	} else if numFound != len(ids) {
		err = environs.ErrPartialInstances
	}
	return results, err
}
604815
func (env *maasEnviron) acquiredInstances(ctx context.ProviderCallContext, ids []instance.Id) ([]instances.Instance, error) {
	if !env.usingMAAS2() {
		filter := getSystemIdValues("id", ids)
		filter.Add("agent_name", env.uuid)
		return env.instances1(ctx, filter)
	}
	args := gomaasapi.MachinesArgs{
		AgentName: env.uuid,
		SystemIDs: instanceIdsToSystemIDs(ids),
	}
	return env.instances2(ctx, args)
}
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
}
1338396
func (api *InstanceMutaterAPI) WatchMachines() (params.StringsWatchResult, error) {
	result := params.StringsWatchResult{}
	if !api.authorizer.AuthController() {
		return result, common.ErrPerm
	}

	watch, err := api.model.WatchMachines()
	if err != nil {
		return result, err
	}
	if changes, ok := <-watch.Changes(); ok {
		result.StringsWatcherId = api.resources.Register(watch)
		result.Changes = changes
	} else {
		return result, errors.Errorf("cannot obtain initial model machines")
	}
	return result, nil
}
56070
func (task *provisionerTask) startMachines(machines []apiprovisioner.MachineProvisioner) error {
	if len(machines) == 0 {
		return nil
	}

	// Get the distributionGroups for each machine now to avoid
	// successive calls to DistributionGroupByMachineId which will
	// return the same data.
	machineTags := make([]names.MachineTag, len(machines))
	for i, machine := range machines {
		machineTags[i] = machine.MachineTag()
	}
	machineDistributionGroups, err := task.distributionGroupFinder.DistributionGroupByMachineId(machineTags...)
	if err != nil {
		return err
	}

	var wg sync.WaitGroup
	errMachines := make([]error, len(machines))
	for i, m := range machines {
		if machineDistributionGroups[i].Err != nil {
			task.setErrorStatus(
				"fetching distribution groups for machine %q: %v",
				m, machineDistributionGroups[i].Err,
			)
			continue
		}
		wg.Add(1)
		go func(machine apiprovisioner.MachineProvisioner, dg []string, index int) {
			defer wg.Done()
			if err := task.startMachine(machine, dg); err != nil {
				task.removeMachineFromAZMap(machine)
				errMachines[index] = err
			}
		}(m, machineDistributionGroups[i].MachineIds, i)
	}

	wg.Wait()
	select {
	case <-task.catacomb.Dying():
		return task.catacomb.ErrDying()
	default:
	}
	var errorStrings []string
	for _, err := range errMachines {
		if err != nil {
			errorStrings = append(errorStrings, err.Error())
		}
	}
	if errorStrings != nil {
		return errors.New(strings.Join(errorStrings, "\n"))
	}
	return nil
}
541028
func (c *CloudAPI) ListMachines(filters map[string]string) ([]*cloudapi.Machine, error) {
	if err := c.ProcessFunctionHook(c, filters); err != nil {
		return nil, err
	}

	availableMachines := c.machines

	if filters != nil {
		for k, f := range filters {
			// check if valid filter
			if contains(machinesFilters, k) {
				machines := []*machine{}
				// filter from availableMachines and add to machines
				for _, m := range availableMachines {
					if k == "name" && m.Name == f {
						machines = append(machines, m)
					} else if k == "type" && m.Type == f {
						machines = append(machines, m)
					} else if k == "state" && m.State == f {
						machines = append(machines, m)
					} else if k == "image" && m.Image == f {
						machines = append(machines, m)
					} else if k == "memory" {
						i, err := strconv.Atoi(f)
						if err == nil && m.Memory == i {
							machines = append(machines, m)
						}
					} else if strings.HasPrefix(k, "tags.") {
						for t, v := range m.Tags {
							if t == k[strings.Index(k, ".")+1:] && v == f {
								machines = append(machines, m)
							}
						}
					}
				}
				availableMachines = machines
			}
		}
	}

	out := make([]*cloudapi.Machine, len(availableMachines))
	for i, machine := range availableMachines {
		out[i] = &machine.Machine
	}

	return out, nil
}
1094433
func (f *FakeCloud) InstanceExistsByProviderID(ctx context.Context, providerID string) (bool, error) {
	f.addCall("instance-exists-by-provider-id")
	return f.ExistsByProviderID, f.ErrByProviderID
}
591462
func (s *stateFileAvailableInstances) Instances() ([]redis.Instance, error) {
	reader, err := os.Open(s.path)
	if err != nil {
		return nil, err
	}

	state := &struct {
		AvailableInstances []redis.Instance `json:"available_instances"`
	}{}

	if err := json.NewDecoder(reader).Decode(state); err != nil {
		return nil, err
	}

	return state.AvailableInstances, nil
}