// Run starts a goroutine to automatically renew a certificate until the passed
// context has been closed. Will return an error if initially a certificate
// cannot be issued/renewed and if any cached certificate is expired.
14665
func (m *Manager) Run(ctxt context.Context) error {
	// manually renew
	err := m.loadOrRenew(ctxt)
	if err != nil {
		return err
	}

	go func() {
		for {
			select {
			case <-m.afterRenew():
				err = m.loadOrRenew(ctxt)
				if err != nil {
					_ = m.errf("cannot renew: %v", err)
					return
				}

			case <-ctxt.Done():
				m.log("context done: %v", ctxt.Err())
				return
			}
		}
	}()

	return nil
}
566193
func Run(ctx context.Context, conf Config) error {
	tcpAddr, err := net.ResolveTCPAddr("tcp", conf.Addr)
	if err != nil {
		return err
	}
	var lsnr net.Listener
	lsnr, err = net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		return err
	}

	if conf.TLSConfig != nil {
		logrus.Info("Enabling TLS")
		lsnr = tls.NewListener(lsnr, conf.TLSConfig)
	}

	var ac auth.AccessController
	if conf.AuthMethod == "token" {
		authOptions, ok := conf.AuthOpts.(map[string]interface{})
		if !ok {
			return fmt.Errorf("auth.options must be a map[string]interface{}")
		}
		ac, err = auth.GetAccessController(conf.AuthMethod, authOptions)
		if err != nil {
			return err
		}
	}

	svr := http.Server{
		Addr: conf.Addr,
		Handler: RootHandler(
			ctx, ac, conf.Trust,
			conf.ConsistentCacheControlConfig, conf.CurrentCacheControlConfig,
			conf.RepoPrefixes),
	}

	logrus.Info("Starting on ", conf.Addr)

	err = svr.Serve(lsnr)

	return err
}
835857
func (w *checkWatcher) Run(ctx context.Context) {
	defer close(w.done)

	// map of check IDs to their metadata
	checks := map[string]*checkRestart{}

	// timer for check polling
	checkTimer := time.NewTimer(0)
	defer checkTimer.Stop() // ensure timer is never leaked

	stopTimer := func() {
		checkTimer.Stop()
		select {
		case <-checkTimer.C:
		default:
		}
	}

	// disable by default
	stopTimer()

	// Main watch loop
	for {
		// disable polling if there are no checks
		if len(checks) == 0 {
			stopTimer()
		}

		select {
		case update := <-w.checkUpdateCh:
			if update.remove {
				// Remove a check
				delete(checks, update.checkID)
				continue
			}

			// Add/update a check
			checks[update.checkID] = update.checkRestart
			w.logger.Debug("watching check", "alloc_id", update.checkRestart.allocID,
				"task", update.checkRestart.taskName, "check", update.checkRestart.checkName)

			// if first check was added make sure polling is enabled
			if len(checks) == 1 {
				stopTimer()
				checkTimer.Reset(w.pollFreq)
			}

		case <-ctx.Done():
			return

		case <-checkTimer.C:
			checkTimer.Reset(w.pollFreq)

			// Set "now" as the point in time the following check results represent
			now := time.Now()

			results, err := w.consul.Checks()
			if err != nil {
				if !w.lastErr {
					w.lastErr = true
					w.logger.Error("failed retrieving health checks", "error", err)
				}
				continue
			}

			w.lastErr = false

			// Keep track of tasks restarted this period so they
			// are only restarted once and all of their checks are
			// removed.
			restartedTasks := map[string]struct{}{}

			// Loop over watched checks and update their status from results
			for cid, check := range checks {
				// Shortcircuit if told to exit
				if ctx.Err() != nil {
					return
				}

				if _, ok := restartedTasks[check.taskKey]; ok {
					// Check for this task already restarted; remove and skip check
					delete(checks, cid)
					continue
				}

				result, ok := results[cid]
				if !ok {
					// Only warn if outside grace period to avoid races with check registration
					if now.After(check.graceUntil) {
						w.logger.Warn("watched check not found in Consul", "check", check.checkName, "check_id", cid)
					}
					continue
				}

				restarted := check.apply(ctx, now, result.Status)
				if restarted {
					// Checks are registered+watched on
					// startup, so it's safe to remove them
					// whenever they're restarted
					delete(checks, cid)

					restartedTasks[check.taskKey] = struct{}{}
				}
			}

			// Ensure even passing checks for restartedTasks are removed
			if len(restartedTasks) > 0 {
				for cid, check := range checks {
					if _, ok := restartedTasks[check.taskKey]; ok {
						delete(checks, cid)
					}
				}
			}
		}
	}
}
19354
func (pget *Pget) Run() error {
	if err := pget.Ready(); err != nil {
		return pget.ErrTop(err)
	}

	if err := pget.Checking(); err != nil {
		return errors.Wrap(err, "failed to check header")
	}

	if err := pget.Download(); err != nil {
		return err
	}

	if err := pget.Utils.BindwithFiles(pget.Procs); err != nil {
		return err
	}

	return nil
}
1322170
func (c Command) Run(ctx *Context) (err error) {
	if len(c.Subcommands) > 0 {
		return c.startApp(ctx)
	}

	if !c.HideHelp && (HelpFlag != BoolFlag{}) {
		// append help to flags
		c.Flags = append(
			c.Flags,
			HelpFlag,
		)
	}

	set, err := c.parseFlags(ctx.Args().Tail())

	context := NewContext(ctx.App, set, ctx)
	context.Command = c
	if checkCommandCompletions(context, c.Name) {
		return nil
	}

	if err != nil {
		if c.OnUsageError != nil {
			err := c.OnUsageError(context, err, false)
			context.App.handleExitCoder(context, err)
			return err
		}
		fmt.Fprintln(context.App.Writer, "Incorrect Usage:", err.Error())
		fmt.Fprintln(context.App.Writer)
		ShowCommandHelp(context, c.Name)
		return err
	}

	if checkCommandHelp(context, c.Name) {
		return nil
	}

	if c.After != nil {
		defer func() {
			afterErr := c.After(context)
			if afterErr != nil {
				context.App.handleExitCoder(context, err)
				if err != nil {
					err = NewMultiError(err, afterErr)
				} else {
					err = afterErr
				}
			}
		}()
	}

	if c.Before != nil {
		err = c.Before(context)
		if err != nil {
			ShowCommandHelp(context, c.Name)
			context.App.handleExitCoder(context, err)
			return err
		}
	}

	if c.Action == nil {
		c.Action = helpSubcommand.Action
	}

	err = HandleAction(c.Action, context)

	if err != nil {
		context.App.handleExitCoder(context, err)
	}
	return err
}
427307
func (c *upgradeJujuCommand) Run(ctx *cmd.Context) (err error) {
	modelType, err := c.ModelType()
	if err != nil {
		return errors.Trace(err)
	}
	if modelType == model.CAAS {
		return c.upgradeCAASModel(ctx)
	}
	return c.upgradeIAASModel(ctx)
}
626816
func (q *Query) Run(ctx context.Context) (QueryResultSet, error) {
	qrs := QueryResultSet{}
	return qrs, q.Iter(ctx, func(qr QueryResult) error {
		qrs = append(qrs, qr)
		return nil
	})
}
461584
func (c *CniMonitor) Run(ctx context.Context) error {

	return c.proc.config.IsComplete()
}
689263
func (c *PassphraseChange) Run(m libkb.MetaContext) (err error) {

	m = m.WithLogTag("PPCHNG")

	defer m.Trace("PassphraseChange#Run", func() error { return err })()
	defer func() {
		m.G().SKBKeyringMu.Unlock()
	}()
	m.G().SKBKeyringMu.Lock()
	m.Debug("| Acquired SKBKeyringMu mutex")

	if len(c.arg.Passphrase) < libkb.MinPassphraseLength {
		return libkb.PassphraseError{Msg: "too short"}
	}

	if err = c.loadMe(); err != nil {
		return
	}

	if _, w := m.ActiveDevice().SyncSecrets(m); w != nil {
		m.Debug("| failed to run secret syncer: %s", w)
	}

	m = m.WithNewProvisionalLoginContextForUser(c.me)

	if c.arg.Force {
		err = c.runForcedUpdate(m)
	} else {
		err = c.runStandardUpdate(m)
	}
	if err != nil {
		return err
	}

	// We used to sync secrets here, but sync secrets in runForceUpdate
	// or runStandardUpdate, since the temporary login information won't
	// persist past the scope of these functions.
	return nil
}
1093239
func (c *ActionFailCommand) Run(ctx *cmd.Context) error {
	err := c.ctx.SetActionMessage(c.failMessage)
	if err != nil {
		return err
	}
	return c.ctx.SetActionFailed()
}
304597
func (ds *RemoteCache) Run(ctx context.Context) error {
	//create new interface if more clients need GC jobs
	backgroundjob, ok := ds.client.(registry.BackgroundService)
	if ok {
		return backgroundjob.Run(ctx)
	}

	<-ctx.Done()
	return ctx.Err()
}
958406
func (e *PGPVerify) Run(m libkb.MetaContext) error {
	var err error
	defer m.Trace("PGPVerify#Run", func() error { return err })()
	var sc libkb.StreamClassification
	sc, e.source, err = libkb.ClassifyStream(e.arg.Source)

	// For a Detached signature, we'll be expecting an UnknownStreamError
	if err != nil {
		if _, ok := err.(libkb.UnknownStreamError); !ok || len(e.arg.Signature) == 0 {
			return err
		}
	}

	if sc.Format == libkb.CryptoMessageFormatPGP && sc.Type == libkb.CryptoMessageTypeClearSignature {
		err = e.runClearsign(m)
		return err
	}
	if len(e.arg.Signature) == 0 {
		err = e.runAttached(m)
		return err
	}
	err = e.runDetached(m)
	return err
}
304733
func (c *showCommand) Run(ctx *cmd.Context) error {
	if err := c.validateIaasController(c.Info().Name); err != nil {
		return errors.Trace(err)
	}
	if c.Log != nil {
		if err := c.Log.Start(ctx); err != nil {
			return err
		}
	}
	client, err := c.NewAPIClient()
	if err != nil {
		return errors.Trace(err)
	}
	defer client.Close()

	result, err := client.Info(c.ID)
	if err != nil {
		return errors.Trace(err)
	}

	c.dumpMetadata(ctx, result)
	return nil
}
156785
func (ec *EstablishingController) Run(stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer ec.queue.ShutDown()

	klog.Infof("Starting EstablishingController")
	defer klog.Infof("Shutting down EstablishingController")

	if !cache.WaitForCacheSync(stopCh, ec.crdSynced) {
		return
	}

	// only start one worker thread since its a slow moving API
	go wait.Until(ec.runWorker, time.Second, stopCh)

	<-stopCh
}
806956
func Run(ctx context.Context, cfg Config, newTeleport NewProcess) error {
	if newTeleport == nil {
		newTeleport = newTeleportProcess
	}
	copyCfg := cfg
	srv, err := newTeleport(&copyCfg)
	if err != nil {
		return trace.Wrap(err, "initialization failed")
	}
	if srv == nil {
		return trace.BadParameter("process has returned nil server")
	}
	if err := srv.Start(); err != nil {
		return trace.Wrap(err, "startup failed")
	}
	// Wait and reload until called exit.
	for {
		srv, err = waitAndReload(ctx, cfg, srv, newTeleport)
		if err != nil {
			// This error means that was a clean shutdown
			// and no reload is necessary.
			if err == ErrTeleportExited {
				return nil
			}
			return trace.Wrap(err)
		}
	}
}
645911
func (i *Instance) Run(ctx context.Context) error {

	go func() {
		<-ctx.Done()
		zap.L().Debug("Stop the supervisor")

		i.CleanUp() // nolint
	}()

	// Clean any previous ACLs. This is needed in case we crashed at some
	// earlier point or there are other ACLs that create conflicts. We
	// try to clean only ACLs related to Trireme.
	if err := i.cleanACLs(); err != nil {
		return fmt.Errorf("Unable to clean previous acls while starting the supervisor: %s", err)
	}

	// Create all the basic target sets. These are the global target sets
	// that do not depend on policy configuration. If they already exist
	// we will delete them and start again.
	targetTCPSet, targetUDPSet, excludedSet, err := createGlobalSets(i.ipset)
	if err != nil {
		return fmt.Errorf("unable to create global sets: %s", err)
	}

	i.targetTCPSet = targetTCPSet
	i.targetUDPSet = targetUDPSet
	i.excludedNetworksSet = excludedSet

	if err := i.updateAllTargetNetworks(i.cfg, &runtime.Configuration{}); err != nil {
		// If there is a failure try to clean up on exit.
		i.ipset.DestroyAll(chainPrefix) // nolint errcheck
		return fmt.Errorf("unable to initialize target networks: %s", err)
	}

	// Initialize all the global Trireme chains. There are several global chaims
	// that apply to all PUs:
	// Tri-App/Tri-Net are the main chains for the egress/ingress directions
	// UID related chains for any UID PUs.
	// Host, Service, Pid chains for the different modes of operation (host mode, pu mode, host service).
	// The priority is explicit (Pid activations take precedence of Service activations and Host Services)
	if err := i.initializeChains(); err != nil {
		return fmt.Errorf("Unable to initialize chains: %s", err)
	}

	// Insert the global ACLS. These are the main ACLs that will direct traffic from
	// the INPUT/OUTPUT chains to the Trireme chains. They also includes the main
	// rules of the main chains. These rules are never touched again, unless
	// if we gracefully terminate.
	if err := i.setGlobalRules(); err != nil {
		return fmt.Errorf("failed to update synack networks: %s", err)
	}

	return nil
}
1073376
func (v *CmdPGPGen) Run() (err error) {
	protocols := []rpc.Protocol{
		NewSecretUIProtocol(v.G()),
	}
	cli, err := GetPGPClient(v.G())
	if err != nil {
		return err
	}
	user, err := GetUserClient(v.G())
	if err != nil {
		return err
	}

	if err = RegisterProtocolsWithContext(protocols, v.G()); err != nil {
		return err
	}

	// Prompt for user IDs if none given on command line
	if len(v.arg.Gen.PGPUids) == 0 {
		if err = v.propmptPGPIDs(); err != nil {
			return err
		}
	} else if err = v.arg.Gen.CreatePGPIDs(); err != nil {
		return err
	}

	hasRandomPw, err := user.LoadHasRandomPw(context.TODO(), keybase1.LoadHasRandomPwArg{})
	if err != nil {
		return err
	}
	if !hasRandomPw {
		v.arg.PushSecret, err = v.G().UI.GetTerminalUI().PromptYesNo(PromptDescriptorPGPGenPushSecret, "Push an encrypted copy of your new secret key to the Keybase.io server?", libkb.PromptDefaultYes)
		if err != nil {
			return err
		}
	}
	if v.arg.DoExport {
		v.arg.ExportEncrypted, err = v.G().UI.GetTerminalUI().PromptYesNo(PromptDescriptorPGPGenEncryptSecret, "When exporting to the GnuPG keychain, encrypt private keys with a passphrase?", libkb.PromptDefaultYes)
		if err != nil {
			return err
		}
	}

	err = cli.PGPKeyGen(context.TODO(), v.arg.Export())
	err = AddPGPMultiInstructions(err)
	return err
}