// Run starts the engine.
// Returns immediately, kicks off a background goroutine.
324333
func (e *MerkleAudit) Run(m libkb.MetaContext) (err error) {
	if m.G().GetEnv().GetDisableMerkleAuditor() {
		m.G().Log.CDebugf(m.Ctx(), "merkle audit disabled, aborting run")
	}
	return RunEngine2(m, e.task)
}
1083588
func (e *Executor) Run(ctx context.Context, command []string) error {
	// Clear any previous state.
	e.executed = false
	e.returnCode = 0
	e.step = nil

	if len(command) == 0 {
		return errors.New("no command")
	}

	ctx, cancelFunc := context.WithCancel(ctx)
	cmd := exec.CommandContext(ctx, command[0], command[1:]...)

	// STDOUT
	stdoutRC, err := cmd.StdoutPipe()
	if err != nil {
		return fmt.Errorf("failed to create STDOUT pipe: %s", err)
	}
	defer stdoutRC.Close()
	stdout := e.configStream(stdoutRC, annotee.STDOUT, e.TeeStdout, true)

	stderrRC, err := cmd.StderrPipe()
	if err != nil {
		return fmt.Errorf("failed to create STDERR pipe: %s", err)
	}
	defer stderrRC.Close()
	stderr := e.configStream(stderrRC, annotee.STDERR, e.TeeStderr, false)

	// Start our process.
	if err := cmd.Start(); err != nil {
		return fmt.Errorf("failed to start bootstrapped process: %s", err)
	}

	// Cleanup the process on exit, and record its status and return code.
	defer func() {
		if err := cmd.Wait(); err != nil {
			var ok bool
			if e.returnCode, ok = exitcode.Get(err); ok {
				e.executed = true
			} else {
				log.WithError(err).Errorf(ctx, "Failed to Wait() for bootstrapped process.")
			}
		} else {
			e.returnCode = 0
			e.executed = true
		}
	}()

	// Probe our execution information.
	options := e.Options
	if options.Execution == nil {
		options.Execution = annotation.ProbeExecution(command, nil, "")
	}

	// Configure our Processor.
	streams := []*annotee.Stream{
		stdout,
		stderr,
	}

	// Process the bootstrapped I/O. We explicitly defer a Finish here to ensure
	// that we clean up any internal streams if our Processor fails/panics.
	//
	// If we fail to process the I/O, terminate the bootstrapped process
	// immediately, since it may otherwise block forever on I/O.
	proc := annotee.New(ctx, options)
	defer proc.Finish()

	if err := proc.RunStreams(streams); err != nil {
		cancelFunc()
		return fmt.Errorf("failed to process bootstrapped I/O: %v", err)
	}

	// Finish and record our annotation steps on completion.
	if e.step, err = proto.Marshal(proc.Finish().RootStep().Proto()); err != nil {
		log.WithError(err).Errorf(ctx, "Failed to Marshal final Step protobuf on completion.")
		return err
	}
	return nil
}
791967
func (m *Main) Run() error {
	m.Logger.Info("running")

	// Read or generate the instance identifier from file.
	id, err := m.readID(filepath.Join(m.DataDir, "instance_id"))
	if err != nil {
		return err
	}
	m.Process.ID = id
	m.Process.DataDir = m.DataDir
	m.Process.Logger = m.Logger.New("component", "process", "id", id)

	// Start process.
	m.Logger.Info("starting process", "id", id)
	if err := m.Process.Start(); err != nil {
		m.Logger.Error("error starting process", "err", err)
		return err
	}

	// Add service to discoverd registry.
	m.Logger.Info("adding service", "name", m.ServiceName)
	if err = m.DiscoverdClient.AddService(m.ServiceName, nil); err != nil && !httphelper.IsObjectExistsError(err) {
		m.Logger.Error("error adding discoverd service", "err", err)
		return err
	}
	inst := &discoverd.Instance{
		Addr: ":" + m.Process.Port,
		Meta: map[string]string{"REDIS_ID": id},
	}

	// Register instance and retain heartbeater.
	m.Logger.Info("registering instance", "addr", inst.Addr, "meta", inst.Meta)
	hb, err := m.DiscoverdClient.RegisterInstance(m.ServiceName, inst)
	if err != nil {
		m.Logger.Error("error registering discoverd instance", "err", err)
		return err
	}
	m.hb = hb
	shutdown.BeforeExit(func() { hb.Close() })

	m.Logger.Info("opening port", "addr", m.Addr)

	// Open HTTP port.
	ln, err := net.Listen("tcp", m.Addr)
	if err != nil {
		m.Logger.Error("error opening port", "err", err)
		return err
	}
	m.ln = keepalive.Listener(ln)

	// Initialize and server handler.
	m.Logger.Info("serving http api")
	h := redis.NewHandler()
	h.Process = m.Process
	h.Heartbeater = m.hb
	h.Logger = m.Logger.New("component", "http")
	go func() { http.Serve(ln, h) }()

	return nil
}
1107838
func (e *BackgroundTask) Run(m libkb.MetaContext) (err error) {
	defer m.Trace(e.Name(), func() error { return err })()

	// use a new background context with a saved cancel function
	var cancel func()
	m, cancel = m.BackgroundWithCancel()

	e.Lock()
	defer e.Unlock()

	e.shutdownFunc = cancel
	if e.shutdown {
		// Shutdown before started
		cancel()
		e.meta("early-shutdown")
		return nil
	}

	// start the loop and return
	go func() {
		err := e.loop(m)
		if err != nil {
			e.log(m, "loop error: %s", err)
		}
		cancel()
		e.meta("loop-exit")
	}()

	return nil
}
929955
func (c *removeCommand) Run(ctx *cmd.Context) error {
	noWaitSet := false
	forceSet := false
	c.fs.Visit(func(flag *gnuflag.Flag) {
		if flag.Name == "no-wait" {
			noWaitSet = true
		} else if flag.Name == "force" {
			forceSet = true
		}
	})
	if !forceSet && noWaitSet {
		return errors.NotValidf("--no-wait without --force")
	}
	var maxWait *time.Duration
	if c.Force {
		if c.NoWait {
			zeroSec := 0 * time.Second
			maxWait = &zeroSec
		}
	}

	client, err := c.getRemoveMachineAPI()
	if err != nil {
		return err
	}
	defer client.Close()

	var results []params.DestroyMachineResult

	if c.KeepInstance || c.Force {
		results, err = client.DestroyMachinesWithParams(c.Force, c.KeepInstance, maxWait, c.MachineIds...)
	} else {
		results, err = client.DestroyMachines(c.MachineIds...)
	}
	if err := block.ProcessBlockedError(err, block.BlockRemove); err != nil {
		return err
	}

	anyFailed := false
	for i, id := range c.MachineIds {
		result := results[i]
		if result.Error != nil {
			anyFailed = true
			ctx.Infof("removing machine %s failed: %s", id, result.Error)
			continue
		}
		if c.KeepInstance {
			ctx.Infof("removing machine %s (but retaining cloud instance)", id)
		} else {
			ctx.Infof("removing machine %s", id)
		}
		for _, entity := range result.Info.DestroyedUnits {
			unitTag, err := names.ParseUnitTag(entity.Tag)
			if err != nil {
				logger.Warningf("%s", err)
				continue
			}
			ctx.Infof("- will remove %s", names.ReadableString(unitTag))
		}
		for _, entity := range result.Info.DestroyedStorage {
			storageTag, err := names.ParseStorageTag(entity.Tag)
			if err != nil {
				logger.Warningf("%s", err)
				continue
			}
			ctx.Infof("- will remove %s", names.ReadableString(storageTag))
		}
		for _, entity := range result.Info.DetachedStorage {
			storageTag, err := names.ParseStorageTag(entity.Tag)
			if err != nil {
				logger.Warningf("%s", err)
				continue
			}
			ctx.Infof("- will detach %s", names.ReadableString(storageTag))
		}
	}

	if anyFailed {
		return cmd.ErrSilent
	}
	return nil
}
879870
func Run(c Component) Wait {
	wait := make(Wait)
	go func() {
		c.Process()
		wait <- Done{}
	}()
	return wait
}
593728
func (nap *NapNap) Run(engine *Server) error {
	engine.Handler = nap
	return engine.ListenAndServe()
}
541268
func (e *EmptyService) Run(ctx context.Context, commandParts []string, options options.Run) (int, error) {
	return 0, nil
}
565206
func (e Engine) Run(stageName string) error {
	if e.Fetcher == nil || e.Logger == nil {
		fmt.Fprintf(os.Stderr, "engine incorrectly configured\n")
		return errors.ErrEngineConfiguration
	}
	baseConfig := types.Config{
		Ignition: types.Ignition{Version: types.MaxVersion.String()},
	}

	systemBaseConfig, r, err := system.FetchBaseConfig(e.Logger)
	e.logReport(r)
	if err != nil && err != providers.ErrNoProvider {
		e.Logger.Crit("failed to acquire system base config: %v", err)
		return err
	}

	cfg, err := e.acquireConfig()
	if err == errors.ErrEmpty {
		e.Logger.Info("%v: ignoring user-provided config", err)
	} else if err != nil {
		e.Logger.Crit("failed to acquire config: %v", err)
		return err
	}

	e.Logger.PushPrefix(stageName)
	defer e.Logger.PopPrefix()

	fullConfig := latest.Merge(baseConfig, latest.Merge(systemBaseConfig, cfg))
	if err = stages.Get(stageName).Create(e.Logger, e.Root, *e.Fetcher).Run(fullConfig); err != nil {
		// e.Logger could be nil
		fmt.Fprintf(os.Stderr, "%s failed", stageName)
		tmp, jsonerr := json.MarshalIndent(fullConfig, "", "  ")
		if jsonerr != nil {
			// Nothing else to do with this error
			fmt.Fprintf(os.Stderr, "Could not marshal full config: %v", err)
		} else {
			fmt.Fprintf(os.Stderr, "Full config:\n%s", string(tmp))
		}
		return err
	}
	e.Logger.Info("%s passed", stageName)
	return nil
}
564707
func (c *configCommand) Run(ctx *cmd.Context) error {
	client, err := c.getAPI()
	if err != nil {
		return errors.Trace(err)
	}
	defer func() { _ = client.Close() }()

	if len(c.resetKeys) > 0 {
		if err := c.resetConfig(client, ctx); err != nil {
			// We return this error naked as it is almost certainly going to be
			// cmd.ErrSilent and the cmd.Command framework expects that back
			// from cmd.Run if the process is blocked.
			return err
		}
	}
	if c.action == nil {
		// If we are reset only, we end up here; we have already done that.
		return nil
	}

	return c.action(client, ctx)
}
728109
func (s *Service) Run(ctx context.Context, commandParts []string, options options.Run) (int, error) {
	err := s.ensureImageExists(ctx, false, false)
	if err != nil {
		return -1, err
	}

	client := s.clientFactory.Create(s)

	namer, err := NewNamer(ctx, client, s.project.Name, s.name, true)
	if err != nil {
		return -1, err
	}

	configOverride := &config.ServiceConfig{Command: commandParts, Tty: !options.DisableTty, StdinOpen: !options.DisableTty}

	c, err := s.createContainer(ctx, namer, "", configOverride, true)
	if err != nil {
		return -1, err
	}

	if err := s.connectContainerToNetworks(ctx, c, true); err != nil {
		return -1, err
	}

	if options.Detached {
		logrus.Infof("%s", c.Name())
		return 0, c.Start(ctx)
	}
	return c.Run(ctx, configOverride)
}
12264
func (c *CloudNodeLifecycleController) Run(stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()

	// The following loops run communicate with the APIServer with a worst case complexity
	// of O(num_nodes) per cycle. These functions are justified here because these events fire
	// very infrequently. DO NOT MODIFY this to perform frequent operations.

	// Start a loop to periodically check if any nodes have been
	// deleted or shutdown from the cloudprovider
	wait.Until(c.MonitorNodes, c.nodeMonitorPeriod, stopCh)
}
371626
func (e *Engine) Run() {
	log.Infof("Seesaw Engine starting for %s", e.config.ClusterName)

	e.initNetwork()

	n, err := config.NewNotifier(e.config)
	if err != nil {
		log.Fatalf("config.NewNotifier() failed: %v", err)
	}
	e.notifier = n

	if e.config.AnycastEnabled {
		go e.bgpManager.run()
	}
	go e.hcManager.run()

	go e.syncClient.run()
	go e.syncServer.run()

	go e.syncRPC()
	go e.engineIPC()
	go e.gratuitousARP()

	e.manager()
}
514694
func (m *Main) Run() error {
	if m.Num < 2 || m.Vehicle == "" {
		return fmt.Errorf("Need more gophers and/or vehicles.")
	}
	fmt.Printf("%d gophers stole my %s!\n", m.Num, m.Vehicle)
	return nil
}
980534
func Run(engine *Engine, protocol string) (string, chan struct{}, chan struct{}) {
	// launch server
	server, err := transport.Launch(protocol + "://localhost:0")
	if err != nil {
		panic(err)
	}

	// prepare channels
	quit := make(chan struct{})
	done := make(chan struct{})

	// start accepting connections
	engine.Accept(server)

	// prepare shutdown
	go func() {
		// wait for signal
		<-quit

		// errors from close are ignored
		_ = server.Close()

		// close broker
		engine.Close()

		close(done)
	}()

	// get random port
	_, port, _ := net.SplitHostPort(server.Addr().String())

	return port, quit, done
}
972900
func (s *Server) Run() {
	s.Log.Info("msg", "Starting HTTP Server")

	// start http server
	httpServer := &http.Server{Addr: s.Config.HTTPAddr, Handler: s}

	go func() {
		s.Log.Info("msg", "HTTP Server listening", "address", s.Config.HTTPAddr)
		httpServer.ListenAndServe()
	}()

	// wait for stop signal
	<-s.stopCh

	s.Log.Info("msg", "Shutting down HTTP Server...")

	httpServer.Shutdown(context.Background())
}
375223
func (ca Actions) Run(ctx context.Context, c *cli.Context, i int) error {
	if len(ca) < i || i >= len(ca) {
		return errors.New("action not found")
	}
	if ca[i].Fn == nil {
		return errors.New("action invalid")
	}
	return ca[i].Fn(ctx, c)
}