// RestartInstance restarts an instance of a service
16314
func (zk *zkf) RestartInstance(ctx datastore.Context, poolID, serviceID string, instanceID int) error {
	defer ctx.Metrics().Stop(ctx.Metrics().Start(fmt.Sprintf("zzk.RestartInstances")))
	logger := plog.WithFields(log.Fields{
		"poolid":     poolID,
		"serviceid":  serviceID,
		"instanceid": instanceID,
	})

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

	// get the hostid and make a state request for the service
	hostID, err := zks.GetServiceStateHostID(conn, poolID, serviceID, instanceID)
	if err != nil {
		return err
	}
	logger = logger.WithField("hostid", hostID)
	isOnline, err := zks.IsHostOnline(conn, poolID, hostID)
	if err != nil {
		logger.WithError(err).Debug("Could not check if host is online")
		return err
	}

	req := zks.StateRequest{
		PoolID:     poolID,
		HostID:     hostID,
		ServiceID:  serviceID,
		InstanceID: instanceID,
	}
	// manage the service
	if isOnline {
		if err := zks.UpdateState(conn, req, func(s *zks.State) bool {
			if s.DesiredState != service.SVCRestart {
				s.DesiredState = service.SVCRestart
				return true
			}
			return false
		}); err != nil {
			logger.WithError(err).Debug("Could not restart service instance")
			return err
		}
		logger.Debug("Set service instance to restart")
	} else {
		logger.Warning("Could not restart service instance, host is not online")
		return ErrHostOffline
	}

	return nil
}
757636
func (s *ServerImpl) Restart() error {
	if s.config.AttachPid != 0 {
		return errors.New("cannot restart process Delve did not create")
	}
	return s.s2.Restart(rpc2.RestartIn{}, nil)
}
1107479
func (client *Client) StartInstance(instanceId string) error {
	args := StartInstanceArgs{InstanceId: instanceId}
	response := StartInstanceResponse{}
	err := client.Invoke("StartInstance", &args, &response)
	return err
}
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
}
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
}
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
}
933023
func (actor Actor) RestartApplication(appGUID string) (Warnings, error) {
	_, warnings, err := actor.CloudControllerClient.UpdateApplicationRestart(appGUID)

	return Warnings(warnings), err
}
910103
func (c *Client) RestartNetwork(p *RestartNetworkParameter) (*Network, error) {
	obj, err := c.Request("restartNetwork", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Network), err
}
83582
func CreateInstance(clsid *GUID, iid *GUID) (*IUnknown, error) {
	return nil, NewError(E_NOTIMPL)
}
856038
func (p *Project) Restart(ctx context.Context, timeout int, services ...string) error {
	return p.perform(events.ProjectRestartStart, events.ProjectRestartDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) {
		wrapper.Do(wrappers, events.ServiceRestartStart, events.ServiceRestart, func(service Service) error {
			return service.Restart(ctx, timeout)
		})
	}), nil)
}
1146552
func (launcher *Launcher) Restart(args []string) {
	launcher.Mutex.Lock()
	defer launcher.Mutex.Unlock()
	launcher.args = args

	if launcher.process == nil {
		return
	}
	if err := launcher.process.Kill(); err != nil {
		log.WithError(err).WithField("pid", launcher.process.Pid).Error("process.Kill()")
	}
	launcher.process = nil
}
1017047
func (e *Environ) MaintainInstance(ctx envcontext.ProviderCallContext, args environs.StartInstanceParams) error {
	return nil
}
535515
func (d *daemon) Restart() {
	d.Lock()
	defer d.Unlock()
	if d.ex == nil {
		ex, err := shell.NewExecutor(d.shell, d.conf.Command, d.indir)
		if err != nil {
			d.log.Shout("Could not create executor: %s", err)
		}
		d.ex = ex
		go d.Run()
	} else {
		d.log.Notice(">> sending signal %s", d.conf.RestartSignal)
		err := d.ex.Signal(d.conf.RestartSignal)
		if err != nil {
			d.log.Warn(
				"failed to send %s signal to %s: %v", d.conf.RestartSignal, d.conf.Command, err,
			)
		}
	}
}
916588
func NewInstance(ts *topo.Server, cell string, commandDisplayInterval time.Duration) *Instance {
	wi := &Instance{topoServer: ts, cell: cell, commandDisplayInterval: commandDisplayInterval}
	// Note: setAndStartWorker() also adds a MemoryLogger for the webserver.
	wi.wr = wi.CreateWrangler(logutil.NewConsoleLogger())
	return wi
}
149197
func (m *ModelStatus) MachineInstance(machineID string) (status.StatusInfo, error) {
	return m.getStatus(machineGlobalInstanceKey(machineID), "instance")
}
96574
func (env *environ) StopInstances(ctx context.ProviderCallContext, instances ...instance.Id) error {
	prefix := env.namespace.Prefix()
	var names []string
	for _, id := range instances {
		name := string(id)
		if strings.HasPrefix(name, prefix) {
			names = append(names, name)
		} else {
			logger.Warningf("ignoring request to stop container %q - not in namespace %q", name, prefix)
		}
	}

	err := env.server().RemoveContainers(names)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
	}
	return errors.Trace(err)
}
22092
func (rs *Resource) Instance(key addrs.InstanceKey) *ResourceInstance {
	return rs.Instances[key]
}