// Run fn until context is cancelled up until StartTimeout time has passed.
424002
func (cfg Config) Run(ctx context.Context, fn func(context.Context) error) error {
	retryDelay := func() time.Duration { return 2 * time.Second }
	if cfg.RetryDelay != nil {
		retryDelay = cfg.RetryDelay
	}
	shouldRetry := func(error) bool { return true }
	if cfg.ShouldRetry != nil {
		shouldRetry = cfg.ShouldRetry
	}
	var startTimeout <-chan time.Time // nil chans never unlock !
	if cfg.StartTimeout != 0 {
		startTimeout = time.After(cfg.StartTimeout)
	}

	var err error
	for try := 0; ; try++ {
		if cfg.Tries != 0 && try == cfg.Tries {
			return &RetryExhaustedError{err}
		}
		if err = fn(ctx); err == nil {
			return nil
		}
		if !shouldRetry(err) {
			return err
		}

		log.Print(fmt.Errorf("Retryable error: %s", err))

		select {
		case <-ctx.Done():
			return err
		case <-startTimeout:
			return err
		default:
			time.Sleep(retryDelay())
		}
	}
}
1035669
func (s *scriptCheck) run() *scriptHandle {
	ctx, cancel := context.WithCancel(context.Background())
	exitCh := make(chan struct{})

	// Wrap the original ScriptExecutor in one that obeys context
	// cancelation.
	ctxExec := newContextExec(ctx, s.exec)

	go func() {
		defer close(exitCh)
		timer := time.NewTimer(0)
		defer timer.Stop()
		for {
			// Block until check is removed, Nomad is shutting
			// down, or the check interval is up
			select {
			case <-ctx.Done():
				// check has been removed
				return
			case <-s.shutdownCh:
				// unblock but don't exit until after we heartbeat once more
			case <-timer.C:
				timer.Reset(s.check.Interval)
			}
			metrics.IncrCounter([]string{"client", "consul", "script_runs"}, 1)

			// Execute check script with timeout
			output, code, err := ctxExec.Exec(s.check.Timeout, s.check.Command, s.check.Args)
			switch err {
			case context.Canceled:
				// check removed during execution; exit
				return
			case context.DeadlineExceeded:
				metrics.IncrCounter([]string{"client", "consul", "script_timeouts"}, 1)
				// If no error was returned, set one to make sure the task goes critical
				if err == nil {
					err = context.DeadlineExceeded
				}

				// Log deadline exceeded every time as it's a
				// distinct issue from checks returning
				// failures
				s.logger.Warn("check timed out", "timeout", s.check.Timeout)
			}

			state := api.HealthCritical
			switch code {
			case 0:
				state = api.HealthPassing
			case 1:
				state = api.HealthWarning
			}

			var outputMsg string
			if err != nil {
				state = api.HealthCritical
				outputMsg = err.Error()
			} else {
				outputMsg = string(output)
			}

			// Actually heartbeat the check
			err = s.agent.UpdateTTL(s.id, outputMsg, state)
			select {
			case <-ctx.Done():
				// check has been removed; don't report errors
				return
			default:
			}

			if err != nil {
				if s.lastCheckOk {
					s.lastCheckOk = false
					s.logger.Warn("updating check failed", "error", err)
				} else {
					s.logger.Debug("updating check still failing", "error", err)
				}

			} else if !s.lastCheckOk {
				// Succeeded for the first time or after failing; log
				s.lastCheckOk = true
				s.logger.Info("updating check succeeded")
			}

			select {
			case <-s.shutdownCh:
				// We've been told to exit and just heartbeated so exit
				return
			default:
			}
		}
	}()
	return &scriptHandle{cancel: cancel, exitCh: exitCh}
}
834936
func RunFunc(benchmarkFunc func() int, duration time.Duration, c int) *Result {
	workers := make([]Worker, c)
	for i := 0; i < c; i++ {
		workers[i] = &funcWorker{ID: i, benchmarkFunc: benchmarkFunc}
	}
	return Run(workers, duration)
}
352114
func (s *Scheduler) Run(ctx context.Context) error {
	go func(s *Scheduler, ctx context.Context) {
		for {
			select {
			case <-ctx.Done():
				return
			case <-time.After(s.Interval): // TODO: change to ticker because of garbage collection
				s.gather <- struct{}{}
			}
		}
	}(s, ctx)
	return s.run(ctx)
}
632273
func (d *Dealer) Run(ctx context.Context) error {
	d.shutdownMu.Lock()
	shutdownCh := make(chan struct{})
	d.shutdownCh = shutdownCh
	d.shutdownMu.Unlock()
	for {
		select {

		case <-ctx.Done():
			return ctx.Err()

			// This channel never closes
		case msg := <-d.chatInputCh:
			err := d.handleMessage(ctx, msg)
			if err != nil {
				d.dh.CLogf(ctx, "Error reading message: %s", err.Error())
			}

			// exit the loop if we've shutdown
		case <-shutdownCh:
			return io.EOF

		}
	}
}
103582
func (w *baseCommandWrapper) Run(ctx *cmd.Context) error {
	defer w.closeAPIContexts()
	w.initContexts(ctx)
	w.setRunStarted()
	return w.Command.Run(ctx)
}
636344
func (c *showOutputCommand) Run(ctx *cmd.Context) error {
	// Check whether units were left off our time string.
	r := regexp.MustCompile("[a-zA-Z]")
	matches := r.FindStringSubmatch(c.wait[len(c.wait)-1:])
	// If any match, we have units.  Otherwise, we don't; assume seconds.
	if len(matches) == 0 {
		c.wait = c.wait + "s"
	}

	waitDur, err := time.ParseDuration(c.wait)
	if err != nil {
		return err
	}

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

	wait := time.NewTimer(0 * time.Second)

	switch {
	case waitDur.Nanoseconds() < 0:
		// Negative duration signals immediate return.  All is well.
	case waitDur.Nanoseconds() == 0:
		// Zero duration signals indefinite wait.  Discard the tick.
		wait = time.NewTimer(0 * time.Second)
		_ = <-wait.C
	default:
		// Otherwise, start an ordinary timer.
		wait = time.NewTimer(waitDur)
	}

	result, err := GetActionResult(api, c.requestedId, wait)
	if err != nil {
		return errors.Trace(err)
	}

	return c.out.Write(ctx, FormatActionResult(result))
}
522191
func (s *Selector) run(ctx context.Context, t *Target) chan error {
	ch := make(chan error, 1)
	t.waitQueue <- func() bool {
		cur := t.cur
		cur.RLock()
		root := cur.Root
		cur.RUnlock()

		if root == nil {
			// not ready?
			return false
		}

		ids, err := s.by(ctx, root)
		if err != nil || len(ids) < s.exp {
			return false
		}
		nodes, err := s.wait(ctx, cur, ids...)
		// if nodes==nil, we're not yet ready
		if nodes == nil || err != nil {
			return false
		}
		if s.after != nil {
			if err := s.after(ctx, nodes...); err != nil {
				ch <- err
			}
		}
		close(ch)
		return true
	}
	return ch
}
274796
func (cli *CLI) Run(args []string) int {
	kingpin.Version(version)
	kingpin.Parse()

	//Setup Logging
	loggingClient := logging.NewLogging(*syslogServer, *syslogProtocol, *logFormatterType, *certPath, *debug, *skipSSLSyslog)
	logging.LogStd(fmt.Sprintf("Starting firehose-to-syslog %s ", version), true)
	//
	// if *modeProf != "" {
	// 	switch *modeProf {
	// 	case "cpu":
	// 		defer profile.Start(profile.CPUProfile, profile.ProfilePath(*pathProf)).Stop()
	// 	case "mem":
	// 		defer profile.Start(profile.MemProfile, profile.ProfilePath(*pathProf)).Stop()
	// 	case "block":
	// 		defer profile.Start(profile.BlockProfile, profile.ProfilePath(*pathProf)).Stop()
	// 	default:
	// 		// do nothing
	// 	}
	// }

	c := cfclient.Config{
		ApiAddress:        *apiEndpoint,
		ClientID:          *clientID,
		ClientSecret:      *clientSecret,
		SkipSslValidation: *skipSSLValidation,
		UserAgent:         "firehose-to-syslog/" + version,
	}
	cfClient, err := cfclient.NewClient(&c)
	if err != nil {
		logging.LogError("New Client: ", err)
		return ExitCodeError

	}
	if len(*dopplerEndpoint) > 0 {
		cfClient.Endpoint.DopplerEndpoint = *dopplerEndpoint
	}
	fmt.Println(cfClient.Endpoint.DopplerEndpoint)
	logging.LogStd(fmt.Sprintf("Using %s as doppler endpoint", cfClient.Endpoint.DopplerEndpoint), true)

	//Creating Caching
	var cacheStore caching.CacheStore
	switch {
	case boltDatabasePath != nil && *boltDatabasePath != "":
		cacheStore = &caching.BoltCacheStore{
			Path: *boltDatabasePath,
		}
	default:
		cacheStore = &caching.MemoryCacheStore{}
	}

	if err := cacheStore.Open(); err != nil {
		logging.LogError("Error open cache: ", err)
		return ExitCodeError
	}
	defer cacheStore.Close()

	cachingClient := caching.NewCacheLazyFill(
		&caching.CFClientAdapter{
			CF: cfClient,
		},
		cacheStore,
		&caching.CacheLazyFillConfig{
			IgnoreMissingApps:  *ignoreMissingApps,
			CacheInvalidateTTL: *tickerTime,
			StripAppSuffixes:   strings.Split(*stripAppSuffixes, ","),
		})

	if caching.IsNeeded(*wantedEvents) {
		// Bootstrap cache
		logging.LogStd("Pre-filling cache...", true)
		err = cachingClient.FillCache()
		if err != nil {
			logging.LogError("Error pre-filling cache: ", err)
			return ExitCodeError
		}
		logging.LogStd("Cache filled.", true)
	}

	//Adding Stats
	statistic := stats.NewStats()
	go statistic.PerSec()

	////Starting Http Server for Stats
	if *statServer {
		Server := &stats.Server{
			Logger: log.New(os.Stdout, "", 1),
			Stats:  statistic,
		}

		go Server.Start()
	}

	//Creating Events
	eventFilters := []eventRouting.EventFilter{eventRouting.HasIgnoreField, eventRouting.NotInCertainOrgs(*orgs)}
	events := eventRouting.NewEventRouting(cachingClient, loggingClient, statistic, eventFilters)
	err = events.SetupEventRouting(*wantedEvents)
	if err != nil {
		logging.LogError("Error setting up event routing: ", err)
		return ExitCodeError
	}

	//Set extrafields if needed
	events.SetExtraFields(*extraFields)

	firehoseConfig := &firehoseclient.FirehoseConfig{
		RLPAddr:                strings.Replace(cfClient.Config.ApiAddress, "api", "log-stream", 1),
		InsecureSSLSkipVerify:  *skipSSLValidation,
		FirehoseSubscriptionID: *subscriptionId,
		BufferSize:             *bufferSize,
	}

	if loggingClient.Connect() || *debug {
		logging.LogStd("Connected to Syslog Server! Connecting to Firehose...", true)
	} else {
		logging.LogError("Failed connecting to the Syslog Server...Please check settings and try again!", "")
		return ExitCodeError
	}

	uaa, err := uaago.NewClient(cfClient.Endpoint.AuthEndpoint)
	if err != nil {
		logging.LogError(fmt.Sprint("Failed connecting to Get token from UAA..", err), "")
	}

	ac := authclient.NewHttp(uaa, *clientID, *clientSecret, *skipSSLValidation)
	firehoseClient := firehoseclient.NewFirehoseNozzle(events, firehoseConfig, statistic, ac)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	firehoseClient.Start(ctx)

	signalChan := make(chan os.Signal, 1)
	cleanupDone := make(chan bool)
	signal.Notify(signalChan, os.Interrupt, os.Kill)
	go func() {
		for range signalChan {
			fmt.Println("\nSignal Received, Stop reading and starting Draining...")
			firehoseClient.StopReading()
			cctx, tcancel := context.WithTimeout(context.TODO(), 30*time.Second)
			tcancel()
			firehoseClient.Draining(cctx)
			cleanupDone <- true
		}
	}()

	<-cleanupDone

	return ExitCodeOk
}
1123248
func (t Term) Run(s QueryExecutor, optArgs ...RunOpts) (*Cursor, error) {
	opts := map[string]interface{}{}
	var ctx context.Context = nil // if it's nil connection will form context from connection opts
	if len(optArgs) >= 1 {
		opts = optArgs[0].toMap()
		ctx = optArgs[0].Context
	}

	if s == nil || !s.IsConnected() {
		return nil, ErrConnectionClosed
	}

	q, err := s.newQuery(t, opts)
	if err != nil {
		return nil, err
	}

	return s.Query(ctx, q)
}
380706
func Run(client RedisClient, key string, opts *Options, handler func()) error {
	locker, err := Obtain(client, key, opts)
	if err != nil {
		return err
	}

	sem := make(chan struct{})
	go func() {
		handler()
		close(sem)
	}()

	select {
	case <-sem:
		return locker.Unlock()
	case <-time.After(locker.opts.LockTimeout):
		return ErrLockDurationExceeded
	}
}
362977
func (l *LinuxMonitor) Run(ctx context.Context) error {

	if err := l.proc.config.IsComplete(); err != nil {
		return fmt.Errorf("linux %t: %s", l.proc.host, err)
	}

	return l.Resync(ctx)
}
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
}
197907
func (tio *Timeout) RunContext(ctx context.Context) (*ExitStatus, error) {
	if err := tio.start(); err != nil {
		return nil, err
	}
	return tio.wait(ctx), nil
}
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)
		}
	}
}
1267949
func Run(stmt ast.Stmt, env *Env) (interface{}, error) {
	return RunContext(context.Background(), stmt, env)
}
291069
func (h HookFunc) Run(e *Event, level Level, message string) {
	h(e, level, message)
}