// StartInstance is part of the InstanceBroker interface.
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
}
6769
func (d *driverOCI) CreateInstance(ctx context.Context, publicKey string) (string, error) {
	metadata := map[string]string{
		"ssh_authorized_keys": publicKey,
	}
	if d.cfg.Metadata != nil {
		for key, value := range d.cfg.Metadata {
			metadata[key] = value
		}
	}
	if d.cfg.UserData != "" {
		metadata["user_data"] = d.cfg.UserData
	}

	instanceDetails := core.LaunchInstanceDetails{
		AvailabilityDomain: &d.cfg.AvailabilityDomain,
		CompartmentId:      &d.cfg.CompartmentID,
		ImageId:            &d.cfg.BaseImageID,
		Shape:              &d.cfg.Shape,
		SubnetId:           &d.cfg.SubnetID,
		Metadata:           metadata,
	}

	// When empty, the default display name is used.
	if d.cfg.InstanceName != "" {
		instanceDetails.DisplayName = &d.cfg.InstanceName
	}

	instance, err := d.computeClient.LaunchInstance(context.TODO(), core.LaunchInstanceRequest{LaunchInstanceDetails: instanceDetails})

	if err != nil {
		return "", err
	}

	return *instance.Id, nil
}
1345071
func (rs *Resource) EnsureInstance(key addrs.InstanceKey) *ResourceInstance {
	ret := rs.Instance(key)
	if ret == nil {
		ret = NewResourceInstance()
		rs.Instances[key] = ret
	}
	return ret
}
1358033
func (env *sessionEnviron) StartInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) (*environs.StartInstanceResult, error) {
	img, err := findImageMetadata(env, args)
	if err != nil {
		return nil, common.ZoneIndependentError(err)
	}
	if err := env.finishMachineConfig(args, img); err != nil {
		return nil, common.ZoneIndependentError(err)
	}

	vm, hw, err := env.newRawInstance(ctx, args, img)
	if err != nil {
		args.StatusCallback(status.ProvisioningError, fmt.Sprint(err), nil)
		return nil, errors.Trace(err)
	}

	logger.Infof("started instance %q", vm.Name)
	logger.Tracef("instance data %+v", vm)
	inst := newInstance(vm, env.environ)
	result := environs.StartInstanceResult{
		Instance: inst,
		Hardware: hw,
	}
	return &result, nil
}
53201
func (f *Facade) getInstance(ctx datastore.Context, hst host.Host, svc service.Service, imageUUID string, state zkservice.State) (*service.Instance, error) {
	logger := plog.WithFields(log.Fields{
		"hostid":     state.HostID,
		"serviceid":  state.ServiceID,
		"instanceid": state.InstanceID,
	})

	// get the current state
	var curState service.InstanceCurrentState
	curState = service.InstanceCurrentState(state.CurrentStateContainer.Status)

	if svc.EmergencyShutdown {
		if curState == service.StateStopped {
			curState = service.StateEmergencyStopped
		} else if curState == service.StateStopping {
			curState = service.StateEmergencyStopping
		}
	}

	logger.Debug("Calulated service status")

	svch := service.BuildServiceHealth(svc)

	inst := &service.Instance{
		InstanceID:    state.InstanceID,
		HostID:        hst.ID,
		HostName:      hst.Name,
		ServiceID:     svc.ID,
		ServiceName:   svc.Name,
		ContainerID:   state.ContainerID,
		ImageSynced:   imageUUID == state.ImageUUID,
		DesiredState:  state.DesiredState,
		CurrentState:  curState,
		HealthStatus:  f.getInstanceHealth(svch, state.InstanceID),
		RAMCommitment: int64(svc.RAMCommitment.Value),
		Scheduled:     state.Scheduled,
		Started:       state.Started,
		Terminated:    state.Terminated,
	}
	logger.Debug("Loaded service instance")

	return inst, nil
}
300668
func (gce *Connection) AddInstance(spec InstanceSpec) (*Instance, error) {
	raw := spec.raw()
	if err := gce.addInstance(raw, spec.Type, spec.AvailabilityZone); err != nil {
		return nil, errors.Trace(err)
	}

	return newInstance(raw, &spec), nil
}
1341538
func (e *Environ) StartInstance(ctx envcontext.ProviderCallContext, args environs.StartInstanceParams) (*environs.StartInstanceResult, error) {
	if args.ControllerUUID == "" {
		return nil, errors.NotFoundf("Controller UUID")
	}

	networks, err := e.ensureNetworksAndSubnets(ctx, args.ControllerUUID, e.Config().UUID())
	if err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return nil, errors.Trace(err)
	}

	zones, err := e.AvailabilityZones(ctx)
	if err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return nil, errors.Trace(err)
	}

	zone := zones[0].Name()
	network := networks[zone][0]
	// refresh the global image cache
	// this only hits the API every 30 minutes, otherwise just retrieves
	// from cache
	imgCache, err := refreshImageCache(e.Compute, e.ecfg().compartmentID())
	if err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return nil, errors.Trace(err)
	}
	logger.Tracef("Image cache contains: %# v", pretty.Formatter(imgCache))

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

	types := imgCache.SupportedShapes(series)

	defaultType := string(VirtualMachine)
	if args.Constraints.VirtType == nil {
		args.Constraints.VirtType = &defaultType
	}

	// check if we find an image that is compliant with the
	// constraints provided in the oracle cloud account
	args.ImageMetadata = imgCache.ImageMetadata(series, *args.Constraints.VirtType)

	spec, image, err := findInstanceSpec(
		args.ImageMetadata,
		types,
		&instances.InstanceConstraint{
			Series:      series,
			Arches:      arches,
			Constraints: args.Constraints,
		},
	)
	if err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return nil, errors.Trace(err)
	}

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

	if err = instancecfg.FinishInstanceConfig(
		args.InstanceConfig,
		e.Config(),
	); err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return nil, errors.Trace(err)
	}
	hostname, err := e.namespace.Hostname(args.InstanceConfig.MachineId)
	if err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return nil, errors.Trace(err)
	}
	tags := args.InstanceConfig.Tags

	var apiPort int
	var desiredStatus ociCore.InstanceLifecycleStateEnum
	// If we are bootstrapping a new controller, we want to wait for the
	// machine to reach running state before attempting to SSH into it,
	// to configure the controller.
	// If the machine that is spawning is not a controller, then userdata
	// will take care of it's initial setup, and waiting for a running
	// status is not necessary
	if args.InstanceConfig.Controller != nil {
		apiPort = args.InstanceConfig.Controller.Config.APIPort()
		desiredStatus = ociCore.InstanceLifecycleStateRunning
	} else {
		desiredStatus = ociCore.InstanceLifecycleStateProvisioning
	}

	cloudcfg, err := e.getCloudInitConfig(series, apiPort)
	if err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		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,
		OCIRenderer{},
	)
	if err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return nil, errors.Annotate(err, "cannot make user data")
	}

	var rootDiskSizeGB int
	if args.Constraints.RootDisk != nil {
		rootDiskSizeGB = int(*args.Constraints.RootDisk) / 1024
		if int(*args.Constraints.RootDisk) < MinVolumeSizeMB {
			logger.Warningf(
				"selected disk size is too small (%d MB). Setting root disk size to minimum volume size (%d MB)",
				int(*args.Constraints.RootDisk), MinVolumeSizeMB)
			rootDiskSizeGB = MinVolumeSizeMB / 1024
		} else if int(*args.Constraints.RootDisk) > MaxVolumeSizeMB {
			logger.Warningf(
				"selected disk size is too large (%d MB). Setting root disk size to maximum volume size (%d MB)",
				int(*args.Constraints.RootDisk), MaxVolumeSizeMB)
			rootDiskSizeGB = MaxVolumeSizeMB / 1024
		}
	} else {
		rootDiskSizeGB = MinVolumeSizeMB / 1024
	}

	assignPublicIp := true
	bootSource := ociCore.InstanceSourceViaImageDetails{
		ImageId:             &image,
		BootVolumeSizeInGBs: &rootDiskSizeGB,
	}
	instanceDetails := ociCore.LaunchInstanceDetails{
		AvailabilityDomain: &zone,
		CompartmentId:      e.ecfg().compartmentID(),
		SourceDetails:      bootSource,
		Shape:              &spec.InstanceType.Name,
		CreateVnicDetails: &ociCore.CreateVnicDetails{
			SubnetId:       network.Id,
			AssignPublicIp: &assignPublicIp,
			DisplayName:    &hostname,
		},
		DisplayName: &hostname,
		Metadata: map[string]string{
			"user_data": string(userData),
		},
		FreeformTags: tags,
	}

	request := ociCore.LaunchInstanceRequest{
		LaunchInstanceDetails: instanceDetails,
	}

	response, err := e.Compute.LaunchInstance(context.Background(), request)
	if err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return nil, errors.Trace(err)
	}

	instance, err := newInstance(response.Instance, e)
	if err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return nil, errors.Trace(err)
	}

	machineId := response.Instance.Id
	timeout := 10 * time.Minute
	if err := instance.waitForMachineStatus(desiredStatus, timeout); err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return nil, errors.Trace(err)
	}
	logger.Infof("started instance %q", *machineId)
	displayName := shortenMachineId(machineId, 6)

	if desiredStatus == ociCore.InstanceLifecycleStateRunning {
		if err := instance.waitForPublicIP(ctx); err != nil {
			providerCommon.HandleCredentialError(err, ctx)
			return nil, errors.Trace(err)
		}
	}

	result := &environs.StartInstanceResult{
		DisplayName: displayName,
		Instance:    instance,
		Hardware:    instance.hardwareCharacteristics(),
	}

	return result, nil
}
53781
func (m *PCPInstanceMetric) SetInstance(val interface{}, instance string) error {
	m.mutex.Lock()
	defer m.mutex.Unlock()

	return m.setInstance(val, instance)
}
159365
func (d *driver) getInstance(ctx types.Context) (awsec2.Instance, error) {
	diInput := &awsec2.DescribeInstancesInput{
		InstanceIds: []*string{mustInstanceIDID(ctx)},
	}
	resp, err := mustSession(ctx).DescribeInstances(diInput)
	if err != nil {
		return awsec2.Instance{}, goof.WithError(
			"error retrieving instance with EC2 API call", err)
	}
	return *resp.Reservations[0].Instances[0], nil
}
1271453
func (instanceApi *InstanceApi) Start(id string) (bool, error) {
	_, err := instanceApi.entityService.Execute(id, INSTANCE_START_OPERATION, []byte{}, map[string]string{})
	return err == nil, err
}
374933
func (client *Client) CreateInstance(args *CreateInstanceArgs) (instanceId string, err error) {
	if args.UserData != "" {
		// Encode to base64 string
		args.UserData = base64.StdEncoding.EncodeToString([]byte(args.UserData))
	}
	response := CreateInstanceResponse{}
	err = client.Invoke("CreateInstance", args, &response)
	if err != nil {
		return "", err
	}
	return response.InstanceId, err
}
444508
func (svc *googleService) start() error {
	instance, err := svc.getInstance()
	if err != nil {
		if !strings.Contains(err.Error(), "no instance found") {
			return err
		}
	}

	if instance == nil {
		return errors.New("no instance found")
	}

	op, err := svc.service.Instances.Start(svc.vm.Project, svc.vm.Zone, svc.vm.Name).Do()
	if err != nil {
		return err
	}

	return svc.waitForOperationReady(op.Name)
}
1304945
func (o *OracleEnviron) AllInstances(ctx context.ProviderCallContext) ([]envinstance.Instance, error) {
	tagFilter := tagValue{tags.JujuModel, o.Config().UUID()}
	all, err := o.allInstances(tagFilter)
	if err != nil {
		return nil, err
	}

	ret := make([]envinstance.Instance, len(all))
	for i, val := range all {
		ret[i] = val
	}
	return ret, nil
}
304665
func (a *AppInstance) InitAppInstance(instanceID string) {
	var err error
	a.Events = make(chan *Event)
	a.responseChannel = make(chan *CommandResponse)
	commandTopic := strings.Join([]string{"commands", instanceID}, "_")
	fmt.Println("Command topic is: ", commandTopic)
	responseTopic := strings.Join([]string{"responses", instanceID}, "_")
	a.commandChannel, err = bus.StartProducer(commandTopic)
	a.commandChannel <- []byte("DUMMY")
	if err != nil {
		fmt.Println(err)
	}
	eventBus, err := bus.StartConsumer(strings.Join([]string{"events", instanceID}, "_"))
	if err != nil {
		fmt.Println(err)
	}
	processEvents(eventBus, a.Events)
	responseBus, err := bus.StartConsumer(responseTopic)
	if err != nil {
		fmt.Println(err)
	}
	a.processCommandResponses(responseBus, a.responseChannel)
}
777364
func (e *Environ) AllInstances(ctx envcontext.ProviderCallContext) ([]instances.Instance, error) {
	tags := map[string]string{
		tags.JujuModel: e.Config().UUID(),
	}
	allInstances, err := e.allInstances(ctx, tags)
	if err != nil {
		providerCommon.HandleCredentialError(err, ctx)
		return nil, errors.Trace(err)
	}

	ret := []instances.Instance{}
	for _, val := range allInstances {
		ret = append(ret, val)
	}
	return ret, nil
}
398519
func newInstanceManager(c *instanceManagerConfig) *instanceManager {

	ctx, cancel := context.WithCancel(c.Ctx)
	i := &instanceManager{
		logger:             c.Logger.With("plugin", c.Id.Name),
		ctx:                ctx,
		cancel:             cancel,
		loader:             c.Loader,
		storeReattach:      c.StoreReattach,
		pluginConfig:       c.PluginConfig,
		id:                 c.Id,
		fingerprintOutCh:   c.FingerprintOutCh,
		statsInterval:      c.StatsInterval,
		firstFingerprintCh: make(chan struct{}),
	}

	go i.run()
	return i
}
400065
func newInstanceManager(c *instanceManagerConfig) *instanceManager {

	ctx, cancel := context.WithCancel(c.Ctx)
	i := &instanceManager{
		logger:               c.Logger.With("driver", c.ID.Name),
		ctx:                  ctx,
		cancel:               cancel,
		loader:               c.Loader,
		storeReattach:        c.StoreReattach,
		fetchReattach:        c.FetchReattach,
		pluginConfig:         c.PluginConfig,
		id:                   c.ID,
		updateNodeFromDriver: c.UpdateNodeFromDriver,
		eventHandlerFactory:  c.EventHandlerFactory,
		firstFingerprintCh:   make(chan struct{}),
	}

	go i.run()
	return i
}