// Run starts the heartbeating to master and starts accepting requests.
499531
func (as *AgentServer) serveTcp(listener net.Listener) {

	for {
		// Listen for an incoming connection.
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("Error accepting: ", err.Error())
			continue
		}
		// Handle connections in a new goroutine.
		go func() {
			defer conn.Close()
			if err = conn.SetDeadline(time.Time{}); err != nil {
				fmt.Printf("Failed to set timeout: %v\n", err)
			}
			if c, ok := conn.(*net.TCPConn); ok {
				c.SetKeepAlive(true)
			}
			as.handleRequest(conn)
		}()
	}
}
202045
func (svc *AsyncService) Run() error {
	for {
		e, open := <-svc.c
		if open {
			// Call event handler
			svc.i.HandleEvent(e)
		} else {
			// Exit runner
			break
		}
	}
	return nil
}
676779
func Run(sOpts *Options, nOpts *natsd.Options) (*StanServer, error) {
	return RunServerWithOpts(sOpts, nOpts)
}
1305136
func (s *Scheduler) Run() {
	s.mu.Lock()
	s.state = stateRunning
	s.mu.Unlock()

	s.startProcessRequestsLoop()
}
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})
				}

			}
		}
	}
}
183909
func (e *PaperKeySubmit) Run(m libkb.MetaContext) error {
	me, err := libkb.LoadMe(libkb.NewLoadUserArgWithMetaContext(m))
	if err != nil {
		return err
	}

	e.deviceWithKeys, err = matchPaperKey(m, me, e.paperPhrase)
	if err != nil {
		return err
	}

	m.ActiveDevice().CacheProvisioningKey(m, e.deviceWithKeys)

	// send a notification that a paper key has been cached
	// for rekey purposes
	m.G().NotifyRouter.HandlePaperKeyCached(me.GetUID(), e.deviceWithKeys.EncryptionKey().GetKID(), e.deviceWithKeys.SigningKey().GetKID())

	// XXX - this is temporary until KBFS handles the above notification
	m.G().UserChanged(m.Ctx(), me.GetUID())

	return nil
}
924079
func (sw *SleepWorkflow) Run(ctx context.Context, manager *Manager, wi *topo.WorkflowInfo) error {
	// Save all values, create a UI Node.
	sw.mu.Lock()
	sw.manager = manager
	sw.wi = wi

	sw.node.Listener = sw
	sw.node.Display = NodeDisplayDeterminate
	sw.node.Actions = []*Action{
		{
			Name:  pauseAction,
			State: ActionStateEnabled,
			Style: ActionStyleNormal,
		},
		{
			Name:  resumeAction,
			State: ActionStateDisabled,
			Style: ActionStyleNormal,
		},
	}
	sw.uiUpdateLocked()
	sw.node.BroadcastChanges(false /* updateChildren */)
	sw.mu.Unlock()

	for {
		sw.mu.Lock()
		data := *sw.data
		sw.mu.Unlock()

		if data.Slept == data.Duration {
			break
		}

		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(time.Second):
			if !data.Paused {
				sw.mu.Lock()
				sw.data.Slept++
				// UI update every second.
				sw.uiUpdateLocked()
				sw.node.BroadcastChanges(false /* updateChildren */)
				// Checkpoint every 5 seconds.
				if sw.data.Slept%5 == 0 {
					if err := sw.checkpointLocked(ctx); err != nil {
						sw.mu.Unlock()
						return err
					}
				}
				sw.mu.Unlock()
			}
		}
	}

	return nil
}
1116274
func (c *configCommand) Run(ctx *cmd.Context) error {
	client, err := c.getAPI()
	if err != nil {
		return err
	}
	defer client.Close()
	return c.action(client, ctx)
}
663118
func (c *CharmResourcesCommand) Run(ctx *cmd.Context) error {
	return c.baseRun(ctx)
}
706478
func (m *Mrb) Run(v Value, self Value) (*MrbValue, error) {
	if self == nil {
		self = m.TopSelf()
	}

	mrbV := v.MrbValue(m)
	mrbSelf := self.MrbValue(m)

	proc := C._go_mrb_proc_ptr(mrbV.value)
	value := C.mrb_run(m.state, proc, mrbSelf.value)

	if exc := checkException(m.state); exc != nil {
		return nil, exc
	}

	return newValue(m.state, value), nil
}
1227581
func (e *EventServer) Run(ctx context.Context) error {

	// Create the handler
	e.server = &http.Server{
		Handler: e,
	}

	// Start a custom listener
	addr, _ := net.ResolveUnixAddr("unix", e.socketPath)
	nl, err := net.ListenUnix("unix", addr)
	if err != nil {
		return fmt.Errorf("Unable to start API server: %s", err)
	}

	// We make the socket accesible to all users of the system.
	// TODO: create a trireme group for this
	if err := os.Chmod(addr.String(), 0766); err != nil {
		return fmt.Errorf("Cannot make the socket accessible to all users: %s", err)
	}

	listener := &UIDListener{nl}

	// Start serving HTTP requests in the background
	go e.server.Serve(listener) // nolint

	// Listen for context cancellation to close the socket.
	go func() {
		<-ctx.Done()
		nl.Close() // nolint
	}()

	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
}
69419
func (u *DropsondeMarshaller) Run(inputChan <-chan *events.Envelope, outputChan chan<- []byte) {
	for message := range inputChan {

		messageBytes, err := proto.Marshal(message)
		if err != nil {
			u.logger.Errorf("dropsondeMarshaller: marshal error %v", err)
			metrics.BatchIncrementCounter("dropsondeMarshaller.marshalErrors")
			continue
		}

		u.incrementMessageCount(message.GetEventType())
		outputChan <- messageBytes
	}
}
18101
func (hs *HealthzServer) Run() {
	serveMux := http.NewServeMux()
	serveMux.Handle("/healthz", healthzHandler{hs: hs})
	server := hs.httpFactory.New(hs.addr, serveMux)

	go wait.Until(func() {
		klog.V(3).Infof("Starting goroutine for healthz on %s", hs.addr)

		listener, err := hs.listener.Listen(hs.addr)
		if err != nil {
			msg := fmt.Sprintf("Failed to start node healthz on %s: %v", hs.addr, err)
			if hs.recorder != nil {
				hs.recorder.Eventf(hs.nodeRef, api.EventTypeWarning, "FailedToStartNodeHealthcheck", msg)
			}
			klog.Error(msg)
			return
		}

		if err := server.Serve(listener); err != nil {
			klog.Errorf("Healthz closed with error: %v", err)
			return
		}
		klog.Error("Unexpected healthz closed.")
	}, nodeHealthzRetryInterval, wait.NeverStop)
}
1324405
func (p *UnitStatePublisher) Run(beatchan <-chan *unit.UnitStateHeartbeat, stop <-chan struct{}) {
	var period time.Duration
	if p.ttl > 10*time.Second {
		period = p.ttl * 4 / 5
	} else {
		period = p.ttl / 2
	}

	go func() {
		for {
			select {
			case <-stop:
				return
			case <-p.clock.After(period):
				p.cacheMutex.Lock()
				for name, us := range p.cache {
					go p.queueForPublish(name, us)
				}
				p.pruneCache()
				p.cacheMutex.Unlock()
			}
		}
	}()

	machID := p.mach.State().ID

	// Spawn goroutines to publish unit states. Each goroutine waits until
	// it sees an event arrive on toPublish, then attempts to grab the
	// relevant UnitState and publish it to the registry.
	for i := 0; i < numPublishers; i++ {
		go func() {
			for {
				select {
				case <-stop:
					return
				case name := <-p.toPublish:
					p.toPublishMutex.Lock()
					// Grab the latest state by that name
					us, ok := p.toPublishStates[name]
					if !ok {
						// If one doesn't exist, ignore.
						p.toPublishMutex.Unlock()
						continue
					}
					delete(p.toPublishStates, name)
					p.toPublishMutex.Unlock()
					p.publisher(name, us)

				}
			}
		}()
	}

	for {
		select {
		case <-stop:
			return
		case bt := <-beatchan:
			if bt.State != nil {
				bt.State.MachineID = machID
			}

			if p.updateCache(bt) {
				go p.queueForPublish(bt.Name, bt.State)
			}
		}
	}
}
785770
func (b *Bench) Run(ctx context.Context) error {
	err := b.createConns(ctx)
	if err != nil {
		return err
	}

	b.createThreads(ctx)
	b.runTest(ctx)
	return nil
}
959574
func (c *enableDestroyController) Run(ctx *cmd.Context) error {
	client, err := c.getAPI()
	if err != nil {
		return errors.Trace(err)
	}
	defer client.Close()
	return errors.Trace(client.RemoveBlocks())
}