Must be called when the agent is starting
514299
async def _init_clean(self):
        
        # Data about running containers
        self._containers_running = {}
        self._container_for_job = {}

        self._student_containers_running = {}
        self._student_containers_for_job = {}

        self._containers_killed = dict()

        # Delete tmp_dir, and recreate-it again
        try:
            await self._ashutil.rmtree(self._tmp_dir)
        except OSError:
            pass

        try:
            await self._aos.mkdir(self._tmp_dir)
        except OSError:
            pass

        # Docker
        self._docker = AsyncProxy(DockerInterface())

        # Auto discover containers
        self._logger.info("Discovering containers")
        self._containers = await self._docker.get_containers()

        self._assigned_external_ports = {}  # container_id : [external_ports]

        if self._address_host is None and len(self._containers) != 0:
            self._logger.info("Guessing external host IP")
            self._address_host = await self._docker.get_host_ip(next(iter(self._containers.values()))["id"])
        if self._address_host is None:
            self._logger.warning(
                "Cannot find external host IP. Please indicate it in the configuration. Remote SSH debug has been deactivated.")
            self._external_ports = None
        else:
            self._logger.info("External address for SSH remote debug is %s", self._address_host)

        # Watchers
        self._timeout_watcher = TimeoutWatcher(self._docker)
738726
@InterfaceAudience.Public
    public void start() {

        if (runningState.get() == true) {
            Log.v(Log.TAG_QUERY, "%s: start() called, but runningState is already true.  Ignoring.", this);
            return;
        } else {
            Log.d(Log.TAG_QUERY, "%s: start() called", this);
            runningState.set(true);
        }

        if (!observing) {
            observing = true;
            getDatabase().addChangeListener(this);
            Log.v(Log.TAG_QUERY, "%s: start() is calling update()", this);
            update();
        }
    }
1225508
def ensure_started(self):
        """"""
        if self.active:
            return self
        self._observer = self._observer_class(**self._observer_params)
        self.start()
        self._active = True
        return self
617793
function _doLaunchAfterServerReady(initialDoc) {
        // update status
        _setStatus(STATUS_CONNECTING);
        _createLiveDocumentForFrame(initialDoc);

        // start listening for requests
        _server.start();

        // Install a one-time event handler when connected to the launcher page
        Inspector.one("connect", _onConnect);

        // open browser to the interstitial page to prepare for loading agents
        _openInterstitialPage();

        // Once all agents loaded (see _onInterstitialPageLoad()), begin Live Highlighting for preprocessor documents
        _openDeferred.done(function () {
            // Setup activeEditorChange event listener so that we can track cursor positions in
            // CSS preprocessor files and perform live preview highlighting on all elements with
            // the current selector in the preprocessor file.
            EditorManager.on("activeEditorChange", onActiveEditorChange);

            // Explicitly trigger onActiveEditorChange so that live preview highlighting
            // can be set up for the preprocessor files.
            onActiveEditorChange(null, EditorManager.getActiveEditor(), null);
        });
    }
785876
public function onRunnerStart()
    {
        $rootSuite = Context::getInstance()->getCurrentSuite();
        $rootSuite->getScope()->peridotAddChildScope($this->scope);
    }
150212
public void start(boolean pLazy, String pUrl, boolean pSecured) {
        start(pLazy);

        AgentDetails details = backendManager.getAgentDetails();
        details.setUrl(pUrl);
        details.setSecured(pSecured);
    }
996742
def run(self):
        
        self.logger.debug('initializing agent')
        self.game_interface.load_interface()

        self.prepare_for_run()

        # Create Ratelimiter
        rate_limit = rate_limiter.RateLimiter(GAME_TICK_PACKET_POLLS_PER_SECOND)
        last_tick_game_time = None  # What the tick time of the last observed tick was
        last_call_real_time = datetime.now()  # When we last called the Agent

        # Get bot module
        agent, agent_class_file = self.load_agent()

        last_module_modification_time = os.stat(agent_class_file).st_mtime

        # Run until main process tells to stop, or we detect Ctrl+C
        try:
            while not self.terminate_request_event.is_set():
                self.pull_data_from_game()
                # game_tick_packet = self.game_interface.get
                # Read from game data shared memory

                # Run the Agent only if the game_info has updated.
                tick_game_time = self.get_game_time()
                should_call_while_paused = datetime.now() - last_call_real_time >= MAX_AGENT_CALL_PERIOD
                if tick_game_time != last_tick_game_time or should_call_while_paused:
                    last_tick_game_time = tick_game_time
                    last_call_real_time = datetime.now()

                    # Reload the Agent if it has been modified or if reload is requested from outside.
                    try:
                        new_module_modification_time = os.stat(agent_class_file).st_mtime
                        if new_module_modification_time != last_module_modification_time or self.reload_request_event.is_set():
                            self.reload_request_event.clear()
                            last_module_modification_time = new_module_modification_time
                            # Clear the render queue on reload.
                            if hasattr(agent, 'renderer') and isinstance(agent.renderer, RenderingManager):
                                agent.renderer.clear_all_touched_render_groups()
                            agent, agent_class_file = self.reload_agent(agent, agent_class_file)
                    except FileNotFoundError:
                        self.logger.error(f"Agent file {agent_class_file} was not found. Will try again.")
                        time.sleep(0.5)
                    except Exception:
                        self.logger.error("Reloading the agent failed:\n" + traceback.format_exc())
                        time.sleep(0.5)  # Avoid burning CPU / logs if this starts happening constantly

                    # Call agent
                    try:
                        self.call_agent(agent, self.agent_class_wrapper.get_loaded_class())
                    except Exception as e:
                        self.logger.error("Call to agent failed:\n" + traceback.format_exc())

                # Ratelimit here
                rate_limit.acquire()
        except KeyboardInterrupt:
            self.terminate_request_event.set()

        # Shut down the bot by calling cleanup functions.
        if hasattr(agent, 'retire'):
            try:
                agent.retire()
            except Exception as e:
                self.logger.error("Retiring the agent failed:\n" + traceback.format_exc())
        if hasattr(agent, 'renderer') and isinstance(agent.renderer, RenderingManager):
            agent.renderer.clear_all_touched_render_groups()
        # Zero out the inputs, so it's more obvious that the bot has stopped.
        self.game_interface.update_player_input(PlayerInput(), self.index)
        self.quick_chat_quit_event.set()  # Shut down quick chat.

        # If terminated, send callback
        self.termination_complete_event.set()
