//stopInstance stops the CloudSigma server corresponding to the given instance ID.
341635
func (c *environClient) stopInstance(id instance.Id) error {
	uuid := string(id)
	if uuid == "" {
		return errors.New("invalid instance id")
	}

	s, err := c.conn.Server(uuid)
	if err != nil {
		return errors.Trace(err)
	}

	err = s.StopWait()
	logger.Tracef("environClient.StopInstance - stop server, %q = %v", uuid, err)

	err = s.Remove(gosigma.RecurseAllDrives)
	logger.Tracef("environClient.StopInstance - remove server, %q = %v", uuid, err)

	return nil
}
631011
func (m *Machine) KeepInstance() (bool, error) {
	instData, err := getInstanceData(m.st, m.Id())
	if err != nil {
		return false, err
	}
	return instData.KeepInstance, nil
}
1233967
func (c *Cluster) StopContainer(id string, timeout uint) error {
	node, err := c.getNodeForContainer(id)
	if err != nil {
		return err
	}
	return wrapError(node, node.StopContainer(id, timeout))
}
975984
func (c *Cloud) getInstanceByID(instanceID string) (*ec2.Instance, error) {
	instances, err := c.getInstancesByIDs([]*string{&instanceID})
	if err != nil {
		return nil, err
	}

	if len(instances) == 0 {
		return nil, cloudprovider.ErrInstanceNotFound
	}
	if len(instances) > 1 {
		return nil, fmt.Errorf("multiple instances found for instance: %s", instanceID)
	}

	return instances[instanceID], nil
}
182331
func (svc *googleService) stop() error {
	_, err := svc.getInstance()
	if err != nil {
		if !strings.Contains(err.Error(), "no instance found") {
			return err
		}
		return fmt.Errorf("no instance found, %v", err)
	}

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

	return svc.waitForOperationReady(op.Name)
}
443647
func (i *Instance) Stop() error {
	// stop the servers
	for _, s := range i.servers {
		if gs, ok := s.server.(GracefulServer); ok {
			if err := gs.Stop(); err != nil {
				log.Printf("[ERROR] Stopping %s: %v", gs.Address(), err)
			}
		}
	}

	// splice i out of instance list, causing it to be garbage-collected
	instancesMu.Lock()
	for j, other := range instances {
		if other == i {
			instances = append(instances[:j], instances[j+1:]...)
			break
		}
	}
	instancesMu.Unlock()

	return nil
}
130765
func (p *Provider) Stop() error {
	p.stopOnce.Do(p.stopInit)

	p.stopMu.Lock()
	defer p.stopMu.Unlock()

	p.stopCtxCancel()
	return 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
}
350681
func shutdownInCloudProvider(ctx context.Context, cloud cloudprovider.Interface, node *v1.Node) (bool, error) {
	instances, ok := cloud.Instances()
	if !ok {
		return false, errors.New("cloud provider does not support instances")
	}

	shutdown, err := instances.InstanceShutdownByProviderID(ctx, node.Spec.ProviderID)
	if err == cloudprovider.NotImplemented {
		return false, nil
	}

	return shutdown, err
}
787669
func (b *backend) validateInstance(ctx context.Context, s logical.Storage, instanceID, region, accountID string) (*ec2.Instance, error) {
	// Create an EC2 client to pull the instance information
	ec2Client, err := b.clientEC2(ctx, s, region, accountID)
	if err != nil {
		return nil, err
	}

	status, err := ec2Client.DescribeInstances(&ec2.DescribeInstancesInput{
		InstanceIds: []*string{
			aws.String(instanceID),
		},
	})
	if err != nil {
		errW := errwrap.Wrapf(fmt.Sprintf("error fetching description for instance ID %q: {{err}}", instanceID), err)
		return nil, errwrap.Wrap(errW, awsutil.CheckAWSError(err))
	}
	if status == nil {
		return nil, fmt.Errorf("nil output from describe instances")
	}
	if len(status.Reservations) == 0 {
		return nil, fmt.Errorf("no reservations found in instance description")

	}
	if len(status.Reservations[0].Instances) == 0 {
		return nil, fmt.Errorf("no instance details found in reservations")
	}
	if *status.Reservations[0].Instances[0].InstanceId != instanceID {
		return nil, fmt.Errorf("expected instance ID not matching the instance ID in the instance description")
	}
	if status.Reservations[0].Instances[0].State == nil {
		return nil, fmt.Errorf("instance state in instance description is nil")
	}
	if *status.Reservations[0].Instances[0].State.Name != "running" {
		return nil, fmt.Errorf("instance is not in 'running' state")
	}
	return status.Reservations[0].Instances[0], nil
}
1253689
func DeleteInstance(cloud fi.Cloud, t *resources.Resource) error {
	c := cloud.(awsup.AWSCloud)

	id := t.ID
	glog.V(2).Infof("Deleting EC2 instance %q", id)
	request := &ec2.TerminateInstancesInput{
		InstanceIds: []*string{&id},
	}
	_, err := c.EC2().TerminateInstances(request)
	if err != nil {
		if awsup.AWSErrorCode(err) == "InvalidInstanceID.NotFound" {
			glog.V(2).Infof("Got InvalidInstanceID.NotFound error deleting instance %q; will treat as already-deleted", id)
		} else {
			return fmt.Errorf("error deleting Instance %q: %v", id, err)
		}
	}
	return nil
}
1107022
func (c *Client) StopContainer(id string, timeout uint) error {
	return c.stopContainer(id, timeout, doOptions{})
}
197692
func (gce *Connection) removeInstance(id, zone string) error {
	err := gce.raw.RemoveInstance(gce.projectID, zone, id)
	if err != nil {
		// TODO(ericsnow) Try removing the firewall anyway?
		return errors.Trace(err)
	}

	fwname := id
	err = gce.raw.RemoveFirewall(gce.projectID, fwname)
	if errors.IsNotFound(err) {
		return nil
	}
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}
1291642
func (d *driverMock) TerminateInstance(ctx context.Context, id string) error {
	if d.TerminateInstanceErr != nil {
		return d.TerminateInstanceErr
	}

	d.TerminateInstanceID = id

	return nil
}
245095
func (s *ServerImpl) Stop() error {
	if s.config.AcceptMulti {
		close(s.stopChan)
		s.listener.Close()
	}
	kill := s.config.AttachPid == 0
	return s.debugger.Detach(kill)
}
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
}
455034
func (d *DeleteInstanceGroup) DeleteInstanceGroup(group *api.InstanceGroup) error {

	groups, err := d.Cloud.GetCloudGroups(d.Cluster, []*api.InstanceGroup{group}, false, nil)
	if err != nil {
		return fmt.Errorf("error finding CloudInstanceGroups: %v", err)
	}

	for _, g := range groups {
		if g.InstanceGroup == nil || g.InstanceGroup.Name != group.Name {
			return fmt.Errorf("found group with unexpected name: %v", g)
		}
	}

	// TODO should we drain nodes and validate the cluster?
	for _, g := range groups {
		glog.Infof("Deleting %q", group.ObjectMeta.Name)

		err = d.Cloud.DeleteGroup(g)
		if err != nil {
			return fmt.Errorf("error deleting cloud resources for InstanceGroup: %v", err)
		}
	}

	err = d.Clientset.InstanceGroupsFor(d.Cluster).Delete(group.ObjectMeta.Name, nil)
	if err != nil {
		return err
	}

	return nil
}