Esempio n. 1
0
class SetupManager:
    """
    This class is responsible for pulling together all bits of the framework to
    set up a match between agents.

    A normal order of methods would be:
        connect_to_game()
        load_config()
        launch_ball_prediction()
        launch_bot_processes()
        start_match()
        infinite_loop()
        # the below two might be from another thread
        reload_all_agents()
        shut_down()
    """
    has_started = False
    num_participants = None
    names = None
    teams = None
    python_files = None
    bot_bundles: List[BotConfigBundle] = None
    match_config: MatchConfig = None
    agent_metadata_queue = mp.Queue()
    extension = None
    bot_processes: Dict[int, BotProcessInfo] = {}
    script_processes: Dict[int, subprocess.Popen] = {}

    def __init__(self):
        self.logger = get_logger(DEFAULT_LOGGER)
        self.game_interface = GameInterface(self.logger)
        self.quit_event = mp.Event()
        self.helper_process_manager = HelperProcessManager(self.quit_event)
        self.bot_quit_callbacks = []
        self.bot_reload_requests = []
        self.agent_metadata_map: Dict[int, AgentMetadata] = {}
        self.match_config: MatchConfig = None
        self.rlbot_gateway_process = None
        self.matchcomms_server: MatchcommsServerThread = None
        self.early_start_seconds = 0
        self.num_metadata_received = 0

    def is_rocket_league_running(self, port) -> bool:
        """
        Returns whether Rocket League is running with the right port.
        """

        try:
            is_rocket_league_running, proc = process_configuration.is_process_running(
                ROCKET_LEAGUE_PROCESS_INFO.PROGRAM,
                ROCKET_LEAGUE_PROCESS_INFO.PROGRAM_NAME,
                ROCKET_LEAGUE_PROCESS_INFO.REQUIRED_ARGS)

            if proc is not None:
                # Check for correct port.
                rocket_league_port = self._read_port_from_rocket_league_args(proc.cmdline())
                if rocket_league_port is not None and rocket_league_port != port:
                    raise Exception(f"Rocket League is already running with port {rocket_league_port} but we wanted "
                                    f"{port}! Please close Rocket League and let us start it for you instead!")
        except WrongProcessArgs:
            raise Exception(f"Rocket League is not running with {ROCKET_LEAGUE_PROCESS_INFO.REQUIRED_ARGS}!\n"
                            "Please close Rocket League and let us start it for you instead!")

        return is_rocket_league_running

    def connect_to_game(self, launcher_preference: RocketLeagueLauncherPreference = DEFAULT_LAUNCHER_PREFERENCE):
        """
        Connects to the game by initializing self.game_interface.
        """
        version.print_current_release_notes()
        port = self.ensure_rlbot_gateway_started()

        # Prevent loading game interface twice.
        if self.has_started:
            if not self.is_rocket_league_running(port):
                raise Exception("Rocket League is not running even though we started it once.\n"
                                "Please restart RLBot.")
            return

        # Currently match_config is None when launching from RLBotGUI.
        if self.match_config is not None and self.match_config.networking_role == 'remote_rlbot_client':
            self.logger.info("Will not start Rocket League because this is configured as a client!")
        # Launch the game if it is not running.
        elif not self.is_rocket_league_running(port):
            mergeTASystemSettings()
            self.launch_rocket_league(port=port, launcher_preference=launcher_preference)

        try:
            self.logger.info("Loading interface...")
            # We're not going to use this game_interface for much, just sending start match messages and inspecting
            # the packet to see if the appropriate cars have been spawned.
            self.game_interface.load_interface(
                port=23234, wants_ball_predictions=False, wants_quick_chat=False, wants_game_messages=False)
        except Exception as e:
            self.logger.error("Terminating rlbot gateway and raising:")
            self.rlbot_gateway_process.terminate()
            raise e
        self.has_started = True

    @staticmethod
    def _read_port_from_rocket_league_args(args):
        for arg in args:
            # The arg will look like RLBot_ControllerURL="127.0.0.1:23233"
            if 'RLBot_ControllerURL' in arg:
                rocket_league_port = int(arg.split(':')[1].replace('"', ''))
                return int(rocket_league_port)
        return None

    def launch_rocket_league(self, port, launcher_preference: RocketLeagueLauncherPreference = DEFAULT_LAUNCHER_PREFERENCE):
        """
        Launches Rocket League but does not connect to it.
        """
        ideal_args = ROCKET_LEAGUE_PROCESS_INFO.get_ideal_args(port)

        if launcher_preference.preferred_launcher == RocketLeagueLauncherPreference.EPIC:
            if launcher_preference.use_login_tricks:
                if launch_with_epic_login_trick(ideal_args):
                    return
                else:
                    self.logger.info("Epic login trick seems to have failed, falling back to simple Epic launch.")
            # Fall back to simple if the tricks failed or we opted out of tricks.
            if launch_with_epic_simple(ideal_args):
                return

        # Try launch via Steam.
        steam_exe_path = try_get_steam_executable_path()
        if steam_exe_path:  # Note: This Python 3.8 feature would be useful here https://www.python.org/dev/peps/pep-0572/#abstract
            exe_and_args = [
                str(steam_exe_path),
                '-applaunch',
                str(ROCKET_LEAGUE_PROCESS_INFO.GAMEID),
            ] + ideal_args
            self.logger.info(f'Launching Rocket League with: {exe_and_args}')
            _ = subprocess.Popen(exe_and_args)  # This is deliberately an orphan process.
            return

        self.logger.warning(f'Launching Rocket League using Steam-only fall-back launch method with args: {ideal_args}')
        self.logger.info("You should see a confirmation pop-up, if you don't see it then click on Steam! "
                         'https://gfycat.com/AngryQuickFinnishspitz')
        args_string = '%20'.join(ideal_args)

        # Try launch via terminal (Linux)
        if platform.system() == 'Linux':
            linux_args = [
                'steam',
                f'steam://rungameid/{ROCKET_LEAGUE_PROCESS_INFO.GAMEID}//{args_string}'
            ]

            try:
                _ = subprocess.Popen(linux_args)
                return
            except OSError:
                self.logger.warning('Could not launch Steam executable on Linux.')

        try:
            self.logger.info("Launching rocket league via steam browser URL as a last resort...")
            webbrowser.open(f'steam://rungameid/{ROCKET_LEAGUE_PROCESS_INFO.GAMEID}//{args_string}')
        except webbrowser.Error:
            self.logger.warning(
                'Unable to launch Rocket League. Please launch Rocket League manually using the -rlbot option to continue.')

    def load_match_config(self, match_config: MatchConfig, bot_config_overrides={}):
        """
        Loads the match config into internal data structures, which prepares us to later
        launch bot processes and start the match.

        This is an alternative to the load_config method; they accomplish the same thing.
        """
        self.num_participants = match_config.num_players
        self.names = [bot.name for bot in match_config.player_configs]
        self.teams = [bot.team for bot in match_config.player_configs]

        for player in match_config.player_configs:
            if player.bot and not player.rlbot_controlled and not player.loadout_config:
                set_random_psyonix_bot_preset(player)

        bundles = [bot_config_overrides[index] if index in bot_config_overrides else
                   get_bot_config_bundle(bot.config_path) if bot.config_path else None
                   for index, bot in enumerate(match_config.player_configs)]

        self.python_files = [bundle.python_file if bundle else None
                             for bundle in bundles]

        self.bot_bundles = []

        for index, bot in enumerate(match_config.player_configs):
            self.bot_bundles.append(bundles[index])
            if bot.loadout_config is None and bundles[index]:
                bot.loadout_config = bundles[index].generate_loadout_config(index, bot.team)

        if match_config.extension_config is not None and match_config.extension_config.python_file_path is not None:
            self.load_extension(match_config.extension_config.python_file_path)

        try:
            urlopen("http://google.com")
            checked_environment_requirements = set()
            online = True
        except URLError:
            print("The user is offline, skipping upgrade the bot requirements")
            online = False

        for bundle in self.bot_bundles:
            if bundle is not None and bundle.use_virtual_environment:
                do_post_setup = online

                if do_post_setup:
                    if bundle.requirements_file in checked_environment_requirements:
                        do_post_setup = False
                    else:
                        checked_environment_requirements.add(bundle.requirements_file)

                builder = EnvBuilderWithRequirements(bundle=bundle, do_post_setup=do_post_setup)
                builder.create(Path(bundle.config_directory) / 'venv')

        for script_config in match_config.script_configs:
            script_config_bundle = get_script_config_bundle(script_config.config_path)
            if script_config_bundle.use_virtual_environment:
                do_post_setup = online

                if do_post_setup:
                    if bundle.requirements_file in checked_environment_requirements:
                        do_post_setup = False
                    else:
                        checked_environment_requirements.add(bundle.requirements_file)
                
                builder = EnvBuilderWithRequirements(bundle=script_config_bundle, do_post_setup=do_post_setup)
                builder.create(Path(script_config_bundle.config_directory) / 'venv')

        self.match_config = match_config
        self.game_interface.match_config = match_config
        self.game_interface.start_match_flatbuffer = match_config.create_flatbuffer()

    def load_config(self, framework_config: ConfigObject = None, config_location=DEFAULT_RLBOT_CONFIG_LOCATION,
                    bot_configs=None,
                    looks_configs=None):
        """
        Loads the configuration into internal data structures, which prepares us to later
        launch bot processes and start the match.

        :param framework_config: A config object that indicates what bots to run. May come from parsing a rlbot.cfg.
        :param config_location: The location of the rlbot.cfg file, which will be used to resolve relative paths.
        :param bot_configs: Overrides for bot configurations.
        :param looks_configs: Overrides for looks configurations.
        """
        self.logger.debug('reading the configs')

        # Set up RLBot.cfg
        if framework_config is None:
            framework_config = create_bot_config_layout()
            framework_config.parse_file(config_location, max_index=MAX_PLAYERS)
        if bot_configs is None:
            bot_configs = {}
        if looks_configs is None:
            looks_configs = {}

        match_config = parse_match_config(framework_config, config_location, bot_configs, looks_configs)
        self.load_match_config(match_config, bot_configs)

    def ensure_rlbot_gateway_started(self) -> int:
        """
        Ensures that RLBot.exe is running. Returns the port that it will be listening on for connections from
        Rocket League. Rocket League should be passed a command line argument so that it starts with this same port.
        :return:
        """

        # TODO: Uncomment this when done with local testing of Remote RLBot.
        self.rlbot_gateway_process, port = gateway_util.find_existing_process()
        if self.rlbot_gateway_process is not None:
            self.logger.info(f"Already have RLBot.exe running! Port is {port}")
            return port

        launch_options = LaunchOptions()
        if self.match_config is not None:  # Currently this is None when launching from RLBotGUI.
            networking_role = NetworkingRole[self.match_config.networking_role]
            launch_options = LaunchOptions(
                networking_role=networking_role,
                remote_address=self.match_config.network_address)

        self.rlbot_gateway_process, port = gateway_util.launch(launch_options)
        self.logger.info(f"Python started RLBot.exe with process id {self.rlbot_gateway_process.pid} "
                         f"and port {port}")
        return port

    def launch_ball_prediction(self):
        # This does nothing now. It's kept here temporarily so that RLBotGUI doesn't break.
        pass

    def has_received_metadata_from_all_bots(self):
        expected_metadata_calls = sum(1 for player in self.match_config.player_configs if player.rlbot_controlled)
        return self.num_metadata_received >= expected_metadata_calls

    def launch_early_start_bot_processes(self, match_config: MatchConfig = None):
        """
        Some bots can start up before the game is ready and not be bothered by missing
        or strange looking values in the game tick packet, etc. Such bots can opt in to the
        early start category and enjoy extra time to load up before the match starts.

        WARNING: Early start is a bad idea if there's any risk that bots will not get their promised
        index. This can happen with remote RLBot, etc.
        """

        if self.match_config.networking_role == NetworkingRole.remote_rlbot_client:
            return  # The bot indices are liable to change, so don't start anything yet.

        self.logger.debug("Launching early-start bot processes")
        num_started = self.launch_bot_process_helper(early_starters_only=True, match_config=match_config or self.match_config)
        self.try_recieve_agent_metadata()
        if num_started > 0 and self.early_start_seconds > 0:
            self.logger.info(f"Waiting for {self.early_start_seconds} seconds to let early-start bots load.")
            end_time = datetime.now() + timedelta(seconds=self.early_start_seconds)
            while datetime.now() < end_time:
                self.try_recieve_agent_metadata()
                time.sleep(0.1)

    def launch_bot_processes(self, match_config: MatchConfig = None):
        self.logger.debug("Launching bot processes")
        self.launch_bot_process_helper(early_starters_only=False, match_config=match_config or self.match_config)

    def launch_bot_process_helper(self, early_starters_only=False, match_config: MatchConfig = None):
        # Start matchcomms here as it's only required for the bots.
        if not self.matchcomms_server:
            self.matchcomms_server = launch_matchcomms_server()
        self.bot_processes = {ind: proc for ind, proc in self.bot_processes.items() if proc.is_alive()}

        num_started = 0

        # Launch processes
        # TODO: this might be the right moment to fix the player indices based on a game tick packet.
        if not early_starters_only:
            packet = get_one_packet()

        # TODO: root through the packet and find discrepancies in the player index mapping.
        for i in range(min(self.num_participants, len(match_config.player_configs))):

            player_config = match_config.player_configs[i]
            if not player_config.has_bot_script():
                continue
            if early_starters_only and not self.bot_bundles[i].supports_early_start:
                continue

            spawn_id = player_config.spawn_id

            if early_starters_only:
                # Danger: we have low confidence in this since we're not leveraging the spawn id.
                participant_index = i
            else:
                participant_index = None

                self.logger.info(f'Player in slot {i} was sent with spawn id {spawn_id}, will search in the packet.')
                for n in range(0, packet.PlayersLength()):
                    packet_spawn_id = packet.Players(n).SpawnId()
                    if spawn_id == packet_spawn_id:
                        self.logger.info(f'Looks good, considering participant index to be {n}')
                        participant_index = n
                if participant_index is None:
                    for prox_index, proc_info in self.bot_processes.items():
                        if spawn_id == proc_info.player_config.spawn_id:
                            participant_index = prox_index
                    if participant_index is None:
                        raise Exception(f"Unable to determine the bot index for spawn id {spawn_id}")

            if participant_index not in self.bot_processes:
                bundle = get_bot_config_bundle(player_config.config_path)
                name = str(self.match_config.player_configs[i].deduped_name)
                if bundle.supports_standalone:
                    executable = sys.executable
                    if bundle.use_virtual_environment:
                        executable = str(Path(bundle.config_directory) / 'venv' / 'Scripts' / 'python.exe')
                    process = subprocess.Popen([
                        executable,
                        bundle.python_file,
                        '--config-file', str(player_config.config_path),
                        '--name', name,
                        '--team', str(self.teams[i]),
                        '--player-index', str(participant_index),
                        '--spawn-id', str(spawn_id),
                        '--matchcomms-url', self.matchcomms_server.root_url.geturl()
                    ], cwd=Path(bundle.config_directory).parent)
                    self.bot_processes[participant_index] = BotProcessInfo(process=None, subprocess=process, player_config=player_config)

                    # Insert immediately into the agent metadata map because the standalone process has no way to communicate it back out
                    self.agent_metadata_map[participant_index] = AgentMetadata(participant_index, name, self.teams[i], {process.pid})
                else:
                    reload_request = mp.Event()
                    quit_callback = mp.Event()
                    self.bot_reload_requests.append(reload_request)
                    self.bot_quit_callbacks.append(quit_callback)
                    process = mp.Process(target=SetupManager.run_agent,
                                         args=(self.quit_event, quit_callback, reload_request, self.bot_bundles[i],
                                               name,
                                               self.teams[i], participant_index, self.python_files[i], self.agent_metadata_queue,
                                               match_config, self.matchcomms_server.root_url, spawn_id))
                    process.start()
                    self.bot_processes[participant_index] = BotProcessInfo(process=process, subprocess=None, player_config=player_config)
                num_started += 1

        self.logger.info(f"Successfully started {num_started} bot processes")

        process_configuration.configure_processes(self.agent_metadata_map, self.logger)

        scripts_started = 0
        for script_config in match_config.script_configs:
            script_config_bundle = get_script_config_bundle(script_config.config_path)
            if early_starters_only and not script_config_bundle.supports_early_start:
                continue
            executable = sys.executable
            if script_config_bundle.use_virtual_environment:
                executable = str(Path(script_config_bundle.config_directory) / 'venv' / 'Scripts' / 'python.exe')

            process = subprocess.Popen(
                [
                    executable,
                    script_config_bundle.script_file, 
                    '--matchcomms-url', self.matchcomms_server.root_url.geturl()
                ],
                cwd=Path(script_config_bundle.config_directory).parent
            )
            self.logger.info(f"Started script with pid {process.pid} using {process.args}")
            self.script_processes[process.pid] = process
            scripts_started += 1

        self.logger.debug(f"Successfully started {scripts_started} scripts")

        return num_started

    def launch_quick_chat_manager(self):
        # Quick chat manager is gone since we're using RLBot.exe now.
        # Keeping this function around for backwards compatibility.
        pass

    def start_match(self):

        if self.match_config.networking_role == NetworkingRole.remote_rlbot_client:
            match_settings = self.game_interface.get_match_settings()
            # TODO: merge the match settings into self.match_config
            # And then make sure we still only start the appropriate bot processes
            # that we originally asked for.

        self.logger.info("Python attempting to start match.")
        self.game_interface.start_match()
        self.game_interface.wait_until_valid_packet()
        self.logger.info("Match has started")

        cleanUpTASystemSettings()

    def infinite_loop(self):
        instructions = "Press 'r' to reload all agents, or 'q' to exit"
        self.logger.info(instructions)
        while not self.quit_event.is_set():
            # Handle commands
            # TODO windows only library
            if platform.system() == 'Windows':
                if msvcrt.kbhit():
                    command = msvcrt.getwch()
                    if command.lower() == 'r':  # r: reload
                        self.reload_all_agents()
                    elif command.lower() == 'q' or command == '\u001b':  # q or ESC: quit
                        self.shut_down()
                        break
                    # Print instructions again if a alphabet character was pressed but no command was found
                    elif command.isalpha():
                        self.logger.info(instructions)
            else:
                try:
                    # https://python-forum.io/Thread-msvcrt-getkey-for-linux
                    import termios, sys
                    TERMIOS = termios

                    fd = sys.stdin.fileno()
                    old = termios.tcgetattr(fd)
                    new = termios.tcgetattr(fd)
                    new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO
                    new[6][TERMIOS.VMIN] = 1
                    new[6][TERMIOS.VTIME] = 0
                    termios.tcsetattr(fd, TERMIOS.TCSANOW, new)
                    command = None
                    try:
                        command = os.read(fd, 1)
                    finally:
                        termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)
                    command = command.decode("utf-8")
                    if command.lower() == 'r':  # r: reload
                        self.reload_all_agents()
                    elif command.lower() == 'q' or command == '\u001b':  # q or ESC: quit
                        self.shut_down()
                        break
                    # Print instructions again if a alphabet character was pressed but no command was found
                    elif command.isalpha():
                        self.logger.info(instructions)
                except:
                    pass

            self.try_recieve_agent_metadata()

    def try_recieve_agent_metadata(self):
        """
        Checks whether any of the started bots have posted their AgentMetadata
        yet. If so, we put them on the agent_metadata_map such that we can
        kill their process later when we shut_down(kill_agent_process_ids=True)

        Returns how from how many bots we received metadata from.
        """
        num_recieved = 0
        while True:  # will exit on queue.Empty
            try:
                single_agent_metadata: AgentMetadata = self.agent_metadata_queue.get(timeout=0.1)
                num_recieved += 1
                self.helper_process_manager.start_or_update_helper_process(single_agent_metadata)
                self.agent_metadata_map[single_agent_metadata.index] = single_agent_metadata
                process_configuration.configure_processes(self.agent_metadata_map, self.logger)
            except queue.Empty:
                self.num_metadata_received += num_recieved
                return num_recieved

    def reload_all_agents(self, quiet=False):
        if not quiet:
            self.logger.info("Reloading all agents...")
        for rr in self.bot_reload_requests:
            rr.set()

    def shut_down(self, time_limit=5, kill_all_pids=False, quiet=False):
        if not quiet:
            self.logger.info("Shutting Down")

        self.quit_event.set()
        end_time = datetime.now() + timedelta(seconds=time_limit)

        # Don't kill RLBot.exe. It needs to keep running because if we're in a GUI
        # that will persist after this shut down, the interface dll in charge of starting
        # matches is already locked in to its shared memory files, and if we start a new
        # RLBot.exe, those files will go stale. https://github.com/skyborgff/RLBot/issues/9

        # Wait for all processes to terminate before terminating main process
        terminated = False
        while not terminated:
            terminated = True
            for callback in self.bot_quit_callbacks:
                if not callback.is_set():
                    terminated = False
            time.sleep(0.1)
            if datetime.now() > end_time:
                self.logger.info("Taking too long to quit, trying harder...")
                break

        self.kill_bot_processes()
        self.kill_agent_process_ids(set(self.script_processes.keys()))

        if kill_all_pids:
            # The original meaning of the kill_all_pids flag only applied to bots, not scripts,
            # so we are doing that separately.
            self.kill_agent_process_ids(process_configuration.extract_all_pids(self.agent_metadata_map))

        self.kill_matchcomms_server()

        # The quit event can only be set once. Let's reset to our initial state
        self.quit_event = mp.Event()
        self.helper_process_manager = HelperProcessManager(self.quit_event)

        if not quiet:
            self.logger.info("Shut down complete!")

    def load_extension(self, extension_filename):
        try:
            extension_class = import_class_with_base(extension_filename, BaseExtension).get_loaded_class()
            self.extension = extension_class(self)
            self.game_interface.set_extension(self.extension)
        except FileNotFoundError as e:
            print(f'Failed to load extension: {e}')

    @staticmethod
    def run_agent(terminate_event, callback_event, reload_request, bundle: BotConfigBundle, name, team, index,
                  python_file, agent_telemetry_queue, match_config: MatchConfig, matchcomms_root: URL, spawn_id: str):

        # Set the working directory to one level above the bot cfg file.
        # This mimics the behavior you get when executing run.py in one of the
        # example bot repositories, so bots will be more likely to 'just work'
        # even if the developer is careless about file paths.
        os.chdir(Path(bundle.config_directory).parent)

        agent_class_wrapper = import_agent(python_file)
        config_file = agent_class_wrapper.get_loaded_class().base_create_agent_configurations()
        config_file.parse_file(bundle.config_obj, config_directory=bundle.config_directory)

        if hasattr(agent_class_wrapper.get_loaded_class(), "run_independently"):
            bm = BotManagerIndependent(terminate_event, callback_event, reload_request, config_file, name, team, index,
                                       agent_class_wrapper, agent_telemetry_queue, match_config, matchcomms_root,
                                       spawn_id)
        else:
            bm = BotManagerStruct(terminate_event, callback_event, reload_request, config_file, name, team, index,
                                  agent_class_wrapper, agent_telemetry_queue, match_config, matchcomms_root, spawn_id)
        bm.run()

    def kill_bot_processes(self):
        for process_info in self.bot_processes.values():
            proc = process_info.process or process_info.subprocess
            proc.terminate()
        for process_info in self.bot_processes.values():
            if process_info.process:
                process_info.process.join(timeout=1)
        self.bot_processes.clear()
        self.num_metadata_received = 0

    def kill_agent_process_ids(self, pids: Set[int]):
        for pid in pids:
            try:
                parent = psutil.Process(pid)
                for child in parent.children(recursive=True):  # or parent.children() for recursive=False
                    self.logger.info(f"Killing {child.pid} (child of {pid})")
                    try:
                        child.kill()
                    except psutil.NoSuchProcess:
                        self.logger.info("Already dead.")
                self.logger.info(f"Killing {pid}")
                try:
                    parent.kill()
                except psutil.NoSuchProcess:
                    self.logger.info("Already dead.")
            except psutil.NoSuchProcess:
                self.logger.info("Can't fetch parent process, already dead.")
            except psutil.AccessDenied as ex:
                self.logger.error(f"Access denied when trying to kill a bot pid! {ex}")
            except Exception as ex:
                self.logger.error(f"Unexpected exception when trying to kill a bot pid! {ex}")

    def kill_matchcomms_server(self):
        if self.matchcomms_server:
            self.matchcomms_server.close()
            self.matchcomms_server = None