565203
def start
      unless config.disable_start_message
        info '[%s] Starting agent, reporting to %s', VERSION, config.server_url
      end

      transport.start
      instrumenter.start
      metrics.start

      config.enabled_spies.each do |lib|
        debug "Requiring spy: #{lib}"
        require "elastic_apm/spies/#{lib}"
      end

      self
    end
259970
async def set_agent(self, msg, context):
        """"""

        service = msg.get('name')
        client = context.user_data

        self.service_manager.set_agent(service, client)
926463
void handleAgentsEvent(AgentsEvent event)
    {
        AsteriskAgentImpl agent = new AsteriskAgentImpl(server,
                event.getName(), "Agent/" + event.getAgent(), AgentState.valueOf(event.getStatus()));
        logger.info("Adding agent " + agent.getName() + "(" + agent.getAgentId() + ")");

        addAgent(agent);
    }
752567
def _callRestartAgent(self, ev_data: RestartLogData, failTimeout) -> None:
        

        logger.info("{}'s restart calling agent for restart".format(self))
        self._actionLog.append_started(ev_data)
        self._action_start_callback()
        self.scheduledAction = None
        asyncio.ensure_future(
            self._sendUpdateRequest(ev_data, failTimeout))
1056011
def restart_agent(self, agent_id, **kwargs):
        ''''''
        host_medium = self.get_medium('host_agent')
        agent = host_medium.get_agent()
        d = host_medium.get_document(agent_id)
        # This is done like this on purpose, we want to ensure that document
        # exists before passing it to the agent (even though he would handle
        # this himself).
        d.addCallback(
            lambda desc: agent.start_agent(desc.doc_id, **kwargs))
        return d
177077
def agent():
  """"""
  agent_module, agent_name = FLAGS.agent.rsplit(".", 1)
  agent_cls = getattr(importlib.import_module(agent_module), agent_name)

  logging.info("Starting agent:")
  with lan_sc2_env.LanSC2Env(
      host=FLAGS.host,
      config_port=FLAGS.config_port,
      race=sc2_env.Race[FLAGS.agent_race],
      step_mul=FLAGS.step_mul,
      agent_interface_format=sc2_env.parse_agent_interface_format(
          feature_screen=FLAGS.feature_screen_size,
          feature_minimap=FLAGS.feature_minimap_size,
          rgb_screen=FLAGS.rgb_screen_size,
          rgb_minimap=FLAGS.rgb_minimap_size,
          action_space=FLAGS.action_space,
          use_feature_units=FLAGS.use_feature_units),
      visualize=FLAGS.render) as env:
    agents = [agent_cls()]
    logging.info("Connected, starting run_loop.")
    try:
      run_loop.run_loop(agents, env)
    except lan_sc2_env.RestartException:
      pass
  logging.info("Done.")
361425
def call_agent_side(self, method, *args, **kwargs):
        '''
        
        '''
        assert not self._finalize_called, ("Attempt to call agent side code "
                                           "after finalize() method has been "
                                           "called. Method: %r" % (method, ))

        ensure_state = kwargs.pop('ensure_state', None)


        d = defer.Deferred(canceller=self._cancel_agent_side_call)
        self._agent_jobs.append(d)
        if ensure_state:
            # call method only if state check is checks in
            d.addCallback(
                lambda _: (self._ensure_state(ensure_state) and
                           method(*args, **kwargs)))
        else:
            d.addCallback(defer.drop_param, method, *args, **kwargs)
        d.addErrback(self._error_handler, method)
        d.addBoth(defer.bridge_param, self._remove_agent_job, d)
        time.call_next(d.callback, None)
        return d
240122
function onRequestCreateAgent(session, channel, message) {
  var agent = agents.createAgent(channel, message.body)
  channel.addAgent(agent)

  channel.sendMessage({
    type:  "response",
    name:  message.name,
    from:  message.to,
    id:    message.id,
    body:  agent.info
  })
}
738066
private void runSelectTask()
  {
    if (_lifecycle.isActive() || _lifecycle.isAfterStopping()) {
      log.warning(this + " cannot start because an instance is active");
      return;
    }

    initNative(_fd);

    synchronized (_thread) {
      _thread.notify();
    }

    if (! _lifecycle.toActive()) {
      log.warning(this + " invalid starting state");
      return;
    }

    runImpl();
  }
462228
public void start()
    {
        Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once");

        service.submit
            (
                new Callable<Object>()
                {
                    @Override
                    public Object call() throws Exception
                    {
                        processEvents();
                        return null;
                    }
                }
            );
    }