// StartInstance is specified in the InstanceBroker interface.
160858
func (e *environ) StartInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) (_ *environs.StartInstanceResult, resultErr error) {
	var inst *ec2Instance
	callback := args.StatusCallback
	defer func() {
		if resultErr == nil || inst == nil {
			return
		}
		if err := e.StopInstances(ctx, inst.Id()); err != nil {
			callback(status.Error, fmt.Sprintf("error stopping failed instance: %v", err), nil)
			logger.Errorf("error stopping failed instance: %v", err)
		}
	}()

	callback(status.Allocating, "Verifying availability zone", nil)

	annotateWrapError := func(received error, annotation string) error {
		if received == nil {
			return nil
		}
		// If there is a problem with authentication/authorisation,
		// we want a correctly typed error.
		annotatedErr := errors.Annotate(
			maybeConvertCredentialError(received, ctx),
			annotation)
		if common.IsCredentialNotValid(annotatedErr) {
			return annotatedErr
		}
		return common.ZoneIndependentError(annotatedErr)
	}

	wrapError := func(received error) error {
		return annotateWrapError(received, "")
	}

	// Verify the provided availability zone to start the instance in.  It's
	// provided via StartInstanceParams Constraints or AvailabilityZone.
	// The availability zone of existing volumes that are to be
	// attached to the machine must all match, and must be the same
	// as specified zone (if any).
	availabilityZone, placementSubnetID, err := e.deriveAvailabilityZoneAndSubnetID(ctx, args)
	if err != nil {
		// An IsNotValid error is returned if the zone is invalid;
		// this is a zone-specific error.
		zoneSpecific := errors.IsNotValid(err)
		if !zoneSpecific {
			return nil, wrapError(err)
		}
		return nil, err
	}

	arches := args.Tools.Arches()

	instanceTypes, err := e.supportedInstanceTypes(ctx)
	if err != nil {
		return nil, wrapError(err)
	}

	spec, err := findInstanceSpec(
		args.InstanceConfig.Controller != nil,
		args.ImageMetadata,
		instanceTypes,
		&instances.InstanceConstraint{
			Region:      e.cloud.Region,
			Series:      args.InstanceConfig.Series,
			Arches:      arches,
			Constraints: args.Constraints,
			Storage:     []string{ssdStorage, ebsStorage},
		},
	)
	if err != nil {
		return nil, wrapError(err)
	}
	tools, err := args.Tools.Match(tools.Filter{Arch: spec.Image.Arch})
	if err != nil {
		return nil, common.ZoneIndependentError(
			errors.Errorf("chosen architecture %v not present in %v", spec.Image.Arch, arches),
		)
	}

	if spec.InstanceType.Deprecated {
		logger.Infof("deprecated instance type specified: %s", spec.InstanceType.Name)
	}

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

	callback(status.Allocating, "Making user data", nil)
	userData, err := providerinit.ComposeUserData(args.InstanceConfig, nil, AmazonRenderer{})
	if err != nil {
		return nil, common.ZoneIndependentError(
			errors.Annotate(err, "cannot make user data"),
		)
	}
	logger.Debugf("ec2 user data; %d bytes", len(userData))
	apiPorts := make([]int, 0, 2)
	if args.InstanceConfig.Controller != nil {
		apiPorts = append(apiPorts, args.InstanceConfig.Controller.Config.APIPort())
		if args.InstanceConfig.Controller.Config.AutocertDNSName() != "" {
			// Open port 80 as well as it handles Let's Encrypt HTTP challenge.
			apiPorts = append(apiPorts, 80)
		}
	} else {
		apiPorts = append(apiPorts, args.InstanceConfig.APIInfo.Ports()[0])
	}
	callback(status.Allocating, "Setting up groups", nil)
	groups, err := e.setUpGroups(ctx, args.ControllerUUID, args.InstanceConfig.MachineId, apiPorts)
	if err != nil {
		return nil, annotateWrapError(err, "cannot set up groups")
	}

	blockDeviceMappings := getBlockDeviceMappings(
		args.Constraints,
		args.InstanceConfig.Series,
		args.InstanceConfig.Controller != nil,
	)
	rootDiskSize := uint64(blockDeviceMappings[0].VolumeSize) * 1024

	// If --constraints spaces=foo was passed, the provisioner will populate
	// args.SubnetsToZones map. In AWS a subnet can span only one zone, so here
	// we build the reverse map zonesToSubnets, which we will use to below in
	// the RunInstance loop to provide an explicit subnet ID, rather than just
	// AZ. This ensures instances in the same group (units of an application or all
	// instances when adding a machine manually) will still be evenly
	// distributed across AZs, but only within subnets of the space constraint.
	//
	// TODO(dimitern): This should be done in a provider-independent way.
	if spaces := args.Constraints.IncludeSpaces(); len(spaces) > 1 {
		logger.Infof("ignoring all but the first positive space from constraints: %v", spaces)
	}

	var instResp *ec2.RunInstancesResp
	commonRunArgs := &ec2.RunInstances{
		MinCount:            1,
		MaxCount:            1,
		UserData:            userData,
		InstanceType:        spec.InstanceType.Name,
		SecurityGroups:      groups,
		BlockDeviceMappings: blockDeviceMappings,
		ImageId:             spec.Image.Id,
	}

	runArgs := commonRunArgs
	runArgs.AvailZone = availabilityZone

	haveVPCID := isVPCIDSet(e.ecfg().vpcID())
	var subnetIDsForZone []string
	var subnetErr error
	if haveVPCID {
		var allowedSubnetIDs []string
		if placementSubnetID != "" {
			allowedSubnetIDs = []string{placementSubnetID}
		} else {
			for subnetID := range args.SubnetsToZones {
				allowedSubnetIDs = append(allowedSubnetIDs, string(subnetID))
			}
		}
		subnetIDsForZone, subnetErr = getVPCSubnetIDsForAvailabilityZone(e.ec2, ctx, e.ecfg().vpcID(), availabilityZone, allowedSubnetIDs)
	} else if args.Constraints.HasSpaces() {
		subnetIDsForZone, subnetErr = findSubnetIDsForAvailabilityZone(availabilityZone, args.SubnetsToZones)
		if subnetErr == nil && placementSubnetID != "" {
			asSet := set.NewStrings(subnetIDsForZone...)
			if asSet.Contains(placementSubnetID) {
				subnetIDsForZone = []string{placementSubnetID}
			} else {
				subnetIDsForZone = nil
				subnetErr = errors.NotFoundf("subnets %q in AZ %q", placementSubnetID, availabilityZone)
			}
		}
	}

	switch {
	case subnetErr != nil && errors.IsNotFound(subnetErr):
		return nil, errors.Trace(subnetErr)
	case subnetErr != nil:
		return nil, errors.Annotatef(maybeConvertCredentialError(subnetErr, ctx), "getting subnets for zone %q", availabilityZone)
	case len(subnetIDsForZone) > 1:
		// With multiple equally suitable subnets, picking one at random
		// will allow for better instance spread within the same zone, and
		// still work correctly if we happen to pick a constrained subnet
		// (we'll just treat this the same way we treat constrained zones
		// and retry).
		runArgs.SubnetId = subnetIDsForZone[rand.Intn(len(subnetIDsForZone))]
		logger.Debugf("selected random subnet %q from all matching in zone %q", runArgs.SubnetId, availabilityZone)
	case len(subnetIDsForZone) == 1:
		runArgs.SubnetId = subnetIDsForZone[0]
		logger.Debugf("selected subnet %q in zone %q", runArgs.SubnetId, availabilityZone)
	}

	callback(status.Allocating, fmt.Sprintf("Trying to start instance in availability zone %q", availabilityZone), nil)
	instResp, err = runInstances(e.ec2, ctx, runArgs, callback)
	if err != nil {
		if !isZoneOrSubnetConstrainedError(err) {
			err = annotateWrapError(err, "cannot run instances")
		}
		return nil, err
	}
	if len(instResp.Instances) != 1 {
		return nil, errors.Errorf("expected 1 started instance, got %d", len(instResp.Instances))
	}

	inst = &ec2Instance{
		e:        e,
		Instance: &instResp.Instances[0],
	}
	instAZ := inst.Instance.AvailZone
	if haveVPCID {
		instVPC := e.ecfg().vpcID()
		instSubnet := inst.Instance.SubnetId
		logger.Infof("started instance %q in AZ %q, subnet %q, VPC %q", inst.Id(), instAZ, instSubnet, instVPC)
	} else {
		logger.Infof("started instance %q in AZ %q", inst.Id(), instAZ)
	}

	// Tag instance, for accounting and identification.
	instanceName := resourceName(
		names.NewMachineTag(args.InstanceConfig.MachineId), e.Config().Name(),
	)
	args.InstanceConfig.Tags[tagName] = instanceName
	if err := tagResources(e.ec2, ctx, args.InstanceConfig.Tags, string(inst.Id())); err != nil {
		return nil, annotateWrapError(err, "tagging instance")
	}

	// Tag the machine's root EBS volume, if it has one.
	if inst.Instance.RootDeviceType == "ebs" {
		cfg := e.Config()
		tags := tags.ResourceTags(
			names.NewModelTag(cfg.UUID()),
			names.NewControllerTag(args.ControllerUUID),
			cfg,
		)
		tags[tagName] = instanceName + "-root"
		if err := tagRootDisk(e.ec2, ctx, tags, inst.Instance); err != nil {
			return nil, annotateWrapError(err, "tagging root disk")
		}
	}

	hc := instance.HardwareCharacteristics{
		Arch:     &spec.Image.Arch,
		Mem:      &spec.InstanceType.Mem,
		CpuCores: &spec.InstanceType.CpuCores,
		CpuPower: spec.InstanceType.CpuPower,
		RootDisk: &rootDiskSize,
		// Tags currently not supported by EC2
		AvailabilityZone: &inst.Instance.AvailZone,
	}
	return &environs.StartInstanceResult{
		Instance: inst,
		Hardware: &hc,
	}, nil
}
1100689
func (broker *lxdBroker) MaintainInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) error {
	machineID := args.InstanceConfig.MachineId

	// There's no InterfaceInfo we expect to get below.
	_, err := prepareOrGetContainerInterfaceInfo(
		broker.api,
		machineID,
		false, // maintain, do not allocate.
		lxdLogger,
	)
	return err
}
1084535
func (c *Container) Instance(i interface{}) {
	w := newServiceWrapperInstance(i, true)
	c.registered = append(c.registered, w)
}
47482
func (l *ServiceListener) Start(sn *ServiceNode, instanceID int) bool {

	l.mu.Lock()
	defer l.mu.Unlock()

	logger := plog.WithFields(log.Fields{
		"serviceid":                   sn.ID,
		"servicename":                 sn.Name,
		"shouldhaveaddressassignment": sn.ShouldHaveAddressAssignment,
		"instanceid":                  instanceID,
	})

	// pick a host
	hostID, err := l.handler.SelectHost(sn)
	if err != nil {
		logger.WithError(err).Warn("Could not select host")
		return false
	}
	// CC-3656: If the strategy doesn't select a host, an invalid service state is created.
	if hostID == "" {
		// The selected strategy didn't select any hosts; we need to make this
		// obvious in the log so it can be corrected.
		strat, err := strategy.Get(string(sn.HostPolicy))
		if err == nil {
			logger = logger.WithField("strategy", strat.Name())
		}
		logger.Warn("No hosts available")
		return false
	}

	logger.WithField("hostid", hostID).Debug("Service instance scheduled to host")
	req := StateRequest{
		PoolID:     l.poolid,
		HostID:     hostID,
		ServiceID:  sn.ID,
		InstanceID: instanceID,
	}

	// make sure the state exists on neither the service nor the host
	DeleteState(l.conn, req)

	if err := CreateState(l.conn, req); err != nil {

		logger.WithError(err).Warn("Could not schedule service instance")
		return false
	}

	return true
}
6027
func (ms *Module) ResourceInstance(addr addrs.ResourceInstance) *ResourceInstance {
	rs := ms.Resource(addr.Resource)
	if rs == nil {
		return nil
	}
	return rs.Instance(addr.Key)
}
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
}
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)
}
323646
func (pool *LoadBalancedPool) getInstance(key []byte, maxInstances int) (
	idx int,
	instance *instancePool,
	isDown bool,
	err error) {

	pool.lock.RLock()
	defer pool.lock.RUnlock()
	if len(pool.instanceList) == 0 {
		return 0, nil, false, errors.Newf("no available instances")
	}
	now := time.Now().Unix()
	numInstancesToTry := uint64(len(pool.instanceList))

	start := 0
	// map used to implement soft swapping to avoid picking the same instance multiple times
	// when we randomly pick instances for consistent-hashing. We could have used this actually
	// for the other strategies.
	// TODO(bashar): get rid of the random shuffle for the other strategies
	var idxMap map[int]int

	if pool.strategy == LBRoundRobin &&
		pool.activeSetSize < numInstancesToTry {
		numInstancesToTry = pool.activeSetSize
	} else if pool.strategy == LBConsistentHashing {

		// we must have a key
		if len(key) == 0 {
			return 0, nil, false, errors.Newf("key was not specified for consistent-hashing")
		} else if maxInstances <= 0 {
			return 0, nil, false, errors.Newf(
				"invalid maxInstances for consistent-hashing: %v", maxInstances)
		}

		// in case we're asked to try more than the number of servers we have
		if maxInstances > int(numInstancesToTry) {
			maxInstances = int(numInstancesToTry)
		}

		// let's find the closest server to start. We don't start from 0 in that case
		hash := pool.hashFunction(key, pool.hashSeed)
		// we need to find the closest server that hashes to >= hash.
		start = sort.Search(len(pool.instanceList), func(i int) bool {
			return pool.instanceHashes[i] >= hash
		})

		// In the case where hash > all elements, sort.Search returns len(pool.instanceList).
		// Hence, we mod the result
		start = start % len(pool.instanceHashes)

		idxMap = make(map[int]int)
	}

	for i := 0; uint64(i) < numInstancesToTry; i++ {
		switch pool.strategy {
		case LBRoundRobin:
			// In RoundRobin strategy instanceIdx keeps changing, to
			// achieve round robin load balancing.
			instanceIdx := atomic.AddUint64(&pool.instanceIdx, 1)
			idx = int(instanceIdx % numInstancesToTry)
		case LBSortedFixed:
			// In SortedFixed strategy instances are always traversed in same
			// exact order.
			idx = i
		case LBShuffledFixed:
			// In ShuffledFixed strategy instances are also always traversed in
			// same exact order.
			idx = i
		case LBConsistentHashing:
			// In ConsistentHashing strategy instances are picked up randomly between
			// start and start + numInstancesToTry. This is to load balance between
			// the alive servers that are closest to the key in the hash space

			// consistent-hashing will prefer availability over consistency. In the case some
			// server is down, we will try new servers in the hash-ring. The way we do this is by
			// picking random instances next (excluding already picked instances). That's why we
			// do a 'soft-swap' between already picked instance and move the start offset by 1
			// every time. We don't touch the pool.instanceList to make sure we don't
			// screw up any order. The swap below guarantees that start always has an idx that
			// has never been tried before.
			newStart := i + start
			idx = (newStart + rand2.Intn(maxInstances)) % len(pool.instanceList)
			// we need to swap idxMap[newStart] with idxMap[idx] (or fill them).
			var ok bool
			if idxMap[idx], ok = idxMap[idx]; ok {
				idxMap[newStart] = idxMap[idx]
			} else {
				idxMap[newStart] = idx
			}
			idxMap[idx] = newStart

			// we need to pick the correct idx after the swap
			idx = idxMap[newStart]
		}

		if pool.markDownUntil[idx] < now {
			break
		}
	}
	return idx, pool.instanceList[idx], (pool.markDownUntil[idx] >= now), nil
}
254844
func (s *Store) Instances(service string) ([]*discoverd.Instance, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.instances(service), nil
}
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
}
505368
func (e *OracleEnviron) createInstance(params oci.InstanceParams) (*oracleInstance, error) {
	if len(params.Instances) > 1 {
		return nil, errors.NotSupportedf("launching multiple instances")
	}

	logger.Debugf("running createInstance")
	resp, err := e.client.CreateInstance(params)
	if err != nil {
		return nil, errors.Trace(err)
	}

	instance, err := newInstance(resp.Instances[0], e)
	if err != nil {
		return nil, errors.Trace(err)
	}

	return instance, nil
}
889420
func (r Resource) Instance(key InstanceKey) ResourceInstance {
	return ResourceInstance{
		Resource: r,
		Key:      key,
	}
}
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
}
601526
func NewInstance(cfg InstanceConfig) *TeleInstance {
	var err error
	if len(cfg.Ports) < 5 {
		fatalIf(fmt.Errorf("not enough free ports given: %v", cfg.Ports))
	}
	if cfg.NodeName == "" {
		cfg.NodeName, err = os.Hostname()
		fatalIf(err)
	}
	// generate instance secrets (keys):
	keygen, err := native.New(context.TODO(), native.PrecomputeKeys(0))
	fatalIf(err)
	if cfg.Priv == nil || cfg.Pub == nil {
		cfg.Priv, cfg.Pub, _ = keygen.GenerateKeyPair("")
	}
	rsaKey, err := ssh.ParseRawPrivateKey(cfg.Priv)
	fatalIf(err)

	tlsCAKey, tlsCACert, err := tlsca.GenerateSelfSignedCAWithPrivateKey(rsaKey.(*rsa.PrivateKey), pkix.Name{
		CommonName:   cfg.ClusterName,
		Organization: []string{cfg.ClusterName},
	}, nil, defaults.CATTL)
	fatalIf(err)

	cert, err := keygen.GenerateHostCert(services.HostCertParams{
		PrivateCASigningKey: cfg.Priv,
		PublicHostKey:       cfg.Pub,
		HostID:              cfg.HostID,
		NodeName:            cfg.NodeName,
		ClusterName:         cfg.ClusterName,
		Roles:               teleport.Roles{teleport.RoleAdmin},
		TTL:                 time.Duration(time.Hour * 24),
	})
	fatalIf(err)
	tlsCA, err := tlsca.New(tlsCACert, tlsCAKey)
	fatalIf(err)
	cryptoPubKey, err := sshutils.CryptoPublicKey(cfg.Pub)
	identity := tlsca.Identity{
		Username: fmt.Sprintf("%v.%v", cfg.HostID, cfg.ClusterName),
		Groups:   []string{string(teleport.RoleAdmin)},
	}
	clock := clockwork.NewRealClock()
	tlsCert, err := tlsCA.GenerateCertificate(tlsca.CertificateRequest{
		Clock:     clock,
		PublicKey: cryptoPubKey,
		Subject:   identity.Subject(),
		NotAfter:  clock.Now().UTC().Add(time.Hour * 24),
	})
	fatalIf(err)

	i := &TeleInstance{
		Ports:         cfg.Ports,
		Hostname:      cfg.NodeName,
		UploadEventsC: make(chan *events.UploadEvent, 100),
	}
	secrets := InstanceSecrets{
		SiteName:     cfg.ClusterName,
		PrivKey:      cfg.Priv,
		PubKey:       cfg.Pub,
		Cert:         cert,
		TLSCACert:    tlsCACert,
		TLSCert:      tlsCert,
		ListenAddr:   net.JoinHostPort(cfg.NodeName, i.GetPortReverseTunnel()),
		WebProxyAddr: net.JoinHostPort(cfg.NodeName, i.GetPortWeb()),
		Users:        make(map[string]*User),
	}
	if cfg.MultiplexProxy {
		secrets.ListenAddr = secrets.WebProxyAddr
	}
	i.Secrets = secrets
	return i
}
457630
func (zk *zkf) WaitInstance(ctx datastore.Context, svc *service.Service, instanceID int, checkInstance func(*zks.State, bool) bool, cancel <-chan struct{}) error {
	logger := plog.WithFields(log.Fields{
		"serviceid":   svc.ID,
		"servicename": svc.Name,
		"poolid":      svc.PoolID,
	})

	// get the root-based connection
	rootconn, err := getLocalConnection(ctx, "/")
	if err != nil {
		logger.WithError(err).Debug("Could not acquire root-based connection")
		return err
	}

	// do wait
	errC := make(chan error)
	stop := make(chan struct{})
	go func() {
		errC <- zks.WaitInstance(stop, rootconn, svc.PoolID, svc.ID, instanceID, checkInstance)
	}()

	select {
	case err := <-errC:
		if err != nil {
			logger.WithError(err).Debug("Could not monitor the instance in zookeeper")
			return err
		}
		return err
	case <-cancel:
		close(stop)
		return <-errC
	}
}
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
}
83582
func CreateInstance(clsid *GUID, iid *GUID) (*IUnknown, error) {
	return nil, NewError(E_NOTIMPL)
}