Esempio n. 2
0
class BotManager:
    def __init__(self, terminate_request_event, termination_complete_event,
                 reload_request_event, bot_configuration, name, team, index,
                 agent_class_wrapper, agent_metadata_queue,
                 match_config: MatchConfig, matchcomms_root: URL,
                 spawn_id: int):
        """
        :param terminate_request_event: an Event (multiprocessing) which will be set from the outside when the program is trying to terminate
        :param termination_complete_event: an Event (multiprocessing) which should be set from inside this class when termination has completed successfully
        :param reload_request_event: an Event (multiprocessing) which will be set from the outside to force a reload of the agent
        :param reload_complete_event: an Event (multiprocessing) which should be set from inside this class when reloading has completed successfully
        :param bot_configuration: parameters which will be passed to the bot's constructor
        :param name: name which will be passed to the bot's constructor. Will probably be displayed in-game.
        :param team: 0 for blue team or 1 for orange team. Will be passed to the bot's constructor.
        :param index: The player index, i.e. "this is player number <index>". Will be passed to the bot's constructor.
            Can be used to pull the correct data corresponding to the bot's car out of the game tick packet.
        :param agent_class_wrapper: The ExternalClassWrapper object that can be used to load and reload the bot
        :param agent_metadata_queue: a Queue (multiprocessing) which expects to receive AgentMetadata once available.
        :param match_config: Describes the match that is being played.
        :param matchcomms_root: The server to connect to if you want to communicate to other participants in the match.
        :param spawn_id: The identifier we expect to see in the game tick packet at our player index. If it does not
            match, then we will force the agent to retire. Pass None to opt out of this behavior.
        """
        self.terminate_request_event = terminate_request_event
        self.termination_complete_event = termination_complete_event
        self.reload_request_event = reload_request_event
        self.bot_configuration = bot_configuration
        self.name = name
        self.team = team
        self.index = index
        self.agent_class_wrapper = agent_class_wrapper
        self.agent_metadata_queue = agent_metadata_queue
        self.logger = get_logger('bot' + str(self.index))
        self.game_interface = GameInterface(self.logger)
        self.last_chat_time = time.time()
        self.chat_counter = 0
        self.reset_chat_time = True
        self.game_tick_packet = None
        self.bot_input = None
        self.ball_prediction = None
        self.rigid_body_tick = None
        self.match_config = match_config
        self.matchcomms_root = matchcomms_root
        self.last_message_index = 0
        self.agent = None
        self.agent_class_file = None
        self.last_module_modification_time = 0
        self.scan_last = 0
        self.scan_temp = 0
        self.file_iterator = None
        self.maximum_tick_rate_preference = bot_configuration.get(
            BOT_CONFIG_MODULE_HEADER, MAXIMUM_TICK_RATE_PREFERENCE_KEY)
        self.spawn_id = spawn_id
        self.counter = 0

    def send_quick_chat_from_agent(self, team_only, quick_chat):
        """
        Passes the agents quick chats to the game, and also to other python bots.
        This does perform limiting.
        You are limited to 5 quick chats in a 2 second period starting from the first chat.
        This means you can spread your chats out to be even within that 2 second period.
        You could spam them in the first little bit but then will be throttled.
        """

        # Send the quick chat to the game
        rlbot_status = send_quick_chat_flat(self.game_interface, self.index,
                                            self.team, team_only, quick_chat)

        if rlbot_status == RLBotCoreStatus.QuickChatRateExceeded:
            self.logger.debug('quick chat disabled')

    def load_agent(self):
        """
        Loads and initializes an agent using instance variables, registers for quick chat and sets render functions.
        :return: An instance of an agent, and the agent class file.
        """
        agent_class = self.agent_class_wrapper.get_loaded_class()
        self.agent = agent_class(self.name, self.team, self.index)
        self.agent.init_match_config(self.match_config)

        self.agent.load_config(
            self.bot_configuration.get_header("Bot Parameters"))

        self.update_metadata_queue()
        self.set_render_manager()

        self.agent_class_file = self.agent_class_wrapper.python_file
        self.agent._register_quick_chat(self.send_quick_chat_from_agent)
        self.agent._register_field_info(self.get_field_info)
        self.agent._register_set_game_state(self.set_game_state)
        self.agent._register_ball_prediction(self.get_ball_prediction)
        self.agent._register_ball_prediction_struct(
            self.get_ball_prediction_struct)
        self.agent._register_get_rigid_body_tick(self.get_rigid_body_tick)
        self.agent._register_match_settings_func(self.get_match_settings)
        self.agent.matchcomms_root = self.matchcomms_root

        # Once all engine setup is done, do the agent-specific initialization, if any:
        self.agent.initialize_agent()
        return self.agent, self.agent_class_file

    def set_render_manager(self):
        """
        Sets the render manager for the agent.
        :param agent: An instance of an agent.
        """
        rendering_manager = self.game_interface.renderer.get_rendering_manager(
            self.index, self.team)
        self.agent._set_renderer(rendering_manager)

    def update_metadata_queue(self):
        """
        Adds a new instance of AgentMetadata into the `agent_metadata_queue` using `agent` data.
        :param agent: An instance of an agent.
        """
        pids = {os.getpid(), *self.agent.get_extra_pids()}

        helper_process_request = self.agent.get_helper_process_request()

        self.agent_metadata_queue.put(
            AgentMetadata(self.index, self.name, self.team, pids,
                          helper_process_request))

    def reload_agent(self):
        """
        Reloads the agent. Can throw exceptions. External classes should use reload_event.set() instead.
        """
        self.logger.info('Reloading Agent: ' + self.agent.name)
        self.agent_class_wrapper.reload()
        old_agent = self.agent
        self.load_agent()
        self.retire_agent(
            old_agent)  # We do this after load_agent as load_agent might fail.

    def run(self):
        """
        Loads interface for RLBot, prepares environment and agent, and calls the update for the agent.
        """
        self.logger.debug('initializing agent')
        self.game_interface.load_interface()

        self.prepare_for_run()

        last_tick_game_time = 0  # What the tick time of the last observed tick was
        last_call_real_time = datetime.now()  # When we last called the Agent
        frame_urgency = 0  # If the bot is getting called more than its preferred max rate, urgency will go negative.

        # Get bot module
        self.load_agent()

        self.last_module_modification_time = self.check_modification_time(
            os.path.dirname(self.agent_class_file))

        # 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()

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

                if frame_urgency < 1 / self.maximum_tick_rate_preference:
                    # Urgency increases every frame, but don't let it build up a large backlog
                    frame_urgency += tick_game_time - last_tick_game_time

                if tick_game_time != last_tick_game_time and frame_urgency >= 0 or should_call_while_paused:
                    last_call_real_time = now
                    # Urgency decreases when a tick is processed.
                    if frame_urgency > 0:
                        frame_urgency -= 1 / self.maximum_tick_rate_preference

                    self.perform_tick()
                    self.counter += 1

                last_tick_game_time = tick_game_time
                if self.spawn_id is not None:
                    packet_spawn_id = self.get_spawn_id()
                    if packet_spawn_id != self.spawn_id:
                        self.logger.warn(
                            f"The bot's spawn id {self.spawn_id} does not match the one in the packet "
                            f"{packet_spawn_id}, retiring!")
                        break

        except KeyboardInterrupt:
            self.terminate_request_event.set()

        self.retire_agent(self.agent)

        # If terminated, send callback
        self.termination_complete_event.set()

    def perform_tick(self):
        # Reload the Agent if it has been modified or if reload is requested from outside.
        # But only do that every 20th tick.
        if self.agent.is_hot_reload_enabled() and self.counter % 20 == 1:
            self.hot_reload_if_necessary()
        try:
            chat_messages = self.game_interface.receive_chat(
                self.index, self.team, self.last_message_index)
            for i in range(0, chat_messages.MessagesLength()):
                message = chat_messages.Messages(i)
                if len(self.match_config.player_configs) > message.PlayerIndex(
                ):
                    self.agent.handle_quick_chat(
                        index=message.PlayerIndex(),
                        team=self.match_config.player_configs[
                            message.PlayerIndex()].team,
                        quick_chat=message.QuickChatSelection())
                else:
                    self.logger.debug(
                        f"Skipping quick chat delivery for {message.MessageIndex()} because "
                        "we don't recognize the player index. Probably stale.")
                self.last_message_index = message.MessageIndex()
        except EmptyDllResponse:
            self.logger.debug("Empty response when reading chat!")
        # Call agent
        try:
            self.call_agent(self.agent,
                            self.agent_class_wrapper.get_loaded_class())
        except Exception as e:
            self.logger.error("Call to agent failed:\n" +
                              traceback.format_exc())

    def hot_reload_if_necessary(self):
        try:
            new_module_modification_time = self.check_modification_time(
                os.path.dirname(self.agent_class_file))
            if new_module_modification_time != self.last_module_modification_time or self.reload_request_event.is_set(
            ):
                self.reload_request_event.clear()
                self.last_module_modification_time = new_module_modification_time
                # Clear the render queue on reload.
                if hasattr(self.agent, 'renderer') and isinstance(
                        self.agent.renderer, RenderingManager):
                    self.agent.renderer.clear_all_touched_render_groups()
                self.reload_agent()
        except FileNotFoundError:
            self.logger.error(
                f"Agent file {self.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(
                5
            )  # Avoid burning CPU, and give the user a moment to read the log

    def retire_agent(self, agent):
        # 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)

        # Don't trust the agent to shut down its own client in retire().
        if agent._matchcomms is not None:
            agent._matchcomms.close()

    def check_modification_time(self, directory, timeout_ms=1):
        if self.scan_last > 0 and timeout_ms is not None:
            stop_time = time.perf_counter_ns() + timeout_ms * 10**6
        else:
            stop_time = None
        if self.file_iterator is None:
            self.file_iterator = glob.iglob(f"{directory}/**/*.py",
                                            recursive=True)
        for f in self.file_iterator:
            self.scan_temp = max(self.scan_temp, os.stat(f).st_mtime)
            if stop_time is not None and time.perf_counter_ns() > stop_time:
                # Timeout exceeded. The scan will pick up from here on the next call.
                break
        else:
            # Scan finished. Update the modification time and restart the scan:
            self.scan_last, self.scan_temp = self.scan_temp, 0
            self.file_iterator = None
        return self.scan_last

    def get_field_info(self):
        return self.game_interface.get_field_info()

    def get_rigid_body_tick(self):
        """Get the most recent state of the physics engine."""
        return self.game_interface.update_rigid_body_tick(self.rigid_body_tick)

    def set_game_state(self, game_state: GameState) -> None:
        self.game_interface.set_game_state(game_state)

    def get_ball_prediction(self):
        return self.game_interface.get_ball_prediction()

    def get_match_settings(self) -> MatchSettings:
        return self.game_interface.get_match_settings()

    def get_ball_prediction_struct(self):
        raise NotImplementedError

    def prepare_for_run(self):
        raise NotImplementedError

    def call_agent(self, agent: BaseAgent, agent_class):
        raise NotImplementedError

    def get_game_time(self):
        raise NotImplementedError

    def pull_data_from_game(self):
        raise NotImplementedError

    def get_spawn_id(self):
        raise NotImplementedError