// Starts an existing internal lb vm.
352245
func (s *InternalLBService) StartInternalLoadBalancerVM(p *StartInternalLoadBalancerVMParams) (*StartInternalLoadBalancerVMResponse, error) {
	resp, err := s.cs.newRequest("startInternalLoadBalancerVM", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r StartInternalLoadBalancerVMResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
264384
func (vm *VM) Start() error {

	if vm.ID == "" {
		return fmt.Errorf("Need an ID to start the virtual machine")
	}

	params := url.Values{}
	params.Set("id", vm.ID)

	client := vm.getExoClient()
	resp, err := client.Request("startVirtualMachine", params)
	if err != nil {
		return fmt.Errorf("Starting virtual machine %q: %s", vm.ID, err)
	}

	start := &egoscale.StartVirtualMachineResponse{}
	if err := json.Unmarshal(resp, start); err != nil {
		return fmt.Errorf("Starting virtual machine %q: %s", vm.ID, err)
	}

	vm.JobID = start.JobID

	return nil
}
1475
func (ncc *SeesawNCC) LBInterfaceInit(iface *ncctypes.LBInterface, out *int) error {
	netIface, err := iface.Interface()
	if err != nil {
		return fmt.Errorf("Failed to get network interface: %v", err)
	}
	nodeIface, err := net.InterfaceByName(iface.NodeInterface)
	if err != nil {
		return fmt.Errorf("Failed to get node interface: %v", err)
	}

	if iface.RoutingTableID < 1 || iface.RoutingTableID > 250 {
		return fmt.Errorf("Invalid routing table ID: %d", iface.RoutingTableID)
	}

	vmac, err := net.ParseMAC(vrrpMAC)
	if err != nil {
		return fmt.Errorf("Failed to parse VRRP MAC %q: %v", vrrpMAC, err)
	}

	// The last byte of the VRRP MAC is determined by the VRID.
	vmac[len(vmac)-1] = iface.VRID
	netIface.HardwareAddr = vmac

	log.Infof("Initialising load balancing interface %s - VRID %d (VMAC %s)", iface.Name, iface.VRID, vmac)

	// Ensure interface is down and set VMAC address.
	if err := ifaceFastDown(netIface); err != nil {
		return fmt.Errorf("Failed to down interface: %v", err)
	}
	if err := ifaceSetMAC(netIface); err != nil {
		return fmt.Errorf("Failed to set MAC: %v", err)
	}

	// Remove VLAN interfaces associated with the load balancing interface.
	if err := ifaceFlushVLANs(netIface); err != nil {
		return fmt.Errorf("Failed to flush VLAN interfaces: %v", err)
	}

	// Configure sysctls for load balancing.
	if err := sysctlInitLB(nodeIface, netIface); err != nil {
		return fmt.Errorf("Failed to initialise sysctls: %v", err)
	}

	// Flush existing IP addresses and add cluster VIPs.
	if err := ifaceFlushIPAddr(netIface); err != nil {
		return fmt.Errorf("Failed to flush IP addresses: %v", err)
	}

	if iface.ClusterVIP.IPv4Addr != nil {
		if err := addClusterVIP(iface, netIface, nodeIface, iface.ClusterVIP.IPv4Addr); err != nil {
			return fmt.Errorf("Failed to add IPv4 cluster VIP: %v", err)
		}
	}
	if iface.ClusterVIP.IPv6Addr != nil {
		if err := addClusterVIP(iface, netIface, nodeIface, iface.ClusterVIP.IPv6Addr); err != nil {
			return fmt.Errorf("Failed to add IPv6 cluster VIP: %v", err)
		}
	}

	// Initialise iptables rules.
	if err := iptablesInit(iface.ClusterVIP); err != nil {
		return err
	}

	// Setup dummy interface.
	dummyIface, err := net.InterfaceByName(iface.DummyInterface)
	if err != nil {
		return fmt.Errorf("Failed to get dummy interface: %v", err)
	}
	if err := ifaceFastDown(dummyIface); err != nil {
		return fmt.Errorf("Failed to down dummy interface: %v", err)
	}
	if err := ifaceFlushIPAddr(dummyIface); err != nil {
		return fmt.Errorf("Failed to flush dummy interface: %v", err)
	}
	if err := ifaceUp(dummyIface); err != nil {
		return fmt.Errorf("Failed to up dummy interface: %v", err)
	}

	return nil
}
812926
func (l *LightningWallet) Startup() error {
	// Already started?
	if atomic.AddInt32(&l.started, 1) != 1 {
		return nil
	}

	// Start the underlying wallet controller.
	if err := l.Start(); err != nil {
		return err
	}

	l.wg.Add(1)
	// TODO(roasbeef): multiple request handlers?
	go l.requestHandler()

	return nil
}
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
}
988717
func StartVolumePluginAPI(
	name, sdkUds string,
	pluginBase string,
	pluginPort uint16,
	authProviderType secrets.AuthTokenProviders,
	authProvider osecrets.Secrets,
) error {
	var secretsStore secrets.Auth
	var err error

	// Only initialize secrets store if we have a valid auth provider.
	if authProvider != nil && authProviderType != secrets.TypeNone {
		secretsStore, err = secrets.NewAuth(authProviderType, authProvider)
		if err != nil {
			return err
		}
	}

	volPluginApi := newVolumePlugin(name, sdkUds, secretsStore)
	if _, _, err := startServer(
		name,
		pluginBase,
		pluginPort,
		volPluginApi,
	); err != nil {
		return err
	}
	return nil
}
78519
func (e *Environ) StartInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) (_ *environs.StartInstanceResult, err error) {
	if args.AvailabilityZone != "" {
		// args.AvailabilityZone should only be set if this OpenStack
		// supports zones; validate the zone.
		volumeAttachmentsZone, err := e.volumeAttachmentsZone(args.VolumeAttachments)
		if err != nil {
			common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
			return nil, common.ZoneIndependentError(err)
		}
		if err := validateAvailabilityZoneConsistency(args.AvailabilityZone, volumeAttachmentsZone); err != nil {
			common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
			return nil, common.ZoneIndependentError(err)
		}
		if err := common.ValidateAvailabilityZone(e, ctx, args.AvailabilityZone); err != nil {
			common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
			return nil, errors.Trace(err)
		}
	}

	series := args.Tools.OneSeries()
	arches := args.Tools.Arches()
	spec, err := findInstanceSpec(e, &instances.InstanceConstraint{
		Region:      e.cloud().Region,
		Series:      series,
		Arches:      arches,
		Constraints: args.Constraints,
	}, args.ImageMetadata)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, common.ZoneIndependentError(err)
	}
	tools, err := args.Tools.Match(tools.Filter{Arch: spec.Image.Arch})
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, common.ZoneIndependentError(
			errors.Errorf("chosen architecture %v not present in %v", spec.Image.Arch, arches),
		)
	}

	if err := args.InstanceConfig.SetTools(tools); err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, common.ZoneIndependentError(err)
	}

	if err := instancecfg.FinishInstanceConfig(args.InstanceConfig, e.Config()); err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, common.ZoneIndependentError(err)
	}
	cloudcfg, err := e.configurator.GetCloudConfig(args)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, common.ZoneIndependentError(err)
	}
	userData, err := providerinit.ComposeUserData(args.InstanceConfig, cloudcfg, OpenstackRenderer{})
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, common.ZoneIndependentError(errors.Annotate(err, "cannot make user data"))
	}
	logger.Debugf("openstack user data; %d bytes", len(userData))

	networks, err := e.networking.DefaultNetworks()
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, common.ZoneIndependentError(errors.Annotate(err, "getting initial networks"))
	}
	usingNetwork := e.ecfg().network()
	networkId, err := e.networking.ResolveNetwork(usingNetwork, false)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		if usingNetwork == "" {
			// If there is no network configured, we only throw out when the
			// error reports multiple Openstack networks.
			// If there are no Openstack networks at all (such as Canonistack),
			// having no network config is not an error condition.
			if strings.HasPrefix(err.Error(), "multiple networks") {
				return nil, common.ZoneIndependentError(errors.New(noNetConfigMsg(err)))
			}
		} else {
			return nil, common.ZoneIndependentError(err)
		}
	} else {
		logger.Debugf("using network id %q", networkId)
		networks = append(networks, nova.ServerNetworks{NetworkId: networkId})
	}

	machineName := resourceName(
		e.namespace,
		e.name,
		args.InstanceConfig.MachineId,
	)

	if e.ecfg().useOpenstackGBP() {
		client := e.neutron()
		ptArg := neutron.PolicyTargetV2{
			Name:                fmt.Sprintf("juju-policytarget-%s", machineName),
			PolicyTargetGroupId: e.ecfg().policyTargetGroup(),
		}
		pt, err := client.CreatePolicyTargetV2(ptArg)
		if err != nil {
			common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
			return nil, errors.Trace(err)
		}
		networks = append(networks, nova.ServerNetworks{PortId: pt.PortId})
	}

	// For BUG 1680787: openstack: add support for neutron networks where port
	// security is disabled.
	// If any network specified for instance boot has PortSecurityEnabled equals
	// false, don't create security groups, instance boot will fail.
	createSecurityGroups := true
	if len(networks) > 0 && e.supportsNeutron() {
		client := e.neutron()
		for _, n := range networks {
			if n.NetworkId == "" {
				// It's a GBP network.
				continue
			}
			net, err := client.GetNetworkV2(n.NetworkId)
			if err != nil {
				common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
				return nil, common.ZoneIndependentError(err)
			}
			if net.PortSecurityEnabled != nil &&
				*net.PortSecurityEnabled == false {
				createSecurityGroups = *net.PortSecurityEnabled
				logger.Infof("network %q has port_security_enabled set to false. Not using security groups.", net.Id)
				break
			}
		}
	}

	var novaGroupNames = []nova.SecurityGroupName{}
	if createSecurityGroups {
		var apiPort int
		if args.InstanceConfig.Controller != nil {
			apiPort = args.InstanceConfig.Controller.Config.APIPort()
		} else {
			// All ports are the same so pick the first.
			apiPort = args.InstanceConfig.APIInfo.Ports()[0]
		}
		groupNames, err := e.firewaller.SetUpGroups(ctx, args.ControllerUUID, args.InstanceConfig.MachineId, apiPort)
		if err != nil {
			common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
			return nil, common.ZoneIndependentError(errors.Annotate(err, "cannot set up groups"))
		}
		novaGroupNames = make([]nova.SecurityGroupName, len(groupNames))
		for i, name := range groupNames {
			novaGroupNames[i].Name = name
		}
	}

	waitForActiveServerDetails := func(
		client *nova.Client,
		id string,
		timeout time.Duration,
	) (server *nova.ServerDetail, err error) {

		var errStillBuilding = errors.Errorf("instance %q has status BUILD", id)
		err = retry.Call(retry.CallArgs{
			Clock:       e.clock,
			Delay:       10 * time.Second,
			MaxDuration: timeout,
			Func: func() error {
				server, err = client.GetServer(id)
				if err != nil {
					return err
				}
				if server.Status == nova.StatusBuild {
					return errStillBuilding
				}
				return nil
			},
			NotifyFunc: func(lastError error, attempt int) {
				args.StatusCallback(status.Provisioning, fmt.Sprintf("%s, wait 10 seconds before retry, attempt %d", lastError, attempt), nil)
			},
			IsFatalError: func(err error) bool {
				return err != errStillBuilding
			},
		})
		if err != nil {
			common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
			return nil, err
		}
		return server, nil
	}

	tryStartNovaInstance := func(
		attempts utils.AttemptStrategy,
		client *nova.Client,
		instanceOpts nova.RunServerOpts,
	) (server *nova.Entity, err error) {
		for a := attempts.Start(); a.Next(); {
			server, err = client.RunServer(instanceOpts)
			if err != nil {
				common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
				break
			}
			if server == nil {
				logger.Warningf("may have lost contact with nova api while creating instances, some stray instances may be around and need to be deleted")
				break
			}
			var serverDetail *nova.ServerDetail
			serverDetail, err = waitForActiveServerDetails(client, server.Id, 5*time.Minute)
			if err != nil || serverDetail == nil {
				server = nil
				break
			} else if serverDetail.Status == nova.StatusActive {
				break
			} else if serverDetail.Status == nova.StatusError {
				// Perhaps there is an error case where a retry in the same AZ
				// is a good idea.
				faultMsg := " unable to determine fault details"
				if serverDetail.Fault != nil {
					faultMsg = fmt.Sprintf(" with fault %q", serverDetail.Fault.Message)
				} else {
					logger.Debugf("getting active server details from nova failed without fault details")
				}
				logger.Infof("Deleting instance %q in ERROR state%v", server.Id, faultMsg)
				if err = e.terminateInstances(ctx, []instance.Id{instance.Id(server.Id)}); err != nil {
					logger.Debugf("Failed to delete instance in ERROR state, %q", err)
				}
				server = nil
				err = errors.New(faultMsg)
				break
			}
		}
		return server, err
	}

	var opts = nova.RunServerOpts{
		Name:               machineName,
		FlavorId:           spec.InstanceType.Id,
		ImageId:            spec.Image.Id,
		UserData:           userData,
		SecurityGroupNames: novaGroupNames,
		Networks:           networks,
		Metadata:           args.InstanceConfig.Tags,
		AvailabilityZone:   args.AvailabilityZone,
	}
	e.configurator.ModifyRunServerOptions(&opts)

	server, err := tryStartNovaInstance(shortAttempt, e.nova(), opts)
	if err != nil || server == nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		// 'No valid host available' is typically a resource error,
		// let the provisioner know it is a good idea to try another
		// AZ if available.
		err := errors.Annotate(err, "cannot run instance")
		zoneSpecific := isNoValidHostsError(err)
		if !zoneSpecific {
			err = common.ZoneIndependentError(err)
		}
		return nil, err
	}

	detail, err := e.nova().GetServer(server.Id)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, common.ZoneIndependentError(errors.Annotate(err, "cannot get started instance"))
	}

	inst := &openstackInstance{
		e:            e,
		serverDetail: detail,
		arch:         &spec.Image.Arch,
		instType:     &spec.InstanceType,
	}
	logger.Infof("started instance %q", inst.Id())
	withPublicIP := e.ecfg().useFloatingIP()
	if withPublicIP {
		// If we don't lock here, AllocatePublicIP() can return the same
		// public IP for 2 different instances.  Only one will successfully
		// be assigned the public IP, the other will not have one.
		e.publicIPMutex.Lock()
		defer e.publicIPMutex.Unlock()
		var publicIP *string
		logger.Debugf("allocating public IP address for openstack node")
		if fip, err := e.networking.AllocatePublicIP(inst.Id()); err != nil {
			common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
			return nil, common.ZoneIndependentError(errors.Annotate(err, "cannot allocate a public IP as needed"))
		} else {
			publicIP = fip
			logger.Infof("allocated public IP %s", *publicIP)
		}
		if err := e.assignPublicIP(publicIP, string(inst.Id())); err != nil {
			if err := e.terminateInstances(ctx, []instance.Id{inst.Id()}); err != nil {
				common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
				// ignore the failure at this stage, just log it
				logger.Debugf("failed to terminate instance %q: %v", inst.Id(), err)
			}
			return nil, common.ZoneIndependentError(errors.Annotatef(err,
				"cannot assign public address %s to instance %q",
				*publicIP, inst.Id(),
			))
		}
		inst.floatingIP = publicIP
	}

	return &environs.StartInstanceResult{
		Instance: inst,
		Hardware: inst.hardwareCharacteristics(),
	}, nil
}
120719
func Start(cmd string, conf *localconfig.TopLevel) {
	bootstrapBlock := extractBootstrapBlock(conf)
	if err := ValidateBootstrapBlock(bootstrapBlock); err != nil {
		logger.Panicf("Failed validating bootstrap block: %v", err)
	}

	clusterType := isClusterType(bootstrapBlock)
	signer := localmsp.NewSigner()

	lf, _ := createLedgerFactory(conf)

	clusterDialer := &cluster.PredicateDialer{}
	clusterClientConfig := initializeClusterClientConfig(conf, clusterType, bootstrapBlock)
	clusterDialer.SetConfig(clusterClientConfig)

	r := createReplicator(lf, bootstrapBlock, conf, clusterClientConfig.SecOpts, signer)
	// Only clusters that are equipped with a recent config block can replicate.
	if clusterType && conf.General.GenesisMethod == "file" {
		r.replicateIfNeeded(bootstrapBlock)
	}

	opsSystem := newOperationsSystem(conf.Operations, conf.Metrics)
	err := opsSystem.Start()
	if err != nil {
		logger.Panicf("failed to initialize operations subsystem: %s", err)
	}
	defer opsSystem.Stop()
	metricsProvider := opsSystem.Provider
	logObserver := floggingmetrics.NewObserver(metricsProvider)
	flogging.Global.SetObserver(logObserver)

	serverConfig := initializeServerConfig(conf, metricsProvider)
	grpcServer := initializeGrpcServer(conf, serverConfig)
	caSupport := &comm.CASupport{
		AppRootCAsByChain:     make(map[string][][]byte),
		OrdererRootCAsByChain: make(map[string][][]byte),
		ClientRootCAs:         serverConfig.SecOpts.ClientRootCAs,
	}

	clusterServerConfig := serverConfig
	clusterGRPCServer := grpcServer
	if clusterType {
		clusterServerConfig, clusterGRPCServer = configureClusterListener(conf, serverConfig, grpcServer, ioutil.ReadFile)
	}

	var servers = []*comm.GRPCServer{grpcServer}
	// If we have a separate gRPC server for the cluster, we need to update its TLS
	// CA certificate pool too.
	if clusterGRPCServer != grpcServer {
		servers = append(servers, clusterGRPCServer)
	}

	tlsCallback := func(bundle *channelconfig.Bundle) {
		// only need to do this if mutual TLS is required or if the orderer node is part of a cluster
		if grpcServer.MutualTLSRequired() || clusterType {
			logger.Debug("Executing callback to update root CAs")
			updateTrustedRoots(caSupport, bundle, servers...)
			if clusterType {
				updateClusterDialer(caSupport, clusterDialer, clusterClientConfig.SecOpts.ServerRootCAs)
			}
		}
	}

	manager := initializeMultichannelRegistrar(bootstrapBlock, r, clusterDialer, clusterServerConfig, clusterGRPCServer, conf, signer, metricsProvider, opsSystem, lf, tlsCallback)
	mutualTLS := serverConfig.SecOpts.UseTLS && serverConfig.SecOpts.RequireClientCert
	server := NewServer(manager, metricsProvider, &conf.Debug, conf.General.Authentication.TimeWindow, mutualTLS)

	logger.Infof("Starting %s", metadata.GetVersionInfo())
	go handleSignals(addPlatformSignals(map[os.Signal]func(){
		syscall.SIGTERM: func() {
			grpcServer.Stop()
			if clusterGRPCServer != grpcServer {
				clusterGRPCServer.Stop()
			}
		},
	}))

	if clusterGRPCServer != grpcServer {
		logger.Info("Starting cluster listener on", clusterGRPCServer.Address())
		go clusterGRPCServer.Start()
	}

	initializeProfilingService(conf)
	ab.RegisterAtomicBroadcastServer(grpcServer.Server(), server)
	logger.Info("Beginning to serve requests")
	grpcServer.Start()
}
654072
func (s *SystemVMService) NewStartSystemVmParams(id string) *StartSystemVmParams {
	p := &StartSystemVmParams{}
	p.p = make(map[string]interface{})
	p.p["id"] = id
	return p
}
255628
func (vm *InprocVM) Start(ccid ccintf.CCID, args []string, env []string, filesToUpload map[string][]byte, builder container.Builder) error {
	path := ccid.GetName()

	ipctemplate := vm.registry.getType(path)
	if ipctemplate == nil {
		return fmt.Errorf(fmt.Sprintf("%s not registered", path))
	}

	instName := vm.GetVMName(ccid)

	ipc, err := vm.getInstance(ipctemplate, instName, args, env)

	if err != nil {
		return fmt.Errorf(fmt.Sprintf("could not create instance for %s", instName))
	}

	if ipc.running {
		return fmt.Errorf(fmt.Sprintf("chaincode running %s", path))
	}

	ipc.running = true

	go func() {
		defer func() {
			if r := recover(); r != nil {
				inprocLogger.Criticalf("caught panic from chaincode  %s", instName)
			}
		}()
		ipc.launchInProc(instName, args, env)
	}()

	return nil
}
712511
func Start(options StartOptions, kbCtx libkbfs.Context) *libfs.Error {
	// Hook simplefs implementation in.
	createSimpleFS := func(
		libkbfsCtx libkbfs.Context, config libkbfs.Config) (rpc.Protocol, error) {
		return keybase1.SimpleFSProtocol(
			simplefs.NewSimpleFS(libkbfsCtx, config)), nil
	}
	// Hook git implementation in.
	shutdownGit := func() {}
	createGitHandler := func(
		libkbfsCtx libkbfs.Context, config libkbfs.Config) (rpc.Protocol, error) {
		var handler keybase1.KBFSGitInterface
		handler, shutdownGit = libgit.NewRPCHandlerWithCtx(
			libkbfsCtx, config, &options.KbfsParams)
		return keybase1.KBFSGitProtocol(handler), nil
	}
	defer func() {
		shutdownGit()
	}()

	// Patch the kbfsParams to inject two additional protocols.
	options.KbfsParams.AdditionalProtocolCreators = []libkbfs.AdditionalProtocolCreator{
		createSimpleFS, createGitHandler,
	}

	log, err := libkbfs.InitLog(options.KbfsParams, kbCtx)
	if err != nil {
		return libfs.InitError(err.Error())
	}

	mi := libfs.NewMountInterrupter(log)
	ctx := context.Background()
	config, err := libkbfs.Init(
		ctx, kbCtx, options.KbfsParams, nil, mi.Done, log)
	if err != nil {
		return libfs.InitError(err.Error())
	}

	defer libkbfs.Shutdown()

	libfs.AddRootWrapper(config)

	if options.RuntimeDir != "" {
		err := os.MkdirAll(options.RuntimeDir, libkb.PermDir)
		if err != nil {
			return libfs.InitError(err.Error())
		}
		info := libkb.NewServiceInfo(libkb.Version, libkbfs.PrereleaseBuild, options.Label, os.Getpid())
		err = info.WriteFile(path.Join(options.RuntimeDir, "kbfs.info"), log)
		if err != nil {
			return libfs.InitError(err.Error())
		}
	}

	if options.KbfsParams.Debug {
		// Turn on debugging.  TODO: allow a proper log file and
		// style to be specified.
		log.Configure("", true, "")
	}

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	if options.MountPoint == "" {
		// The mounter will detect this case and pick up the path from DokanConfig
		options.MountPoint, err = config.KeybaseService().EstablishMountDir(ctx)
		if err != nil {
			return libfs.InitError(err.Error())
		}
		log.CInfof(ctx, "Got mount dir from service: -%s-", options.MountPoint)
	}
	options.DokanConfig.Path = options.MountPoint

	if !options.SkipMount && !strings.EqualFold(options.MountPoint, "none") {

		fs, err := NewFS(ctx, config, log)
		if err != nil {
			return libfs.InitError(err.Error())
		}
		options.DokanConfig.FileSystem = fs

		if newFolderNameErr != nil {
			log.CWarningf(ctx, "Error guessing new folder name: %v", newFolderNameErr)
		}
		log.CDebugf(ctx, "New folder name guess: %q %q", newFolderName, newFolderAltName)

		st, err := os.Lstat(options.MountPoint)
		log.CDebugf(ctx, "Before mount check (should fail) Lstat(%q): %v,%v", options.MountPoint, st, err)

		err = startMounting(options, log, mi)
		if err != nil {
			logDokanInfo(ctx, log)
			// Abort on error if we were force mounting, otherwise continue.
			if options.ForceMount {
				// Cleanup when exiting in case the mount got dirty.
				mi.Done()
				return libfs.MountError(err.Error())
			}
			log.CErrorf(ctx, "Running KBFS without a filesystem mount due to: %v", err)
		}
	}

	log.CDebugf(ctx, "Entering mount wait")
	mi.Wait()
	log.CDebugf(ctx, "Filesystem unmounted - mount wait returned - exiting")
	return nil
}
54595
func (driver *MesosSchedulerDriver) Start() (mesos.Status, error) {
	driver.eventLock.Lock()
	defer driver.eventLock.Unlock()
	return driver.start()
}
371244
func (computeSystem *System) Start() (err error) {
	computeSystem.handleLock.RLock()
	defer computeSystem.handleLock.RUnlock()

	operation := "hcsshim::ComputeSystem::Start"
	computeSystem.logOperationBegin(operation)
	defer func() { computeSystem.logOperationEnd(operation, err) }()

	if computeSystem.handle == 0 {
		return makeSystemError(computeSystem, "Start", "", ErrAlreadyClosed, nil)
	}

	// This is a very simple backoff-retry loop to limit the number
	// of parallel container starts if environment variable
	// HCSSHIM_MAX_PARALLEL_START is set to a positive integer.
	// It should generally only be used as a workaround to various
	// platform issues that exist between RS1 and RS4 as of Aug 2018
	if currentContainerStarts.maxParallel > 0 {
		for {
			currentContainerStarts.Lock()
			if currentContainerStarts.inProgress < currentContainerStarts.maxParallel {
				currentContainerStarts.inProgress++
				currentContainerStarts.Unlock()
				break
			}
			if currentContainerStarts.inProgress == currentContainerStarts.maxParallel {
				currentContainerStarts.Unlock()
				time.Sleep(100 * time.Millisecond)
			}
		}
		// Make sure we decrement the count when we are done.
		defer func() {
			currentContainerStarts.Lock()
			currentContainerStarts.inProgress--
			currentContainerStarts.Unlock()
		}()
	}

	var resultp *uint16
	syscallWatcher(computeSystem.logctx, func() {
		err = hcsStartComputeSystem(computeSystem.handle, "", &resultp)
	})
	events, err := processAsyncHcsResult(err, resultp, computeSystem.callbackNumber, hcsNotificationSystemStartCompleted, &timeout.SystemStart)
	if err != nil {
		return makeSystemError(computeSystem, "Start", "", err, events)
	}

	return nil
}
1073323
func (c *ClusterManager) Start(
	clusterMaxSize int,
	nodeInitialized bool,
	gossipPort string,
	selfClusterDomain string,
) error {
	return c.StartWithConfiguration(
		clusterMaxSize,
		nodeInitialized,
		gossipPort,
		[]string{ClusterDBKey},
		selfClusterDomain,
		&cluster.ClusterServerConfiguration{})
}
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
}
1206772
func (vm *VM) Start() error {
	_, err := runner.RunCombinedError("startvm", vm.Name)
	if err != nil {
		// If the user has paused the VM it reads as halted but the Start
		// command will fail. Try to resume it as a backup.
		_, rerr := runner.RunCombinedError("controlvm", vm.Name, "resume")
		if rerr != nil {
			// If neither succeeds, return both errors.
			return lvm.WrapErrors(lvm.ErrStartingVM, err, rerr)
		}
	}
	return nil
}
1090779
func (bstar *Bstar) Start() error {
	if bstar.voter_fn == nil {
		panic("Missing voter function")
	}
	bstar.update_peer_expiry()
	return bstar.Reactor.Run(bstar_HEARTBEAT / 5)
}