// start makes a *State functional post-creation, by:
//   * setting controllerTag, cloudName and leaseStoreId
//   * starting lease managers and watcher backends
//   * creating cloud metadata storage
//
// start will close the *State if it fails.
438291
func (st *State) start(controllerTag names.ControllerTag, hub *pubsub.SimpleHub) (err error) {
	defer func() {
		if err == nil {
			return
		}
		if err2 := st.Close(); err2 != nil {
			logger.Errorf("closing State for %s: %v", st.modelTag, err2)
		}
	}()

	st.controllerTag = controllerTag

	// Run the "connectionStatus" Mongo command to obtain the authenticated
	// user name, if any. This is used below for the lease store ID.
	// See: https://docs.mongodb.com/manual/reference/command/connectionStatus/
	//
	// TODO(axw) when we move the workers to a higher level state.Manager
	// type, we should pass in a tag that identifies the agent running the
	// worker. That can then be used to identify the lease manager.
	var connectionStatus struct {
		AuthInfo struct {
			AuthenticatedUsers []struct {
				User string `bson:"user"`
			} `bson:"authenticatedUsers"`
		} `bson:"authInfo"`
	}
	if err := st.session.DB(jujuDB).Run(bson.D{{"connectionStatus", 1}}, &connectionStatus); err != nil {
		return errors.Annotate(err, "obtaining connection status")
	}

	if len(connectionStatus.AuthInfo.AuthenticatedUsers) == 1 {
		st.leaseStoreId = connectionStatus.AuthInfo.AuthenticatedUsers[0].User
	} else {
		// If we're running state anonymously, we can still use the lease
		// manager; but we need to make sure we use a unique store ID, and
		// will thus not be very performant.
		logger.Infof("running state anonymously; using unique store id")
		uuid, err := utils.NewUUID()
		if err != nil {
			return errors.Trace(err)
		}
		st.leaseStoreId = fmt.Sprintf("anon-%s", uuid.String())
	}
	// now we've set up leaseStoreId, we can use workersFactory

	logger.Infof("starting standard state workers")
	workers, err := newWorkers(st, hub)
	if err != nil {
		return errors.Trace(err)
	}
	st.workers = workers

	logger.Infof("creating cloud image metadata storage")
	st.CloudImageMetadataStorage = cloudimagemetadata.NewStorage(
		cloudimagemetadataC,
		&environMongo{st},
	)

	logger.Infof("started state for %s successfully", st.modelTag)
	return nil
}
157642
func (o *Once) Start(f func() error) error {
	if o.state.CAS(int32(Idle), int32(Starting)) {
		var err error
		if f != nil {
			err = f()
		}

		// skip forward to error state
		if err != nil {
			o.setError(err)
			o.state.Store(int32(Errored))
			close(o.stoppingCh)
			close(o.stopCh)
		} else {
			o.state.Store(int32(Running))
		}
		close(o.startCh)

		return err
	}

	<-o.startCh
	return o.loadError()
}
372084
func (s *server) Start() error {
	var startErr error
	s.start.Do(func() {
		if s.torController != nil {
			if err := s.initTorController(); err != nil {
				startErr = err
				return
			}
		}

		if s.natTraversal != nil {
			s.wg.Add(1)
			go s.watchExternalIP()
		}

		// Start the notification server. This is used so channel
		// management goroutines can be notified when a funding
		// transaction reaches a sufficient number of confirmations, or
		// when the input for the funding transaction is spent in an
		// attempt at an uncooperative close by the counterparty.
		if err := s.sigPool.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.writePool.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.readPool.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.cc.chainNotifier.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.channelNotifier.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.sphinx.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.htlcSwitch.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.sweeper.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.utxoNursery.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.chainArb.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.breachArbiter.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.authGossiper.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.chanRouter.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.fundingMgr.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.invoices.Start(); err != nil {
			startErr = err
			return
		}
		if err := s.chanStatusMgr.Start(); err != nil {
			startErr = err
			return
		}

		// Before we start the connMgr, we'll check to see if we have
		// any backups to recover. We do this now as we want to ensure
		// that have all the information we need to handle channel
		// recovery _before_ we even accept connections from any peers.
		chanRestorer := &chanDBRestorer{
			db:         s.chanDB,
			secretKeys: s.cc.keyRing,
			chainArb:   s.chainArb,
		}
		if len(s.chansToRestore.PackedSingleChanBackups) != 0 {
			err := chanbackup.UnpackAndRecoverSingles(
				s.chansToRestore.PackedSingleChanBackups,
				s.cc.keyRing, chanRestorer, s,
			)
			if err != nil {
				startErr = fmt.Errorf("unable to unpack single "+
					"backups: %v", err)
				return
			}
		}
		if len(s.chansToRestore.PackedMultiChanBackup) != 0 {
			err := chanbackup.UnpackAndRecoverMulti(
				s.chansToRestore.PackedMultiChanBackup,
				s.cc.keyRing, chanRestorer, s,
			)
			if err != nil {
				startErr = fmt.Errorf("unable to unpack chan "+
					"backup: %v", err)
				return
			}
		}

		if err := s.chanSubSwapper.Start(); err != nil {
			startErr = err
			return
		}

		s.connMgr.Start()

		// With all the relevant sub-systems started, we'll now attempt
		// to establish persistent connections to our direct channel
		// collaborators within the network. Before doing so however,
		// we'll prune our set of link nodes found within the database
		// to ensure we don't reconnect to any nodes we no longer have
		// open channels with.
		if err := s.chanDB.PruneLinkNodes(); err != nil {
			startErr = err
			return
		}
		if err := s.establishPersistentConnections(); err != nil {
			startErr = err
			return
		}

		// If network bootstrapping hasn't been disabled, then we'll
		// configure the set of active bootstrappers, and launch a
		// dedicated goroutine to maintain a set of persistent
		// connections.
		if !cfg.NoNetBootstrap && !(cfg.Bitcoin.SimNet || cfg.Litecoin.SimNet) &&
			!(cfg.Bitcoin.RegTest || cfg.Litecoin.RegTest) {

			bootstrappers, err := initNetworkBootstrappers(s)
			if err != nil {
				startErr = err
				return
			}

			s.wg.Add(1)
			go s.peerBootstrapper(defaultMinPeers, bootstrappers)
		} else {
			srvrLog.Infof("Auto peer bootstrapping is disabled")
		}

		// Set the active flag now that we've completed the full
		// startup.
		atomic.StoreInt32(&s.active, 1)
	})

	return startErr
}
82327
func (s *Stater) Start(ctx context.Context) {
	// Make sure the stater can only be started once
	s.oStart.Do(func() {
		// Check context
		if ctx.Err() != nil {
			return
		}

		// Reset context
		s.ctx, s.cancel = context.WithCancel(ctx)

		// Reset once
		s.oStop = &sync.Once{}

		// Start stats
		for _, v := range s.ss {
			v.h.Start()
		}

		// Execute the rest in a go routine
		go func() {
			// Create ticker
			t := time.NewTicker(s.period)
			defer t.Stop()

			// Loop
			lastStatAt := time.Now()
			for {
				select {
				case <-t.C:
					// Get delta
					now := time.Now()
					delta := now.Sub(lastStatAt)
					lastStatAt = now

					// Loop through stats
					var stats []Stat
					for _, v := range s.ss {
						stats = append(stats, Stat{
							StatMetadata: v.m,
							Value:        v.h.Value(delta),
						})
					}

					// Handle stats
					go s.fn(stats)
				case <-s.ctx.Done():
					// Stop stats
					for _, v := range s.ss {
						v.h.Stop()
					}
					return
				}
			}
		}()
	})
}
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
}
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
}
667001
func (s *Service) Start(config *Config) {
	if config == nil {
		panic("no config specified")
	}

	s.mutex.Lock()
	defer s.mutex.Unlock()

	// return if already started
	if atomic.LoadUint32(&s.state) == serviceStarted {
		return
	}

	// set state
	atomic.StoreUint32(&s.state, serviceStarted)

	// save config
	s.config = config

	// initialize backoff
	s.backoff = &backoff.Backoff{
		Min:    s.MinReconnectDelay,
		Max:    s.MaxReconnectDelay,
		Factor: 2,
	}

	// mark future store as protected
	s.futureStore.Protect(true)

	// create new tomb
	s.tomb = new(tomb.Tomb)

	// start supervisor
	s.tomb.Go(s.supervisor)
}
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{})
}
246582
func Start() {
	connect()
	go startBatcher(commonBatchStream)

	for i := range registry {
		debug("starting", registry[i])
		go registry[i].StartLoop()
	}
}
1235282
func Start(plgn Plugin) {
	gob.Register(plgn)
	RegisterPlugin(plgn.GetMeta().Name, plgn)

	if len(os.Args) == 2 && os.Args[1] == PluginMeta {
		b, _ := json.Marshal(plgn.GetMeta())
		UIOutput(string(b))

	} else {

		plugin.Serve(&plugin.ServeConfig{
			HandshakeConfig: handshakeConfig,
			Plugins:         GetPlugins(),
		})
	}
}
1264002
func (c *FleetClient) Start(targets []string, wg *sync.WaitGroup, out, ew io.Writer) {
	// expand @* targets
	expandedTargets, err := c.expandTargets(targets)
	if err != nil {
		io.WriteString(ew, err.Error())
		return
	}

	for _, target := range expandedTargets {
		wg.Add(1)
		go doStart(c, target, wg, out, ew)
	}
	return
}
1136788
func (ed *Dispatcher) Start() error {
	if !ed.setState(dispatcherStateInitial, dispatcherStateStarted) {
		return errors.New("cannot start dispatcher since it's not in its initial state")
	}

	ed.RegisterHandlers()

	if err := ed.initRegistrations(); err != nil {
		return errors.WithMessage(err, "error initializing registrations")
	}

	if ed.initialLastBlockNum > 0 {
		if err := ed.updateLastBlockNum(ed.initialLastBlockNum); err != nil {
			logger.Warnf("Unable to update last block num to %d: %s", ed.initialLastBlockNum, err)
		}
	}

	go func() {
		for {
			if ed.getState() == dispatcherStateStopped {
				break
			}

			logger.Debug("Listening for events...")
			e, ok := <-ed.eventch
			if !ok {
				break
			}

			logger.Debugf("Received event: %+v", reflect.TypeOf(e))

			if handler, ok := ed.handlers[reflect.TypeOf(e)]; ok {
				logger.Debugf("Dispatching event: %+v", reflect.TypeOf(e))
				handler(e)
			} else {
				logger.Errorf("Handler not found for: %s", reflect.TypeOf(e))
			}
		}
		logger.Debug("Exiting event dispatcher")
	}()
	return nil
}
328483
func (c *Client) Start() error {
	if err := c.Listen(); err != nil {
		return err
	}
	return c.Serve()
}
953174
func (s *service) Start(ctx context.Context, r *taskAPI.StartRequest) (*taskAPI.StartResponse, error) {
	log.G(ctx).Debugf("Start: %s: %s", r.ID, r.ExecID)
	var p *process
	var err error
	if p, err = s.getProcess(r.ID, r.ExecID); err != nil {
		return nil, err
	}
	p.Lock()
	defer p.Unlock()

	if p.started {
		return nil, errors.New("cannot start already started container or process")
	}

	rhcs := s.newRunhcs()

	// This is a start/exec
	if r.ExecID != "" {
		execFmt := fmt.Sprintf("exec-%s-%s", r.ID, r.ExecID)
		pidfilePath := path.Join(p.bundle, fmt.Sprintf("runhcs-%s-pidfile.pid", execFmt))
		procConfig := path.Join(p.bundle, execFmt+"config.json")
		eopts := &runhcs.ExecOpts{
			IO:      p.relay.io,
			PidFile: pidfilePath,
			Detach:  true,
		}

		if rhcs.Debug {
			if s.shimOpts.DebugType == options.Options_FILE {
				eopts.ShimLog = filepath.Join(p.bundle, fmt.Sprintf("runhcs-shim-%s.log", execFmt))
			} else {
				doForwardLogs := func(source, pipeName string, opt *string) error {
					*opt = safePipePrefix + pipeName
					l, err := winio.ListenPipe(*opt, nil)
					if err != nil {
						return err
					}
					go func() {
						defer l.Close()
						c, err := l.Accept()
						if err != nil {
							log.G(ctx).
								WithField("task-id", r.ID).
								WithField("exec-id", r.ExecID).
								WithError(err).
								Errorf("failed to accept %s", pipeName)
						} else {
							fields := map[string]interface{}{
								"log-source": source,
								"task-id":    r.ID,
								"exec-id":    r.ExecID,
							}
							go forwardRunhcsLogs(ctx, c, fields)
						}
					}()
					return nil
				}

				err = doForwardLogs("runhcs-shim-exec", "runhcs-shim-log-"+execFmt, &eopts.ShimLog)
				if err != nil {
					return nil, err
				}
			}
		}

		// For the exec case increment the startedWg to make sure we publish the
		// started event previous to the exit published in `waitForProcess`.
		p.startedWg.Add(1)
		defer func() {
			if err != nil {
				// If an exec failure takes place decrement the startedWg so we
				// dont get off on counts.
				p.startedWg.Done()
			}
		}()

		// ID here is the containerID to exec the process in.
		err = rhcs.Exec(ctx, r.ID, procConfig, eopts)
		if err != nil {
			return nil, errors.Wrapf(err, "failed to exec process: %s", r.ExecID)
		}

		p.started = true

		// We successfully exec'd the process. Convert from initpid to the container process.
		pid, err := runc.ReadPidFile(pidfilePath)
		if err != nil {
			return nil, errors.Wrap(err, "failed to read container pid from pidfile")
		}

		proc, err := os.FindProcess(pid)
		if err != nil {
			return nil, errors.Wrap(err, "failed to find exec process pid")
		}
		go waitForProcess(ctx, p, proc, s)
	} else {
		if err := rhcs.Start(ctx, p.id); err != nil {
			return nil, errors.Wrapf(err, "failed to start container: %s", p.id)
		}

		p.started = true

		// TODO: JTERRY75 - This is a total hack. We cant return from this call
		// until the state has transitioned. Because runhcs start is long lived it
		// will return before the actual state is "RUNNING" which causes a failure
		// if the 'state' query comes in and it is not in the "RUNNING" state.
		stateRequest := &taskAPI.StateRequest{
			ID:     r.ID,
			ExecID: r.ExecID,
		}
		for {
			sr, err := s.State(ctx, stateRequest)
			if err != nil {
				log.G(ctx).WithError(err).Debug("failed to query state of container")
				break
			}
			// Have we transitioned states yet? Expect != created && != unknown
			if sr.Status != task.StatusCreated && sr.Status != task.StatusUnknown {
				break
			}
			time.Sleep(1 * time.Second)
		}
	}

	pid := p.stat().pid
	if r.ExecID != "" {
		s.publisher.Publish(ctx,
			runtime.TaskExecStartedEventTopic,
			&eventstypes.TaskExecStarted{
				ContainerID: p.cid,
				ExecID:      p.id,
				Pid:         pid,
			})
	} else {
		s.publisher.Publish(ctx,
			runtime.TaskStartEventTopic,
			&eventstypes.TaskStart{
				ContainerID: p.id,
				Pid:         pid,
			})
	}

	p.startedWg.Done()

	return &taskAPI.StartResponse{
		Pid: pid,
	}, nil
}
879612
func (l *Lifecycle) Start(ctx context.Context) error {
	for _, hook := range l.hooks {
		if hook.OnStart != nil {
			l.logger.Printf("START\t\t%s()", hook.caller)
			if err := hook.OnStart(ctx); err != nil {
				return err
			}
		}
		l.numStarted++
	}
	return nil
}
699009
func (c *cniProcessor) Start(ctx context.Context, eventInfo *common.EventInfo) error {
	contextID, err := generateContextID(eventInfo)
	if err != nil {
		return err
	}

	runtimeInfo, err := c.metadataExtractor(eventInfo)
	if err != nil {
		return err
	}

	if err := c.config.Policy.HandlePUEvent(ctx, contextID, common.EventCreate, runtimeInfo); err != nil {
		return err
	}

	if err := c.config.Policy.HandlePUEvent(ctx, contextID, common.EventStart, runtimeInfo); err != nil {
		return err
	}

	c.config.Collector.CollectContainerEvent(&collector.ContainerRecord{
		ContextID: contextID,
		IPAddress: runtimeInfo.IPAddresses(),
		Tags:      runtimeInfo.Tags(),
		Event:     collector.ContainerStart,
	})

	return nil
}
222759
func (c *Controller) Start() {
	if c.runner != nil {
		return
	}

	// Reconcile during first run removing itself until server is ready.
	endpointPorts := createEndpointPortSpec(c.PublicServicePort, "https", c.ExtraEndpointPorts)
	if err := c.EndpointReconciler.RemoveEndpoints(kubernetesServiceName, c.PublicIP, endpointPorts); err != nil {
		klog.Errorf("Unable to remove old endpoints from kubernetes service: %v", err)
	}

	repairClusterIPs := servicecontroller.NewRepair(c.ServiceClusterIPInterval, c.ServiceClient, c.EventClient, &c.ServiceClusterIPRange, c.ServiceClusterIPRegistry)
	repairNodePorts := portallocatorcontroller.NewRepair(c.ServiceNodePortInterval, c.ServiceClient, c.EventClient, c.ServiceNodePortRange, c.ServiceNodePortRegistry)

	// run all of the controllers once prior to returning from Start.
	if err := repairClusterIPs.RunOnce(); err != nil {
		// If we fail to repair cluster IPs apiserver is useless. We should restart and retry.
		klog.Fatalf("Unable to perform initial IP allocation check: %v", err)
	}
	if err := repairNodePorts.RunOnce(); err != nil {
		// If we fail to repair node ports apiserver is useless. We should restart and retry.
		klog.Fatalf("Unable to perform initial service nodePort check: %v", err)
	}

	c.runner = async.NewRunner(c.RunKubernetesNamespaces, c.RunKubernetesService, repairClusterIPs.RunUntil, repairNodePorts.RunUntil)
	c.runner.Start()
}