// serveOldInstance looks on GCE for an instance such as defined in depl.Conf, and if
// found, serves the appropriate page depending on whether the instance is usable. It does
// not serve anything if the instance is not found.
422558
func (h *DeployHandler) serveOldInstance(w http.ResponseWriter, br blob.Ref, depl *Deployer) (found bool) {
	inst, err := depl.Get()
	if err != nil {
		// TODO(mpl,bradfitz): log or do something more
		// drastic if the error is something other than
		// instance not found.
		return false
	}
	h.logger.Printf("Reusing existing instance for (%v, %v, %v)", depl.Conf.Project, depl.Conf.Name, depl.Conf.Zone)

	if err := h.recordState(br, &creationState{
		InstConf: br,
		InstAddr: addr(inst),
		Exists:   true,
	}); err != nil {
		h.logger.Printf("Could not record creation state for %v: %v", br, err)
		h.serveErrorPage(w, fmt.Errorf("An error occurred while recording the state of your instance. %v", fileIssue(br.String())))
		return true
	}
	h.serveProgress(w, br)
	return true
}
972527
func (s *Service) ServiceInstances() []ServiceInstance {
	svcs := s.services.Load().([]ServiceInstance)
	ret := make([]ServiceInstance, len(svcs))
	copy(ret, svcs)
	sort.Sort(serviceInstanceList(ret))
	return ret
}
655088
func (e *environ) StartInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) (*environs.StartInstanceResult, error) {

	defer delay()
	machineId := args.InstanceConfig.MachineId
	logger.Infof("dummy startinstance, machine %s", machineId)
	if err := e.checkBroken("StartInstance"); err != nil {
		return nil, err
	}
	estate, err := e.state()
	if err != nil {
		return nil, err
	}
	estate.mu.Lock()
	defer estate.mu.Unlock()

	// check if an error has been injected on the transientErrorInjection channel (testing purposes)
	select {
	case injectedError := <-transientErrorInjection:
		return nil, injectedError
	default:
	}

	if args.InstanceConfig.MachineNonce == "" {
		return nil, errors.New("cannot start instance: missing machine nonce")
	}
	if args.InstanceConfig.Controller != nil {
		if args.InstanceConfig.Controller.MongoInfo.Tag != names.NewMachineTag(machineId) {
			return nil, errors.New("entity tag must match started machine")
		}
	}
	if args.InstanceConfig.APIInfo.Tag != names.NewMachineTag(machineId) {
		return nil, errors.New("entity tag must match started machine")
	}
	logger.Infof("would pick agent binaries from %s", args.Tools)
	series := args.Tools.OneSeries()

	idString := fmt.Sprintf("%s-%d", e.name, estate.maxId)
	// Add the addresses we want to see in the machine doc. This means both
	// IPv4 and IPv6 loopback, as well as the DNS name.
	addrs := network.NewAddresses(idString+".dns", "127.0.0.1", "::1")
	logger.Debugf("StartInstance addresses: %v", addrs)
	i := &dummyInstance{
		id:           instance.Id(idString),
		addresses:    addrs,
		machineId:    machineId,
		series:       series,
		firewallMode: e.Config().FirewallMode(),
		state:        estate,
	}

	var hc *instance.HardwareCharacteristics
	// To match current system capability, only provide hardware characteristics for
	// environ machines, not containers.
	if state.ParentId(machineId) == "" {
		// Assume that the provided Availability Zone won't fail,
		// though one is required.
		var zone string
		if args.Placement != "" {
			split := strings.Split(args.Placement, "=")
			if len(split) == 2 && split[0] == "zone" {
				zone = split[1]
			}
		}
		if zone == "" && args.AvailabilityZone != "" {
			zone = args.AvailabilityZone
		}

		// We will just assume the instance hardware characteristics exactly matches
		// the supplied constraints (if specified).
		hc = &instance.HardwareCharacteristics{
			Arch:             args.Constraints.Arch,
			Mem:              args.Constraints.Mem,
			RootDisk:         args.Constraints.RootDisk,
			CpuCores:         args.Constraints.CpuCores,
			CpuPower:         args.Constraints.CpuPower,
			Tags:             args.Constraints.Tags,
			AvailabilityZone: &zone,
		}
		// Fill in some expected instance hardware characteristics if constraints not specified.
		if hc.Arch == nil {
			arch := "amd64"
			hc.Arch = &arch
		}
		if hc.Mem == nil {
			mem := uint64(1024)
			hc.Mem = &mem
		}
		if hc.RootDisk == nil {
			disk := uint64(8192)
			hc.RootDisk = &disk
		}
		if hc.CpuCores == nil {
			cores := uint64(1)
			hc.CpuCores = &cores
		}
	}
	// Simulate subnetsToZones gets populated when spaces given in constraints.
	spaces := args.Constraints.IncludeSpaces()
	var subnetsToZones map[network.Id][]string
	for isp := range spaces {
		// Simulate 2 subnets per space.
		if subnetsToZones == nil {
			subnetsToZones = make(map[network.Id][]string)
		}
		for isn := 0; isn < 2; isn++ {
			providerId := fmt.Sprintf("subnet-%d", isp+isn)
			zone := fmt.Sprintf("zone%d", isp+isn)
			subnetsToZones[network.Id(providerId)] = []string{zone}
		}
	}
	// Simulate creating volumes when requested.
	volumes := make([]storage.Volume, len(args.Volumes))
	for iv, v := range args.Volumes {
		persistent, _ := v.Attributes["persistent"].(bool)
		volumes[iv] = storage.Volume{
			Tag: v.Tag,
			VolumeInfo: storage.VolumeInfo{
				Size:       v.Size,
				Persistent: persistent,
			},
		}
	}
	// Simulate attaching volumes when requested.
	volumeAttachments := make([]storage.VolumeAttachment, len(args.VolumeAttachments))
	for iv, v := range args.VolumeAttachments {
		volumeAttachments[iv] = storage.VolumeAttachment{
			Volume:  v.Volume,
			Machine: v.Machine,
			VolumeAttachmentInfo: storage.VolumeAttachmentInfo{
				DeviceName: fmt.Sprintf("sd%c", 'b'+rune(iv)),
				ReadOnly:   v.ReadOnly,
			},
		}
	}
	var mongoInfo *mongo.MongoInfo
	if args.InstanceConfig.Controller != nil {
		mongoInfo = args.InstanceConfig.Controller.MongoInfo
	}
	estate.insts[i.id] = i
	estate.maxId++
	estate.ops <- OpStartInstance{
		Env:               e.name,
		MachineId:         machineId,
		MachineNonce:      args.InstanceConfig.MachineNonce,
		PossibleTools:     args.Tools,
		Constraints:       args.Constraints,
		SubnetsToZones:    subnetsToZones,
		Volumes:           volumes,
		VolumeAttachments: volumeAttachments,
		Instance:          i,
		Jobs:              args.InstanceConfig.Jobs,
		Info:              mongoInfo,
		APIInfo:           args.InstanceConfig.APIInfo,
		AgentEnvironment:  args.InstanceConfig.AgentEnvironment,
		Secret:            e.ecfg().secret(),
	}
	return &environs.StartInstanceResult{
		Instance: i,
		Hardware: hc,
	}, nil
}
886607
func (h *DeployHandler) serveInstanceState(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	if r.Method != "GET" {
		h.serveError(w, r, fmt.Errorf("Wrong method: %v", r.Method))
		return
	}
	br := r.URL.Query().Get("instancekey")
	stateValue, err := h.instState.Get(br)
	if err != nil {
		http.Error(w, "unknown instance", http.StatusNotFound)
		return
	}
	var state creationState
	if err := json.Unmarshal([]byte(stateValue), &state); err != nil {
		h.serveError(w, r, fmt.Errorf("could not json decode instance state: %v", err))
		return
	}
	if state.Err != "" {
		// No need to log that error here since we're already doing it in serveCallback
		h.serveErrorPage(w, fmt.Errorf("an error occurred while creating your instance: %v", state.Err))
		return
	}
	if state.Success || state.Exists {
		conf, err := h.instanceConf(ctx, state.InstConf)
		if err != nil {
			h.logger.Printf("Could not get parameters for success message: %v", err)
			h.serveErrorPage(w, fmt.Errorf("your instance was created and should soon be up at https://%s but there might have been a problem in the creation process. %v", state.Err, fileIssue(br)))
			return
		}
		h.serveSuccess(w, &TemplateData{
			Prefix:            h.prefix,
			Help:              h.help,
			InstanceIP:        state.InstAddr,
			InstanceHostname:  state.InstHostname,
			ProjectConsoleURL: fmt.Sprintf("%s/project/%s/compute", ConsoleURL, conf.Project),
			Conf:              conf,
			ZoneValues:        h.zoneValues(),
			MachineValues:     machineValues,
		})
		return
	}
	h.recordStateErrMu.RLock()
	defer h.recordStateErrMu.RUnlock()
	if _, ok := h.recordStateErr[br]; ok {
		// No need to log that error here since we're already doing it in serveCallback
		h.serveErrorPage(w, fmt.Errorf("An error occurred while recording the state of your instance. %v", fileIssue(br)))
		return
	}
	fmt.Fprintf(w, "running")
}
496252
func (ldr *AEBackupInformationListLoader) LoadInstance(c context.Context, key *datastore.Key) (interface{}, error) {
	store := &AEDatastoreStore{}
	entity, err := store.GetAEBackupInformation(c, key.Parent(), key.IntID())
	if err != nil {
		return nil, err
	}
	return entity, nil
}
414288
func getInstance() *Instance {
	stdOnce.Do(func() {
		std, _ = NewEx(&Config{
			DisableAutoSaveHistory: true,
		})
	})
	return std
}
1185435
func findInstanceSpec(
	c EnvironAPI,
	allImageMetadata []*imagemetadata.ImageMetadata,
	instanceType []instances.InstanceType,
	ic *instances.InstanceConstraint,
) (*instances.InstanceSpec, string, error) {

	logger.Debugf("received %d image(s): %v", len(allImageMetadata), allImageMetadata)
	version, err := series.SeriesVersion(ic.Series)
	if err != nil {
		return nil, "", errors.Trace(err)
	}
	filtered := []*imagemetadata.ImageMetadata{}
	for _, val := range allImageMetadata {
		if val.Version != version {
			continue
		}
		filtered = append(filtered, val)
	}

	images := instances.ImageMetadataToImages(filtered)
	spec, err := instances.FindInstanceSpec(images, ic, instanceType)
	if err != nil {
		return nil, "", errors.Trace(err)
	}

	imagelist, err := getImageName(c, spec.Image.Id)
	if err != nil {
		return nil, "", errors.Trace(err)
	}

	return spec, imagelist, nil
}
529340
func (ldr *AEDatastoreAdminOperationListLoader) LoadInstance(c context.Context, key *datastore.Key) (interface{}, error) {
	store := &AEDatastoreStore{}
	entity, err := store.GetAEDatastoreAdminOperation(c, key.IntID())
	if err != nil {
		return nil, err
	}
	return entity, nil
}
149197
func (m *ModelStatus) MachineInstance(machineID string) (status.StatusInfo, error) {
	return m.getStatus(machineGlobalInstanceKey(machineID), "instance")
}
171223
func (env *joyentEnviron) FindInstanceSpec(
	ic *instances.InstanceConstraint,
	imageMetadata []*imagemetadata.ImageMetadata,
) (*instances.InstanceSpec, error) {
	// Require at least one VCPU so we get KVM rather than smart package.
	if ic.Constraints.CpuCores == nil {
		ic.Constraints.CpuCores = &defaultCpuCores
	}
	allInstanceTypes, err := env.listInstanceTypes()
	if err != nil {
		return nil, err
	}
	images := instances.ImageMetadataToImages(imageMetadata)
	spec, err := instances.FindInstanceSpec(images, ic, allInstanceTypes)
	if err != nil {
		return nil, err
	}
	return spec, nil
}
652085
func (env *environ) StartInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) (*environs.StartInstanceResult, error) {
	// Start a new instance.

	spec, err := buildInstanceSpec(env, args)
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	if err := env.finishInstanceConfig(args, spec); err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	// Validate availability zone.
	volumeAttachmentsZone, err := volumeAttachmentsZone(args.VolumeAttachments)
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}
	if err := validateAvailabilityZoneConsistency(args.AvailabilityZone, volumeAttachmentsZone); err != nil {
		return nil, errors.Trace(err)
	}

	raw, err := newRawInstance(env, ctx, args, spec)
	if err != nil {
		return nil, errors.Trace(err)
	}
	logger.Infof("started instance %q in zone %q", raw.ID, raw.ZoneName)
	inst := newInstance(raw, env)

	// Build the result.
	hwc := getHardwareCharacteristics(env, spec, inst)
	result := environs.StartInstanceResult{
		Instance: inst,
		Hardware: hwc,
	}
	return &result, nil
}
486968
func (env *environ) StartInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) (result *environs.StartInstanceResult, err error) {
	err = env.withSession(ctx, func(env *sessionEnviron) error {
		result, err = env.StartInstance(ctx, args)
		return err
	})
	return result, err
}
660248
func (e *Environ) DistributeInstances(
	ctx context.ProviderCallContext, candidates, distributionGroup []instance.Id, limitZones []string,
) ([]instance.Id, error) {
	valid, err := common.DistributeInstances(e, ctx, candidates, distributionGroup, limitZones)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return valid, err
	}
	return valid, nil
}
976146
func (env *maasEnviron) DistributeInstances(
	ctx context.ProviderCallContext, candidates, distributionGroup []instance.Id, limitZones []string,
) ([]instance.Id, error) {
	return common.DistributeInstances(env, ctx, candidates, distributionGroup, limitZones)
}
838485
func (c *environClient) instances() ([]gosigma.Server, error) {
	return c.conn.ServersFiltered(gosigma.RequestDetail, c.isMyServer)
}
1181758
func (svc *googleService) getInstance() (*googlecloud.Instance, error) {
	return svc.service.Instances.Get(svc.vm.Project, svc.vm.Zone, svc.vm.Name).Do()
}
732656
func (d *raftData) ServiceInstances(service string) []*discoverd.Instance {
	a := make([]*discoverd.Instance, 0, len(d.Instances[service]))
	for _, i := range d.Instances[service] {
		a = append(a, i)
	}

	sort.Sort(instanceSlice(a))
	return a
}