// toInstance returns an *instances.Instance representation of the given
// *model.VM.
434194
func toInstance(vm *model.VM) *instances.Instance {
	inst := &instances.Instance{
		Id:             vm.ID,
		ConfigRevision: vm.Revision,
		Disks:          make([]*instances.Disk, len(vm.Attributes.Disk)),
		Drained:        vm.Drained,
		Hostname:       vm.Hostname,
		Lifetime:       vm.Lifetime,
		Project:        vm.Attributes.Project,
		Swarming:       vm.Swarming,
		Timeout:        vm.Timeout,
		Zone:           vm.Attributes.Zone,
	}
	for i, d := range vm.Attributes.Disk {
		inst.Disks[i] = &instances.Disk{
			Image: d.Image,
		}
	}
	if vm.Created > 0 {
		inst.Created = &timestamp.Timestamp{
			Seconds: vm.Created,
		}
	}
	if vm.Connected > 0 {
		inst.Connected = &timestamp.Timestamp{
			Seconds: vm.Connected,
		}
	}
	return inst
}
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
}
38434
func (env *maasEnviron) StartInstance(
	ctx context.ProviderCallContext,
	args environs.StartInstanceParams,
) (_ *environs.StartInstanceResult, err error) {

	availabilityZone := args.AvailabilityZone
	var nodeName, systemId string
	if args.Placement != "" {
		placement, err := env.parsePlacement(ctx, args.Placement)
		if err != nil {
			return nil, common.ZoneIndependentError(err)
		}
		// NOTE(axw) we wipe out args.AvailabilityZone if the
		// user specified a specific node or system ID via
		// placement, as placement must always take precedence.
		switch {
		case placement.systemId != "":
			availabilityZone = ""
			systemId = placement.systemId
		case placement.nodeName != "":
			availabilityZone = ""
			nodeName = placement.nodeName
		}
	}
	if availabilityZone != "" {
		if err := common.ValidateAvailabilityZone(env, ctx, availabilityZone); err != nil {
			return nil, errors.Trace(err)
		}
		logger.Debugf("attempting to acquire node in zone %q", availabilityZone)
	}

	// Storage.
	volumes, err := buildMAASVolumeParameters(args.Volumes, args.Constraints)
	if err != nil {
		return nil, common.ZoneIndependentError(errors.Annotate(err, "invalid volume parameters"))
	}

	var interfaceBindings []interfaceBinding
	if len(args.EndpointBindings) != 0 {
		for endpoint, spaceProviderID := range args.EndpointBindings {
			interfaceBindings = append(interfaceBindings, interfaceBinding{
				Name:            endpoint,
				SpaceProviderId: string(spaceProviderID),
			})
		}
	}
	selectNode := env.selectNode2
	if !env.usingMAAS2() {
		selectNode = env.selectNode
	}
	inst, selectNodeErr := selectNode(ctx,
		selectNodeArgs{
			Constraints:      args.Constraints,
			AvailabilityZone: availabilityZone,
			NodeName:         nodeName,
			SystemId:         systemId,
			Interfaces:       interfaceBindings,
			Volumes:          volumes,
		})
	if selectNodeErr != nil {
		err := errors.Annotate(selectNodeErr, "failed to acquire node")
		if selectNodeErr.noMatch && availabilityZone != "" {
			// The error was due to MAAS not being able to
			// find provide a machine matching the specified
			// constraints in the zone; try again in another.
			return nil, errors.Trace(err)
		}
		return nil, common.ZoneIndependentError(err)
	}

	defer func() {
		if err != nil {
			if err := env.StopInstances(ctx, inst.Id()); err != nil {
				logger.Errorf("error releasing failed instance: %v", err)
			}
		}
	}()

	hc, err := inst.hardwareCharacteristics()
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	series := args.Tools.OneSeries()
	selectedTools, err := args.Tools.Match(tools.Filter{
		Arch: *hc.Arch,
	})
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}
	if err := args.InstanceConfig.SetTools(selectedTools); err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	hostname, err := inst.hostname()
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	if err := instancecfg.FinishInstanceConfig(args.InstanceConfig, env.Config()); err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	subnetsMap, err := env.subnetToSpaceIds(ctx)
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	cloudcfg, err := env.newCloudinitConfig(hostname, series)
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	userdata, err := providerinit.ComposeUserData(args.InstanceConfig, cloudcfg, MAASRenderer{})
	if err != nil {
		return nil, common.ZoneIndependentError(errors.Annotate(
			err, "could not compose userdata for bootstrap node",
		))
	}
	logger.Debugf("maas user data; %d bytes", len(userdata))

	var displayName string
	var interfaces []network.InterfaceInfo
	if !env.usingMAAS2() {
		inst1 := inst.(*maas1Instance)
		startedNode, err := env.startNode(*inst1.maasObject, series, userdata)
		if err != nil {
			return nil, common.ZoneIndependentError(err)
		}
		// Once the instance has started the response should contain the
		// assigned IP addresses, even when NICs are set to "auto" instead of
		// "static". So instead of selectedNode, which only contains the
		// acquire-time details (no IP addresses for NICs set to "auto" vs
		// "static"),e we use the up-to-date startedNode response to get the
		// interfaces.
		interfaces, err = maasObjectNetworkInterfaces(ctx, startedNode, subnetsMap)
		if err != nil {
			return nil, common.ZoneIndependentError(err)
		}
		env.tagInstance1(inst1, args.InstanceConfig)
		displayName, err = inst1.displayName()
		if err != nil {
			return nil, common.ZoneIndependentError(err)
		}
	} else {
		inst2 := inst.(*maas2Instance)
		startedInst, err := env.startNode2(*inst2, series, userdata)
		if err != nil {
			return nil, common.ZoneIndependentError(err)
		}
		domains, err := env.Domains(ctx)
		if err != nil {
			return nil, errors.Trace(err)
		}
		interfaces, err = maas2NetworkInterfaces(ctx, startedInst, subnetsMap, domains...)
		if err != nil {
			return nil, common.ZoneIndependentError(err)
		}
		env.tagInstance2(inst2, args.InstanceConfig)

		displayName, err = inst2.displayName()
		if err != nil {
			return nil, common.ZoneIndependentError(err)
		}
	}
	logger.Debugf("started instance %q", inst.Id())

	requestedVolumes := make([]names.VolumeTag, len(args.Volumes))
	for i, v := range args.Volumes {
		requestedVolumes[i] = v.Tag
	}
	resultVolumes, resultAttachments, err := inst.volumes(
		names.NewMachineTag(args.InstanceConfig.MachineId),
		requestedVolumes,
	)
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}
	if len(resultVolumes) != len(requestedVolumes) {
		return nil, common.ZoneIndependentError(errors.Errorf(
			"requested %v storage volumes. %v returned",
			len(requestedVolumes), len(resultVolumes),
		))
	}

	return &environs.StartInstanceResult{
		DisplayName:       displayName,
		Instance:          inst,
		Hardware:          hc,
		NetworkInfo:       interfaces,
		Volumes:           resultVolumes,
		VolumeAttachments: resultAttachments,
	}, nil
}
696502
func (client *Client) DeleteInstance(instanceId string) error {
	args := DeleteDBInstanceArgs{DBInstanceId: instanceId}
	response := DeleteDBInstanceResponse{}
	err := client.Invoke("DeleteDBInstance", &args, &response)
	return err
}
114626
func serviceToInstance(service *registry.Service) (*fargo.Instance, error) {
	if len(service.Nodes) == 0 {
		return nil, errors.New("Require nodes")
	}

	node := service.Nodes[0]

	instance := &fargo.Instance{
		App:              service.Name,
		HostName:         node.Address,
		IPAddr:           node.Address,
		VipAddress:       node.Address,
		SecureVipAddress: node.Address,
		Port:             node.Port,
		Status:           fargo.UP,
		UniqueID: func(i fargo.Instance) string {
			return fmt.Sprintf("%s:%s", node.Address, node.Id)
		},
		DataCenterInfo: fargo.DataCenterInfo{Name: fargo.MyOwn},
	}

	// set version
	instance.SetMetadataString("version", service.Version)

	// set instance ID
	instance.SetMetadataString("instanceId", node.Id)

	// set endpoints
	if b, err := json.Marshal(service.Endpoints); err == nil {
		instance.SetMetadataString("endpoints", string(b))
	}

	// set metadata
	if b, err := json.Marshal(node.Metadata); err == nil {
		instance.SetMetadataString("metadata", string(b))
	}

	return instance, nil
}
1240618
func NewInstancesServer() instances.InstancesServer {
	return &instances.DecoratedInstances{
		Prelude:  vmAccessPrelude,
		Service:  &Instances{},
		Postlude: gRPCifyAndLogErr,
	}
}
551992
func (o *OracleEnviron) StartInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) (*environs.StartInstanceResult, error) {
	if args.ControllerUUID == "" {
		return nil, errors.NotFoundf("Controller UUID")
	}

	series := args.Tools.OneSeries()
	arches := args.Tools.Arches()

	// take all instance types from the oracle cloud provider
	types, err := instanceTypes(o.client)
	if err != nil {
		return nil, errors.Trace(err)
	}

	// check if we find an image that is compliant with the
	// constraints provided in the oracle cloud account
	if args.ImageMetadata, err = checkImageList(o.client); err != nil {
		return nil, errors.Trace(err)
	}

	// find the best suitable instance based on
	// the oracle cloud instance types,
	// the images that already matched the juju constrains
	spec, imagelist, err := findInstanceSpec(
		o.client,
		args.ImageMetadata,
		types,
		&envinstance.InstanceConstraint{
			Region:      o.spec.Region,
			Series:      series,
			Arches:      arches,
			Constraints: args.Constraints,
		},
	)
	if err != nil {
		return nil, errors.Trace(err)
	}

	tools, err := args.Tools.Match(tools.Filter{Arch: spec.Image.Arch})
	if err != nil {
		return nil, errors.Trace(err)
	}
	logger.Tracef("agent binaries: %v", tools)
	if err = args.InstanceConfig.SetTools(tools); err != nil {
		return nil, errors.Trace(err)
	}

	if err = instancecfg.FinishInstanceConfig(
		args.InstanceConfig,
		o.Config(),
	); err != nil {
		return nil, errors.Trace(err)
	}

	hostname, err := o.namespace.Hostname(args.InstanceConfig.MachineId)
	if err != nil {
		return nil, errors.Trace(err)
	}

	machineName := o.client.ComposeName(hostname)
	imageName := o.client.ComposeName(imagelist)

	tags := make([]string, 0, len(args.InstanceConfig.Tags)+1)
	for k, v := range args.InstanceConfig.Tags {
		if k == "" || v == "" {
			continue
		}
		t := tagValue{k, v}
		tags = append(tags, t.String())
	}
	tags = append(tags, machineName)

	var apiPort int
	var desiredStatus ociCommon.InstanceState
	if args.InstanceConfig.Controller != nil {
		apiPort = args.InstanceConfig.Controller.Config.APIPort()
		desiredStatus = ociCommon.StateRunning
	} else {
		// All ports are the same so pick the first.
		apiPort = args.InstanceConfig.APIInfo.Ports()[0]
		desiredStatus = ociCommon.StateStarting
	}

	// create a new seclists
	secLists, err := o.CreateMachineSecLists(
		args.InstanceConfig.MachineId, apiPort)
	if err != nil {
		return nil, errors.Trace(err)
	}
	logger.Debugf("Creating vnic sets")
	vnicSets, err := o.ensureVnicSet(ctx, args.InstanceConfig.MachineId, tags)
	if err != nil {
		return nil, errors.Trace(err)
	}
	// fetch instance network card configuration
	logger.Debugf("Getting instance networks")
	networking, err := o.getInstanceNetworks(ctx, args, secLists, []string{vnicSets.Name})
	if err != nil {
		return nil, errors.Trace(err)
	}

	logger.Debugf("Getting cloud config")
	cloudcfg, err := o.getCloudInitConfig(args.InstanceConfig.Series, networking)
	if err != nil {
		return nil, errors.Annotate(err, "cannot create cloudinit template")
	}

	// compose userdata with the cloud config template
	logger.Debugf("Composing userdata")
	userData, err := providerinit.ComposeUserData(
		args.InstanceConfig,
		cloudcfg,
		OracleRenderer{},
	)
	if err != nil {
		return nil, errors.Annotate(err, "cannot make user data")
	}

	logger.Debugf("oracle user data: %d bytes", len(userData))

	attributes := map[string]interface{}{
		"userdata": string(userData),
	}

	// create the instance based on the instance params
	instance, err := o.createInstance(oci.InstanceParams{
		Instances: []oci.Instances{
			{
				Shape:       spec.InstanceType.Name,
				Imagelist:   imageName,
				Name:        machineName,
				Label:       args.InstanceConfig.MachineAgentServiceName,
				Hostname:    hostname,
				Tags:        tags,
				Attributes:  attributes,
				Reverse_dns: true,
				Networking:  networking,
			},
		},
	})
	if err != nil {
		return nil, errors.Trace(err)
	}

	instance.arch = &spec.Image.Arch
	instance.instType = &spec.InstanceType

	machineId := instance.machine.Name
	timeout := 10 * time.Minute
	if err := instance.waitForMachineStatus(desiredStatus, timeout); err != nil {
		return nil, errors.Trace(err)
	}
	logger.Infof("started instance %q", machineId)

	//TODO: add config option for public IP allocation
	logger.Debugf("Associating public IP to instance %q", machineId)
	if err := instance.associatePublicIP(); err != nil {
		return nil, errors.Trace(err)
	}
	result := &environs.StartInstanceResult{
		Instance: instance,
		Hardware: instance.hardwareCharacteristics(),
	}

	return result, nil
}
1137241
func newInstances(c context.Context, acc, host string) instances.InstancesClient {
	return instances.NewInstancesPRPCClient(&prpc.Client{
		C:    client.NewClient(getMetadata(c), acc),
		Host: host,
	})
}
533228
func (s *State) ResourceInstance(addr addrs.AbsResourceInstance) *ResourceInstance {
	if s == nil {
		panic("State.ResourceInstance on nil *State")
	}
	ms := s.Module(addr.Module)
	if ms == nil {
		return nil
	}
	return ms.ResourceInstance(addr.Resource)
}
767347
func LookupInstance(ctx context.Context, instance string) (Service, error) {
	var srv Service

	conn, err := NewMDNSConn()
	if err != nil {
		return srv, err
	}

	return lookupInstance(ctx, instance, conn)
}
414288
func getInstance() *Instance {
	stdOnce.Do(func() {
		std, _ = NewEx(&Config{
			DisableAutoSaveHistory: true,
		})
	})
	return std
}
1042931
func (i *awsInstance) describeInstance() (*ec2.Instance, error) {
	return describeInstance(i.ec2, InstanceID(i.awsID))
}
695359
func (cl *cloudLaunch) lookupInstance() *compute.Instance {
	inst, err := cl.computeService.Instances.Get(cl.GCEProjectID, cl.zone(), cl.instName()).Do()
	if ae, ok := err.(*googleapi.Error); ok && ae.Code == 404 {
		return nil
	} else if err != nil {
		log.Fatalf("Instances.Get: %v", err)
	}
	return inst
}
1291731
func newInstance(params response.Instance, env *OracleEnviron) (*oracleInstance, error) {
	if params.Name == "" {
		return nil, errors.New(
			"Instance response does not contain a name",
		)
	}
	name, err := extractInstanceIDFromMachineName(params.Name)
	if err != nil {
		return nil, err
	}
	mutex := &sync.Mutex{}
	instance := &oracleInstance{
		name: string(name),
		status: instance.Status{
			Status:  status.Status(params.State),
			Message: "",
		},
		machine: params,
		mutex:   mutex,
		env:     env,
	}

	return instance, nil
}
1136060
func (env *azureEnviron) allInstances(
	ctx context.ProviderCallContext,
	resourceGroup string,
	refreshAddresses bool,
	controllerOnly bool,
) ([]instances.Instance, error) {
	deploymentsClient := resources.DeploymentsClient{env.resources}
	sdkCtx := stdcontext.Background()
	deploymentsResult, err := deploymentsClient.ListByResourceGroupComplete(sdkCtx, resourceGroup, "", nil)
	if err != nil {
		if isNotFoundResult(deploymentsResult.Response().Response) {
			// This will occur if the resource group does not
			// exist, e.g. in a fresh hosted environment.
			return nil, nil
		}
		return nil, errorutils.HandleCredentialError(errors.Trace(err), ctx)
	}
	if deploymentsResult.Response().IsEmpty() {
		return nil, nil
	}

	var azureInstances []*azureInstance
	for ; deploymentsResult.NotDone(); err = deploymentsResult.NextWithContext(sdkCtx) {
		if err != nil {
			return nil, errors.Annotate(err, "listing resources")
		}
		deployment := deploymentsResult.Value()
		name := to.String(deployment.Name)
		if _, err := names.ParseMachineTag(name); err != nil {
			// Deployments we create for Juju machines are named
			// with the machine tag. We also create a "common"
			// deployment, so this will exclude that VM and any
			// other stray deployment resources.
			continue
		}
		if deployment.Properties == nil || deployment.Properties.Dependencies == nil {
			continue
		}
		if controllerOnly && !isControllerDeployment(deployment) {
			continue
		}
		provisioningState := to.String(deployment.Properties.ProvisioningState)
		inst := &azureInstance{name, provisioningState, env, nil, nil}
		azureInstances = append(azureInstances, inst)
	}

	if len(azureInstances) > 0 && refreshAddresses {
		if err := setInstanceAddresses(
			ctx,
			resourceGroup,
			network.InterfacesClient{env.network},
			network.PublicIPAddressesClient{env.network},
			azureInstances,
		); err != nil {
			return nil, errors.Trace(err)
		}
	}

	instances := make([]instances.Instance, len(azureInstances))
	for i, inst := range azureInstances {
		instances[i] = inst
	}
	return instances, nil
}
405798
func (env *environ) StartInstance(
	ctx context.ProviderCallContext, args environs.StartInstanceParams,
) (*environs.StartInstanceResult, error) {
	series := args.Tools.OneSeries()
	logger.Debugf("StartInstance: %q, %s", args.InstanceConfig.MachineId, series)

	arch, err := env.finishInstanceConfig(args)
	if err != nil {
		return nil, errors.Trace(err)
	}

	container, err := env.newContainer(ctx, args, arch)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		if args.StatusCallback != nil {
			args.StatusCallback(status.ProvisioningError, err.Error(), nil)
		}
		return nil, errors.Trace(err)
	}
	logger.Infof("started instance %q", container.Name)
	inst := newInstance(container, env)

	// Build the result.
	hwc := env.getHardwareCharacteristics(args, inst)
	result := environs.StartInstanceResult{
		Instance: inst,
		Hardware: hwc,
	}
	return &result, nil
}
1161023
func (c *Changes) ResourceInstance(addr addrs.AbsResourceInstance) *ResourceInstanceChangeSrc {
	addrStr := addr.String()
	for _, rc := range c.Resources {
		if rc.Addr.String() == addrStr && rc.DeposedKey == states.NotDeposed {
			return rc
		}
	}

	return nil
}