// Run connects to slack RTM API using the provided token
498291
func Run(token string) {
	api = slack.New(token)
	rtm = api.NewRTM()
	teaminfo, _ = api.GetTeamInfo()

	b := bot.New(&bot.Handlers{
		Response: responseHandler,
	},
		&bot.Config{
			Protocol: protocol,
			Server:   teaminfo.Domain,
		},
	)

	b.Disable([]string{"url"})

	go rtm.ManageConnection()

Loop:
	for {
		select {
		case msg := <-rtm.IncomingEvents:
			switch ev := msg.Data.(type) {
			case *slack.HelloEvent:
				readBotInfo(api)
				readChannelData(api)
			case *slack.ChannelCreatedEvent:
				readChannelData(api)
			case *slack.ChannelRenameEvent:
				readChannelData(api)

			case *slack.MessageEvent:
				if !ev.Hidden && !ownMessage(ev.User) {
					C := channelList[ev.Channel]
					var channel = ev.Channel
					if C.IsChannel {
						channel = fmt.Sprintf("#%s", C.Name)
					}
					go b.MessageReceived(
						&bot.ChannelData{
							Protocol:  "slack",
							Server:    teaminfo.Domain,
							Channel:   channel,
							HumanName: C.Name,
							IsPrivate: !C.IsChannel,
						},
						extractText(ev),
						extractUser(ev),
					)
				}

			case *slack.RTMError:
				fmt.Printf("Error: %s\n", ev.Error())

			case *slack.InvalidAuthEvent:
				fmt.Printf("Invalid credentials")
				break Loop
			}
		}
	}
}
178998
func (mod *GitHubBee) Run(eventChan chan bees.Event) {
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: mod.accessToken},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)

	mod.eventChan = eventChan
	mod.client = github.NewClient(tc)

	since := time.Now() // .Add(-time.Duration(24 * time.Hour))
	timeout := time.Duration(time.Second * 10)
	for {
		select {
		case <-mod.SigChan:
			return
		case <-time.After(timeout):
			mod.getRepositoryEvents(mod.owner, mod.repository, since)

		}
		since = time.Now()
		timeout = time.Duration(time.Minute)
	}
}
1310649
func (c *APIServiceRegistrationController) Run(stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer c.queue.ShutDown()

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

	if !controllers.WaitForCacheSync("APIServiceRegistrationController", stopCh, c.apiServiceSynced) {
		return
	}

	// only start one worker thread since its a slow moving API and the aggregation server adding bits
	// aren't threadsafe
	go wait.Until(c.runWorker, time.Second, stopCh)

	<-stopCh
}
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
}
1346561
func (ar *allocRunner) Run() {
	// Close the wait channel on return
	defer close(ar.waitCh)

	// Start the task state update handler
	go ar.handleTaskStateUpdates()

	// Start the alloc update handler
	go ar.handleAllocUpdates()

	// If task update chan has been closed, that means we've been shutdown.
	select {
	case <-ar.taskStateUpdateHandlerCh:
		return
	default:
	}

	// Run the prestart hooks if non-terminal
	if ar.shouldRun() {
		if err := ar.prerun(); err != nil {
			ar.logger.Error("prerun failed", "error", err)
			goto POST
		}
	}

	// Run the runners (blocks until they exit)
	ar.runTasks()

POST:
	// Run the postrun hooks
	if err := ar.postrun(); err != nil {
		ar.logger.Error("postrun failed", "error", err)
	}

}
111952
func Run(s Server, signals ...os.Signal) {
	RunFunc(s.Serve, s.Close, signals...)
}
1352010
func (h *DispatchHook) Run(ctx context.Context, name string, ui Ui, comm Communicator, data interface{}) error {

	hooks, ok := h.Mapping[name]
	if !ok {
		// No hooks for that name. No problem.
		return nil
	}

	for _, hook := range hooks {
		if err := ctx.Err(); err != nil {
			return err
		}

		if err := hook.Run(ctx, name, ui, comm, data); err != nil {
			return err
		}
	}

	return nil
}
1291634
func (e *Signer) Run(stopCh <-chan struct{}) {
	// Shut down queues
	defer utilruntime.HandleCrash()
	defer e.syncQueue.ShutDown()

	if !controller.WaitForCacheSync("bootstrap_signer", stopCh, e.configMapSynced, e.secretSynced) {
		return
	}

	klog.V(5).Infof("Starting workers")
	go wait.Until(e.serviceConfigMapQueue, 0, stopCh)
	<-stopCh
	klog.V(1).Infof("Shutting down")
}
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
	}
}
525056
func (r bot) Run(p *robots.Payload) (s string) {
	// The string returned here will be shown only to the user who executed the command
	// and will show up as a message from slackbot.
	text := strings.TrimSpace(p.Text)
	if text != "" {
		split := strings.Split(text, " ")
		pc := split[0]
		query := strings.Join(split[1:], " ")
		switch pc {
		case "query":
			return r.query(query)
		case "start", "unstart", "finish", "accept", "reject", "deliver":
			return r.changeState(pc, query)
		}
		return fmt.Sprintf("Unknown pivotal command: %s\n%s", pc, r.Description())
	}
	return ""
}
399796
func (n *NodeAuthorizer) Run() error {
	// @step: create the kubernetes client
	client, err := utils.GetKubernetesClient()
	if err != nil {
		return err
	}
	n.client = client

	// @step: create the http service
	server := &http.Server{
		Addr: n.config.Listen,
		TLSConfig: &tls.Config{
			MinVersion:               tls.VersionTLS12,
			PreferServerCipherSuites: true,
		},
	}

	// @step: are we using mutual tls?
	if n.config.TLSClientCAPath != "" {
		// a client certificate is not required, but if given we need to verify it
		server.TLSConfig.ClientAuth = tls.VerifyClientCertIfGiven
		caCert, err := ioutil.ReadFile(n.config.TLSClientCAPath)
		if err != nil {
			return err
		}

		caCertPool := x509.NewCertPool()
		caCertPool.AppendCertsFromPEM(caCert)
		server.TLSConfig.ClientCAs = caCertPool
	}

	// @step: add the routing
	r := mux.NewRouter()
	r.Handle("/authorize/{name}", authorized(n.authorizeHandler, n.config.ClientCommonName, n.useMutualTLS())).Methods(http.MethodPost)
	r.Handle("/metrics", prometheus.Handler()).Methods(http.MethodGet)
	r.HandleFunc("/health", n.healthHandler).Methods(http.MethodGet)
	server.Handler = recovery(r)

	// @step: wait for either an error or a termination signal
	errs := make(chan error, 2)
	go func() {
		errs <- server.ListenAndServeTLS(n.config.TLSCertPath, n.config.TLSPrivateKeyPath)
	}()

	go func() {
		c := make(chan os.Signal)
		signal.Notify(c, syscall.SIGINT)
		errs <- fmt.Errorf("received termination signal: %s", <-c)
	}()

	return <-errs
}
748694
func (tso *TimestampOracle) Run() error {
	log.Debugf("tso %s begin to run", tso)

	m := map[string]interface{}{
		"Addr": tso.cfg.Addr,
	}
	ze, err := zkhelper.CreateElectionWithContents(tso.zkConn, tso.cfg.RootPath, m)
	if err != nil {
		return errors.Trace(err)
	}
	tso.zkElector = &ze

	task := &tsoTask{
		tso:         tso,
		connCh:      make(chan net.Conn, maxConnChanSize),
		interruptCh: make(chan error, 1),
		stopCh:      make(chan struct{}, 1),
		interrupted: 0,
	}

	tso.wg.Add(1)
	go task.Listening()

	err = tso.zkElector.RunTask(task)
	return errors.Trace(err)
}
390972
func (a *adapter) Run() error {
	prompt()

	go func() {
		for {
			line, _, err := a.in.ReadLine()
			message := a.newMessage(string(line))

			if err != nil {
				if err == io.EOF {
					break
					// a.Robot.signalChan <- syscall.SIGTERM
				}
				fmt.Println("error:", err)
			}
			a.Receive(message)
			prompt()
		}
	}()

	<-a.quit
	return nil
}
753288
func Run(c *Config) {
	config = c
	client = rest.NewClient(config.Server, config.Port, config.UseTLS, config.Debug)
	err := client.Login(api.UserCredentials{Email: config.Email, Name: config.User, Password: config.Password})
	if err != nil {
		log.Fatalf("login err: %s\n", err)
	}

	b := bot.New(&bot.Handlers{
		Response: responseHandler,
	},
		&bot.Config{
			Protocol: protocol,
			Server:   config.Server,
		},
	)

	b.Disable([]string{"url"})

	msgChan := client.GetAllMessages()
	for {
		select {
		case msgs := <-msgChan:
			for _, msg := range msgs {
				if !ownMessage(c, msg) {
					b.MessageReceived(
						&bot.ChannelData{
							Protocol:  protocol,
							Server:    "",
							Channel:   msg.ChannelId,
							IsPrivate: false,
						},
						&bot.Message{Text: msg.Text},
						&bot.User{ID: msg.User.Id, RealName: msg.User.UserName, Nick: msg.User.UserName, IsBot: false})
				}

			}
		}
	}
}
294865
func (e *TokensController) Run(workers int, stopCh <-chan struct{}) {
	// Shut down queues
	defer utilruntime.HandleCrash()
	defer e.syncServiceAccountQueue.ShutDown()
	defer e.syncSecretQueue.ShutDown()

	if !controller.WaitForCacheSync("tokens", stopCh, e.serviceAccountSynced, e.secretSynced) {
		return
	}

	klog.V(5).Infof("Starting workers")
	for i := 0; i < workers; i++ {
		go wait.Until(e.syncServiceAccount, 0, stopCh)
		go wait.Until(e.syncSecret, 0, stopCh)
	}
	<-stopCh
	klog.V(1).Infof("Shutting down")
}
1017223
func (t *Ticker) Run() {
	// predeclare some vars
	var (
		i, j, pos, fieldNum int
		n                   uint64
		v                   byte
		stop                bool
		err                 error
		cur                 stats.CPUStats
		cpu                stats.CPU
	)
	for {
		select {
		case <-t.Done:
			return
		case <-t.C:
			cur.Timestamp = time.Now().UTC().UnixNano()
			err = t.Reset()
			if err != nil {
				t.Errs <- err
				break
			}
			cur.CPU = cur.CPU[:0]
			// read each line until eof
			for {
				t.Line, err = t.ReadSlice('\n')
				if err != nil {
					if err == io.EOF {
						break
					}
					t.Errs <- &joe.ReadError{Err: err}
					break
				}
				// Get everything up to the first space, this is the key.  Not all keys are processed.
				for i, v = range t.Line {
					if v == 0x20 {
						t.Val = t.Line[:i]
						pos = i + 1
						break
					}
				}
				// skip the intr line
				if t.Val[0] == 'i' {
					continue
				}
				if t.Val[0] == 'c' {
					if t.Val[1] == 'p' { // process CPU
						cpu.ID = string(t.Val[:])
						j = 0
						// skip over any remaining spaces
						for i, v = range t.Line[pos:] {
							if v != 0x20 {
								break
							}
							j++
						}
						fieldNum = 0
						pos, j = j+pos, j+pos
						// space is the field separator
						for i, v = range t.Line[pos:] {
							if v == '\n' {
								stop = true
							}
							if v == 0x20 || stop {
								fieldNum++
								n, err = helpers.ParseUint(t.Line[j : pos+i])
								if err != nil {
									t.Errs <- &joe.ParseError{Info: string(t.Val[:]), Err: err}
									continue
								}
								j = pos + i + 1
								if fieldNum < 6 {
									if fieldNum < 4 {
										if fieldNum == 1 {
											cpu.User = int64(n)
											continue
										}
										if fieldNum == 2 {
											cpu.Nice = int64(n)
											continue
										}
										cpu.System = int64(n) // 3
										continue
									}
									if fieldNum == 4 {
										cpu.Idle = int64(n)
										continue
									}
									cpu.IOWait = int64(n) // 5
									continue
								}
								if fieldNum < 8 {
									if fieldNum == 6 {
										cpu.IRQ = int64(n)
										continue
									}
									cpu.SoftIRQ = int64(n) // 7
									continue
								}
								if fieldNum == 8 {
									cpu.Steal = int64(n)
									continue
								}
								if fieldNum == 9 {
									cpu.Quest = int64(n)
									continue
								}
								cpu.QuestNice = int64(n) // 10
							}
						}
						cur.CPU = append(cur.CPU, cpu)
						stop = false
						continue
					}
					// Otherwise it's ctxt info; rest of the line is the data.
					n, err = helpers.ParseUint(t.Line[pos : len(t.Line)-1])
					if err != nil {
						t.Errs <- &joe.ParseError{Info: string(t.Val[:]), Err: err}
						continue
					}
					cur.Ctxt = int64(n)
					continue
				}
				if t.Val[0] == 'b' {
					// rest of the line is the data
					n, err = helpers.ParseUint(t.Line[pos : len(t.Line)-1])
					if err != nil {
						t.Errs <- &joe.ParseError{Info: string(t.Val[:]), Err: err}
						continue
					}
					cur.BTime = int64(n)
					continue
				}
				if t.Val[0] == 'p' && t.Val[4] == 'e' { // processes info
					// rest of the line is the data
					n, err = helpers.ParseUint(t.Line[pos : len(t.Line)-1])
					if err != nil {
						t.Errs <- &joe.ParseError{Info: string(t.Val[:]), Err: err}
						continue
					}
					cur.Processes = int64(n)
					continue
				}
			}
			t.Data <- t.Profiler.calculateUtilization(&cur)
			t.Profiler.prior.Ctxt = cur.Ctxt
			t.Profiler.prior.BTime = cur.BTime
			t.Profiler.prior.Processes = cur.Processes
			if len(t.Profiler.prior.CPU) != len(cur.CPU) {
				t.Profiler.prior.CPU = make([]stats.CPU, len(cur.CPU))
			}
			copy(t.Profiler.prior.CPU, cur.CPU)
		}
	}
}
939355
func (u *UIDMonitor) Run(ctx context.Context) error {

	if err := u.proc.config.IsComplete(); err != nil {
		return fmt.Errorf("uid: %s", err)
	}

	return u.Resync(ctx)
}