// Run tests if a yarpc client returns correctly a client timeout error behind
// the TimeoutError interface when the context deadline is reached while the
// server is taking too long to respond.
179463
func Run(t crossdock.T) {
	assert := crossdock.Assert(t)
	fatals := crossdock.Fatals(t)

	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()

	dispatcher := disp.Create(t)
	fatals.NoError(dispatcher.Start(), "could not start Dispatcher")
	defer dispatcher.Stop()

	client := raw.New(dispatcher.ClientConfig("yarpc-test"))
	_, err := client.Call(ctx, "sleep/raw", nil)
	fatals.Error(err, "expected a failure for timeout")

	if yarpcerrors.FromError(err).Code() == yarpcerrors.CodeInvalidArgument {
		t.Skipf("sleep/raw method not implemented: %v", err)
		return
	}

	assert.Equal(yarpcerrors.CodeDeadlineExceeded, yarpcerrors.FromError(err).Code(), "is an error with code CodeDeadlineExceeded: %v", err)
}
625572
func (proxy *SCTPProxy) Run() {
	quit := make(chan bool)
	defer close(quit)
	for {
		client, err := proxy.listener.Accept()
		if err != nil {
			log.Printf("Stopping proxy on sctp/%v for sctp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err)
			return
		}
		go proxy.clientLoop(client.(*sctp.SCTPConn), quit)
	}
}
1050757
func Run(c *deis.Client, appID string, command string) (api.AppRunResponse, error) {
	req := api.AppRunRequest{Command: command}
	body, err := json.Marshal(req)

	if err != nil {
		return api.AppRunResponse{}, err
	}

	u := fmt.Sprintf("/v2/apps/%s/run", appID)

	res, reqErr := c.Request("POST", u, body)
	if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) {
		return api.AppRunResponse{}, reqErr
	}

	arr := api.AppRunResponse{}

	if err = json.NewDecoder(res.Body).Decode(&arr); err != nil {
		return api.AppRunResponse{}, err
	}

	return arr, reqErr
}
505034
func Run(t crossdock.T) {
	t = createHeadersT(t)

	fatals := crossdock.Fatals(t)
	assert := crossdock.Assert(t)
	checks := crossdock.Checks(t)

	dispatcher := disp.Create(t)
	fatals.NoError(dispatcher.Start(), "could not start Dispatcher")
	defer dispatcher.Stop()

	var caller headerCaller
	encoding := t.Param(params.Encoding)
	switch encoding {
	case "raw":
		caller = rawCaller{raw.New(dispatcher.ClientConfig("yarpc-test"))}
	case "json":
		caller = jsonCaller{json.New(dispatcher.ClientConfig("yarpc-test"))}
	case "thrift":
		caller = thriftCaller{echoclient.New(dispatcher.ClientConfig("yarpc-test"))}
	default:
		fatals.Fail("", "unknown encoding %q", encoding)
	}

	token1 := random.String(10)
	token2 := random.String(10)

	tests := []struct {
		desc string
		give map[string]string
		want map[string]string
	}{
		{
			"valid headers",
			map[string]string{"token1": token1, "token2": token2},
			map[string]string{"token1": token1, "token2": token2},
		},
		{
			"non-string values",
			map[string]string{"token": "42"},
			map[string]string{"token": "42"},
		},
		{
			"empty strings",
			map[string]string{"token": ""},
			map[string]string{"token": ""},
		},
		{
			"no headers",
			nil,
			nil,
		},
		{
			"empty map",
			map[string]string{},
			map[string]string{},
		},
		{
			"varying casing",
			map[string]string{"ToKeN1": token1, "tOkEn2": token2},
			map[string]string{"token1": token1, "token2": token2},
		},
		{
			"http header conflict",
			map[string]string{"Rpc-Procedure": "does not exist"},
			map[string]string{"rpc-procedure": "does not exist"},
		},
		{
			"mixed case value",
			map[string]string{"token": "MIXED case Value"},
			map[string]string{"token": "MIXED case Value"},
		},
	}

	for _, tt := range tests {
		gotHeaders, err := caller.Call(tt.give)
		if checks.NoError(err, "%v: call failed", tt.desc) {
			internal.RemoveVariableMapKeys(gotHeaders)

			// assert.Equal doesn't work with nil maps
			if len(tt.want) == 0 {
				assert.Empty(gotHeaders, "%v: returns valid headers", tt.desc)
			} else {
				assert.Equal(tt.want, gotHeaders, "%v: returns valid headers", tt.desc)
			}
		}
	}
}
669969
func (s *statsClient) Run(ctx context.Context) error {
	if err := s.rpchdl.NewRPCClient(statsContextID, s.statsChannel, s.secret); err != nil {
		zap.L().Error("Stats RPC client cannot connect", zap.Error(err))
		return err
	}

	go s.sendStats(ctx)

	return nil
}
646243
func Run(config *Config) {
	var err error
	ctx := context.Background()
	httpChatClient, err = google.DefaultClient(ctx, chatAuthScope)
	if err != nil {
		log.Printf("Error setting http client: %v\n", err)
		return
	}

	client, err := pubsub.NewClient(ctx, config.PubSubProject)
	if err != nil {
		log.Printf("Error creating client: %v\n", err)
		return
	}

	topic := client.Topic(config.TopicName)

	// Create a new subscription to the previously created topic
	// with the given name.
	sub := client.Subscription(config.SubscriptionName)
	ok, err := sub.Exists(ctx)
	if err != nil {
		log.Printf("Error getting subscription: %v\n", err)
		return
	}
	if !ok {
		// Subscription doesn't exist.
		sub, err = client.CreateSubscription(ctx, config.SubscriptionName,
			pubsub.SubscriptionConfig{
				Topic:       topic,
				AckDeadline: 10 * time.Second,
			})
		if err != nil {
			log.Printf("Error subscribing: %v\n", err)
			return
		}
	}

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

	err = sub.Receive(context.Background(),
		func(ctx context.Context, m *pubsub.Message) {
			var msg ChatMessage
			err = json.Unmarshal(m.Data, &msg)
			if err != nil {
				log.Printf("Failed message unmarshal(%v): %s\n", err, m.Data)
				m.Ack()
				return
			}
			if msg.Token != config.Token {
				log.Printf("Failed to verify token: %s", msg.Token)
				m.Ack()
				return
			}

			log.Printf("Space: %s (%s)\n", msg.Space.Name, msg.Space.DisplayName)
			log.Printf("Message type: %s\n", msg.Type)
			log.Printf("From: %s (%s)\n", msg.User.Name, msg.User.DisplayName)
			switch msg.Type {
			case "ADDED_TO_SPACE":
				if config.WelcomeMessage != "" {
					log.Printf("Sending welcome message to %s\n", msg.Space.Name)
					b.SendMessage(msg.Space.Name, config.WelcomeMessage, nil)
				}
			case "REMOVED_FROM_SPACE":
				break
			case "MESSAGE":
				log.Printf("Message: %s\n", msg.Message.ArgumentText)
				b.MessageReceived(
					&bot.ChannelData{
						Protocol:  protocol,
						Server:    server,
						HumanName: msg.Space.DisplayName,
						Channel:   msg.Space.Name + ":" + msg.Message.Thread.Name,
						IsPrivate: msg.Space.Type == "DM",
					},
					&bot.Message{
						Text:     msg.Message.ArgumentText,
						IsAction: false,
					},
					&bot.User{
						ID:       msg.User.Name,
						Nick:     msg.User.DisplayName,
						RealName: msg.User.DisplayName,
					})
			}

			m.Ack()
		})
	if err != nil {
		log.Printf("Error setting up receiving: %v\n", err)
		return
	}
	// Wait indefinetely
	select {}
}
1322327
func (s *SecretsProxy) Run(ctx context.Context) error {
	s.Lock()
	defer s.Unlock()

	var err error

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

	s.server = &http.Server{
		Handler: http.HandlerFunc(s.apiProcessor),
	}

	go func() {
		<-ctx.Done()
		s.server.Close() // nolint errcheck
	}()

	go s.server.Serve(server.NewUIDListener(nl)) // nolint errcheck

	return nil
}
976022
func (e *Runner) Run(args []string) error {
	e.prepareForExecution()

	// determine which phase should be run according to RunnerOptions
	phaseRunFlags, err := e.computePhaseRunFlags()
	if err != nil {
		return err
	}

	// builds the runner data
	var data RunData
	if data, err = e.InitData(args); err != nil {
		return err
	}

	err = e.visitAll(func(p *phaseRunner) error {
		// if the phase should not be run, skip the phase.
		if run, ok := phaseRunFlags[p.generatedName]; !run || !ok {
			return nil
		}

		// Errors if phases that are meant to create special subcommands only
		// are wrongly assigned Run Methods
		if p.RunAllSiblings && (p.RunIf != nil || p.Run != nil) {
			return errors.Wrapf(err, "phase marked as RunAllSiblings can not have Run functions %s", p.generatedName)
		}

		// If the phase defines a condition to be checked before executing the phase action.
		if p.RunIf != nil {
			// Check the condition and returns if the condition isn't satisfied (or fails)
			ok, err := p.RunIf(data)
			if err != nil {
				return errors.Wrapf(err, "error execution run condition for phase %s", p.generatedName)
			}

			if !ok {
				return nil
			}
		}

		// Runs the phase action (if defined)
		if p.Run != nil {
			if err := p.Run(data); err != nil {
				return errors.Wrapf(err, "error execution phase %s", p.generatedName)
			}
		}

		return nil
	})

	return err
}
1237000
func (a *ArgoCDServer) Run(ctx context.Context, port int) {
	grpcS := a.newGRPCServer()
	grpcWebS := grpcweb.WrapServer(grpcS)
	var httpS *http.Server
	var httpsS *http.Server
	if a.useTLS() {
		httpS = newRedirectServer(port)
		httpsS = a.newHTTPServer(ctx, port, grpcWebS)
	} else {
		httpS = a.newHTTPServer(ctx, port, grpcWebS)
	}
	metricsServ := newAPIServerMetricsServer()

	// Start listener
	var conn net.Listener
	var realErr error
	_ = wait.ExponentialBackoff(backoff, func() (bool, error) {
		conn, realErr = net.Listen("tcp", fmt.Sprintf(":%d", port))
		if realErr != nil {
			a.log.Warnf("failed listen: %v", realErr)
			return false, nil
		}
		return true, nil
	})
	errors.CheckError(realErr)

	// Cmux is used to support servicing gRPC and HTTP1.1+JSON on the same port
	tcpm := cmux.New(conn)
	var tlsm cmux.CMux
	var grpcL net.Listener
	var httpL net.Listener
	var httpsL net.Listener
	if !a.useTLS() {
		httpL = tcpm.Match(cmux.HTTP1Fast())
		grpcL = tcpm.Match(cmux.HTTP2HeaderField("content-type", "application/grpc"))
	} else {
		// We first match on HTTP 1.1 methods.
		httpL = tcpm.Match(cmux.HTTP1Fast())

		// If not matched, we assume that its TLS.
		tlsl := tcpm.Match(cmux.Any())
		tlsConfig := tls.Config{
			Certificates: []tls.Certificate{*a.settings.Certificate},
		}
		if a.TLSConfigCustomizer != nil {
			a.TLSConfigCustomizer(&tlsConfig)
		}
		tlsl = tls.NewListener(tlsl, &tlsConfig)

		// Now, we build another mux recursively to match HTTPS and gRPC.
		tlsm = cmux.New(tlsl)
		httpsL = tlsm.Match(cmux.HTTP1Fast())
		grpcL = tlsm.Match(cmux.Any())
	}

	// Start the muxed listeners for our servers
	log.Infof("argocd %s serving on port %d (url: %s, tls: %v, namespace: %s, sso: %v)",
		argocd.GetVersion(), port, a.settings.URL, a.useTLS(), a.Namespace, a.settings.IsSSOConfigured())

	go a.projInformer.Run(ctx.Done())
	go func() { a.checkServeErr("grpcS", grpcS.Serve(grpcL)) }()
	go func() { a.checkServeErr("httpS", httpS.Serve(httpL)) }()
	if a.useTLS() {
		go func() { a.checkServeErr("httpsS", httpsS.Serve(httpsL)) }()
		go func() { a.checkServeErr("tlsm", tlsm.Serve()) }()
	}
	go a.watchSettings(ctx)
	go a.rbacPolicyLoader(ctx)
	go func() { a.checkServeErr("tcpm", tcpm.Serve()) }()
	go func() { a.checkServeErr("metrics", metricsServ.ListenAndServe()) }()
	if !cache.WaitForCacheSync(ctx.Done(), a.projInformer.HasSynced) {
		log.Fatal("Timed out waiting for project cache to sync")
	}

	a.stopCh = make(chan struct{})
	<-a.stopCh
	errors.CheckError(conn.Close())
}
702744
func (mr *ModRunner) Run() error {
	for {
		modchan := make(chan *moddwatch.Mod, 1024)
		err := mr.runOnChan(modchan, func() {})
		if err != nil {
			return err
		}
	}
}
551508
func (c *ServiceClient) Run() {
	defer close(c.exitCh)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// init will be closed when Consul has been contacted
	init := make(chan struct{})
	go checkConsulTLSSkipVerify(ctx, c.logger, c.client, init)

	// Process operations while waiting for initial contact with Consul but
	// do not sync until contact has been made.
INIT:
	for {
		select {
		case <-init:
			c.markSeen()
			break INIT
		case <-c.shutdownCh:
			return
		case ops := <-c.opCh:
			c.merge(ops)
		}
	}
	c.logger.Trace("able to contact Consul")

	// Block until contact with Consul has been established
	// Start checkWatcher
	go c.checkWatcher.Run(ctx)

	// Always immediately sync to reconcile Nomad and Consul's state
	retryTimer := time.NewTimer(0)

	failures := 0
	for {
		select {
		case <-retryTimer.C:
		case <-c.shutdownCh:
			// Cancel check watcher but sync one last time
			cancel()
		case ops := <-c.opCh:
			c.merge(ops)
		}

		if err := c.sync(); err != nil {
			if failures == 0 {
				// Log on the first failure
				c.logger.Warn("failed to update services in Consul", "error", err)
			} else if failures%10 == 0 {
				// Log every 10th consecutive failure
				c.logger.Error("still unable to update services in Consul", "failures", failures, "error", err)
			}

			failures++
			if !retryTimer.Stop() {
				// Timer already expired, since the timer may
				// or may not have been read in the select{}
				// above, conditionally receive on it
				select {
				case <-retryTimer.C:
				default:
				}
			}
			backoff := c.retryInterval * time.Duration(failures)
			if backoff > c.maxRetryInterval {
				backoff = c.maxRetryInterval
			}
			retryTimer.Reset(backoff)
		} else {
			if failures > 0 {
				c.logger.Info("successfully updated services in Consul")
				failures = 0
			}

			// Reset timer to periodic interval to periodically
			// reconile with Consul
			if !retryTimer.Stop() {
				select {
				case <-retryTimer.C:
				default:
				}
			}
			retryTimer.Reset(c.periodicInterval)
		}

		select {
		case <-c.shutdownCh:
			// Exit only after sync'ing all outstanding operations
			if len(c.opCh) > 0 {
				for len(c.opCh) > 0 {
					c.merge(<-c.opCh)
				}
				continue
			}
			return
		default:
		}

	}
}
369672
func Run(t crossdock.T) {
	fatals := crossdock.Fatals(t)

	server := t.Param(params.Server)
	fatals.NotEmpty(server, "server is required")

	clientConn, err := ggrpc.Dial(fmt.Sprintf("%s:8089", server), ggrpc.WithInsecure())
	fatals.NoError(err, "grpc.Dial failed")

	client := crossdockpb.NewEchoClient(clientConn)

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	token := random.String(5)

	pong, err := client.Echo(wrap(ctx), &crossdockpb.Ping{Beep: token})

	crossdock.Fatals(t).NoError(err, "call to Echo::echo failed: %v", err)
	crossdock.Assert(t).Equal(token, pong.Boop, "server said: %v", pong.Boop)
}
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())
}
902795
func (e *ExecutablePlugin) Run(timeout time.Duration) (Response, error) {
	var (
		respReceived bool
		resp         Response
		err          error
		respBytes    []byte
	)

	doneChan := make(chan struct{})
	stdOutScanner := bufio.NewScanner(e.stdout)

	// Start the command and begin reading its output.
	if err = e.cmd.Start(); err != nil {
		return resp, err
	}

	e.captureStderr()
	go func() {
		for {
			for stdOutScanner.Scan() {
				// The first chunk from the scanner is the plugin's response to the
				// handshake.  Once we've received that, we can begin to forward
				// logs on to snapteld's log.
				if !respReceived {
					respBytes = stdOutScanner.Bytes()
					err = json.Unmarshal(respBytes, &resp)
					respReceived = true
					close(doneChan)
				} else {
					execLogger.WithFields(log.Fields{
						"plugin": e.name,
						"io":     "stdout",
					}).Debug(stdOutScanner.Text())
				}
			}

			if errScanner := stdOutScanner.Err(); errScanner != nil {
				reader := bufio.NewReader(e.stdout)
				log, errRead := reader.ReadString('\n')
				if errRead == io.EOF {
					break
				}

				execLogger.
					WithField("plugin", path.Base(e.cmd.Path())).
					WithField("io", "stdout").
					WithField("scanner_err", errScanner).
					WithField("read_string_err", errRead).
					Warn(log)

				continue //scanner finished with errors so try to scan once again
			}
			break //scanner finished scanning without errors so break the loop
		}
	}()

	// Wait until:
	//   a) We receive a signal that the plugin has responded
	// OR
	//   b) The timeout expires
	select {
	case <-doneChan:
	case <-time.After(timeout):
		// We timed out waiting for the plugin's response.  Set err.
		err = fmt.Errorf("timed out waiting for plugin %s", path.Base(e.cmd.Path()))
	}
	if err != nil {
		execLogger.WithFields(log.Fields{
			"received_response": string(respBytes),
		}).Error("error loading plugin")

		// Kill the plugin if we failed to load it.
		e.Kill()
	}
	lowerName := strings.ToLower(resp.Meta.Name)
	if lowerName != resp.Meta.Name {
		execLogger.WithFields(log.Fields{
			"plugin-name":    resp.Meta.Name,
			"plugin-version": resp.Meta.Version,
			"plugin-type":    resp.Type.String(),
		}).Warning("uppercase plugin name")
	}
	resp.Meta.Name = lowerName

	return resp, err
}
21925
func (s *ProxyInfo) Run(ctx context.Context) error {

	statsServer := rpcwrapper.NewRPCWrapper()
	rpcServer := &StatsServer{
		rpchdl:    statsServer,
		collector: s.collector,
		secret:    s.statsServerSecret,
	}

	// Start the server for statistics collection.
	go statsServer.StartServer(ctx, "unix", constants.StatsChannel, rpcServer) // nolint
	return nil
}
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
}
63578
func (sc *syncClient) run() error {
	for {
		select {
		case <-sc.stopped:
			<-sc.start
			log.Infof("Starting sync client...")
		default:
			sc.runOnce()
			select {
			case <-time.After(5 * time.Second):
			case <-sc.quit:
				sc.stopped <- true
			}
		}
	}
}