// StarBot starts a bot, which runs a users code in the container built for their language
// @returns error if client fails to start the bot pod
189938
func (kc *KubeClient) StartBot(ip string, botID int32, proj *models.Project, game *models.Game) (*api.Pod, error) {
	pod := createBotPod(ip, botID, proj, game)
	log.Printf("Starting bot! Spec:\n%v", pod)
	return kc.client.Pods(api.NamespaceDefault).Create(pod)
}
858951
func (s *CreateSimulationApplicationInput) SetRobotSoftwareSuite(v *RobotSoftwareSuite) *CreateSimulationApplicationInput {
	s.RobotSoftwareSuite = v
	return s
}
784470
func (s *UpdateSimulationApplicationInput) SetRobotSoftwareSuite(v *RobotSoftwareSuite) *UpdateSimulationApplicationInput {
	s.RobotSoftwareSuite = v
	return s
}
479810
func runAPIService(cmd *cobra.Command, args []string) (exit int) {
	// Set up the signal handler here so we can make sure the
	// signals are caught after print the starting message.
	signal.Notify(exitCh, syscall.SIGINT, syscall.SIGTERM)

	stderr.Print("API service starting...")

	listeners, err := openAPISockets()
	if err != nil {
		stderr.PrintE("Failed to open sockets", err)
		return 254
	}
	if len(listeners) == 0 { // This is unlikely...
		stderr.Println("No sockets to listen to. Quitting.")
		return 254
	}

	publicServer := grpc.NewServer() // TODO(yifan): Add TLS credential option.

	v1AlphaAPIServer, err := newV1AlphaAPIServer()
	if err != nil {
		stderr.PrintE("failed to create API service", err)
		return 254
	}

	v1alpha.RegisterPublicAPIServer(publicServer, v1AlphaAPIServer)

	for _, l := range listeners {
		defer l.Close()
		go publicServer.Serve(l)
	}

	stderr.Printf("API service running")

	<-exitCh

	stderr.Print("API service exiting...")

	return
}
571196
func (robot *Robot) Run() error {
	Logger.Info("starting robot")

	// HACK
	Logger.Debugf("opening %s store connection", Config.StoreName)
	go func() {
		robot.Store.Open()

		Logger.Debug("loading users from store")
		robot.Users.Load()
	}()

	Logger.Debugf("starting %s adapter", Config.AdapterName)
	go robot.Adapter.Run()

	// Start the HTTP server after the adapter, as adapter.Run() adds additional
	// handlers to the router.
	Logger.Debug("starting HTTP server")
	go func() {
		if err := http.ListenAndServe(`:`+strconv.Itoa(Config.Port), Router); err != nil {
			Logger.Debug(err)
		}
	}()

	signal.Notify(robot.signalChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)

	stop := false
	for !stop {
		select {
		case sig := <-robot.signalChan:
			switch sig {
			case syscall.SIGINT, syscall.SIGTERM:
				stop = true
			}
		}
	}
	// Stop listening for new signals
	signal.Stop(robot.signalChan)

	// Initiate the shutdown process for our robot
	robot.Stop()

	return nil
}
289623
func (r *Robot) Start(args ...interface{}) (err error) {
	if len(args) > 0 && args[0] != nil {
		r.AutoRun = args[0].(bool)
	}
	log.Println("Starting Robot", r.Name, "...")
	if cerr := r.Connections().Start(); cerr != nil {
		err = multierror.Append(err, cerr)
		log.Println(err)
		return
	}
	if derr := r.Devices().Start(); derr != nil {
		err = multierror.Append(err, derr)
		log.Println(err)
		return
	}
	if r.Work == nil {
		r.Work = func() {}
	}

	log.Println("Starting work...")
	go func() {
		r.Work()
		<-r.done
	}()

	r.running.Store(true)
	if r.AutoRun {
		c := make(chan os.Signal, 1)
		r.trap(c)

		// waiting for interrupt coming on the channel
		<-c

		// Stop calls the Stop method on itself, if we are "auto-running".
		r.Stop()
	}

	return
}
690277
func (a *API) robots(res http.ResponseWriter, req *http.Request) {
	jsonRobots := []*gobot.JSONRobot{}
	a.master.Robots().Each(func(r *gobot.Robot) {
		jsonRobots = append(jsonRobots, gobot.NewJSONRobot(r))
	})
	a.writeJSON(map[string]interface{}{"robots": jsonRobots}, res)
}
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})
				}

			}
		}
	}
}
516524
func (bot *ExchangeBot) Start(ctx context.Context, wg *sync.WaitGroup) {
	tick := time.NewTimer(time.Second)

	config := bot.config

	reconnectionAttempt := 0

	if config.MasterBot != "" {
		stream, err := bot.connectMasterBot(ctx, 0)
		if err != nil {
			log.Errorf("Failed to initialize gRPC stream. Falling back to direct connection: %v", err)
		} else {
			// Drain the timer to prevent the first cycle
			if !tick.Stop() {
				<-tick.C
			}
			// Start a loop to listen for updates from the dcrrates server.
			go func() {
				for {
					update, err := stream.Recv()
					if err != nil {
						if ctx.Err() != nil {
							return
						}
						log.Errorf("DCRRates error. Attempting to reconnect in 10 seconds: %v", err)
						delay := 10 * time.Second
						delayString := "10 seconds"
						// Try to reconnect every minute until a connection is made.
						for {
							reconnectionAttempt++
							stream, err = bot.connectMasterBot(ctx, delay)
							if err == nil {
								break
							} else {
								if ctx.Err() != nil {
									return
								}
								if reconnectionAttempt > 12 { // ~ two minutes
									delay = time.Minute
									delayString = "1 minute"
								}
								log.Errorf("Failed to reconnect to DCRRates. Attempting to reconnect in %s: %v", delayString, err)
							}
						}
						log.Infof("DCRRates connection re-established.")
						reconnectionAttempt = 0
						continue
					}
					// Send the update through the Exchange so that appropriate attributes
					// are set.
					if IsDcrExchange(update.Token) {
						state := exchangeStateFromProto(update)
						bot.Exchanges[update.Token].Update(state)
					} else if IsBtcIndex(update.Token) {
						bot.Exchanges[update.Token].UpdateIndices(update.GetIndices())
					}
				}
			}()
		}
	} // End DCRRates master
	if bot.masterConnection == nil {
		// Start refresh on all exchanges, and then change the updateTimes to
		// de-sync the updates.
		timeBetween := bot.DataExpiry / time.Duration(len(bot.Exchanges))
		idx := 0
		for _, xc := range bot.Exchanges {
			go func(xc Exchange, d int) {
				xc.Refresh()
				if !xc.IsFailed() {
					xc.Hurry(timeBetween * time.Duration(d))
				}
			}(xc, idx)
			idx++
		}
	}

out:
	for {
		select {
		case update := <-bot.exchangeChan:
			err := bot.updateExchange(update)
			if err != nil {
				log.Warnf("Error encountered in exchange update: %v", err)
				continue
			}
			bot.signalExchangeUpdate(update)
		case update := <-bot.indexChan:
			err := bot.updateIndices(update)
			if err != nil {
				log.Warnf("Error encountered in index update: %v", err)
				continue
			}
			bot.signalIndexUpdate(update)
		case <-tick.C:
			bot.Cycle()
		case <-ctx.Done():
			break out
		}
		if bot.masterConnection == nil {
			tick = bot.nextTick()
		}
	}
	if wg != nil {
		wg.Done()
	}
	bot.mtx.RLock()
	defer bot.mtx.RUnlock()
	for _, ch := range bot.quitChans {
		close(ch)
	}
	if bot.masterConnection != nil {
		bot.masterConnection.Close()
	}
}
919314
func SetUp(c *Config) *bot.Bot {
	config = c

	ircConn = ircevent.IRC(c.User, c.Nick)
	ircConn.RealName = c.RealName
	ircConn.Password = c.Password
	ircConn.UseTLS = c.UseTLS
	ircConn.TLSConfig = &tls.Config{
		ServerName: getServerName(c.Server),
	}
	ircConn.VerboseCallbackHandler = c.Debug

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

	ircConn.AddCallback("001", onWelcome)
	ircConn.AddCallback("PRIVMSG", onPRIVMSG)
	ircConn.AddCallback("CTCP_ACTION", onCTCPACTION)

	return b
}
561645
func processBot(c context.Context, desc model.PoolDescriptor) error {
	t, err := auth.GetRPCTransport(c, auth.AsSelf)
	if err != nil {
		return err
	}
	sc, err := swarmingAPI.New(&http.Client{Transport: t})
	if err != nil {
		return err
	}
	sc.BasePath = fmt.Sprintf("https://%s/_ah/api/swarming/v1/", desc.Host())

	var bots []model.Bot
	bl := sc.Bots.List().Dimensions(desc.Dimensions().Format()...)
	// Keep fetching until the cursor is empty.
	for {
		botList, err := bl.Do()
		if err != nil {
			return err
		}
		for _, botInfo := range botList.Items {
			// Ignore deleted bots.
			if botInfo.Deleted {
				continue
			}
			bot, err := parseBot(c, desc.Host(), botInfo)
			if err != nil {
				return err
			}
			bots = append(bots, *bot)
		}

		if botList.Cursor == "" {
			break
		}
		bl = bl.Cursor(botList.Cursor)
	}
	// If there are too many bots, then it won't fit in datastore.
	// Only store a subset of the bots.
	// TODO(hinoka): This is inaccurate, but will only affect few builders.
	// Instead of chopping this list off, just store the statistics.
	if len(bots) > 1000 {
		bots = bots[:1000]
	}
	// This is a large RPC, don't try to batch it.
	return datastore.Put(c, &model.BotPool{
		PoolID:     desc.PoolID(),
		Descriptor: desc,
		Bots:       bots,
		LastUpdate: clock.Now(c),
	})
}
1321864
func terminateBotAsync(c context.Context, id, hostname string) error {
	t := &tq.Task{
		Payload: &tasks.TerminateBot{
			Id:       id,
			Hostname: hostname,
		},
	}
	if err := getDispatcher(c).AddTask(c, t); err != nil {
		return errors.Annotate(err, "failed to schedule terminate task").Err()
	}
	return nil
}
1284285
func NewJSONRobot(robot *Robot) *JSONRobot {
	jsonRobot := &JSONRobot{
		Name:        robot.Name,
		Commands:    []string{},
		Connections: []*JSONConnection{},
		Devices:     []*JSONDevice{},
	}

	for command := range robot.Commands() {
		jsonRobot.Commands = append(jsonRobot.Commands, command)
	}

	robot.Devices().Each(func(device Device) {
		jsonDevice := NewJSONDevice(device)
		jsonRobot.Connections = append(jsonRobot.Connections, NewJSONConnection(robot.Connection(jsonDevice.Connection)))
		jsonRobot.Devices = append(jsonRobot.Devices, jsonDevice)
	})
	return jsonRobot
}
908134
func (s *RegisterRobotInput) SetRobot(v string) *RegisterRobotInput {
	s.Robot = &v
	return s
}
264614
func (r *ServerService) GetBotConfig() *ServerGetBotConfigCall {
	c := &ServerGetBotConfigCall{s: r.s, urlParams_: make(gensupport.URLParams)}
	return c
}
446210
func (g *Master) AddRobot(r *Robot) *Robot {
	*g.robots = append(*g.robots, r)
	return r
}
288675
func (p *UserAgent) checkBot(sections []section) {
	// If there's only one element, and it's doesn't have the Mozilla string,
	// check whether this is a bot or not.
	if len(sections) == 1 && sections[0].name != "Mozilla" {
		p.mozilla = ""

		// Check whether the name has some suspicious "bot" or "crawler" in his name.
		if botRegex.Match([]byte(sections[0].name)) {
			p.setSimple(sections[0].name, "", true)
			return
		}

		// Tough luck, let's try to see if it has a website in his comment.
		if name := getFromSite(sections[0].comment); name != "" {
			// First of all, this is a bot. Moreover, since it doesn't have the
			// Mozilla string, we can assume that the name and the version are
			// the ones from the first section.
			p.setSimple(sections[0].name, sections[0].version, true)
			return
		}

		// At this point we are sure that this is not a bot, but some weirdo.
		p.setSimple(sections[0].name, sections[0].version, false)
	} else {
		// Let's iterate over the available comments and check for a website.
		for _, v := range sections {
			if name := getFromSite(v.comment); name != "" {
				// Ok, we've got a bot name.
				results := strings.SplitN(name, "/", 2)
				version := ""
				if len(results) == 2 {
					version = results[1]
				}
				p.setSimple(results[0], version, true)
				return
			}
		}

		// We will assume that this is some other weird browser.
		p.fixOther(sections)
	}
}