Bedrock Server Manager Core Documentation

class bedrock_server_manager.BedrockServerManager

Bases: object

Manages global application settings, server discovery, and application-wide data.

The BedrockServerManager serves as the primary high-level interface for operations that affect the Bedrock Server Manager application globally or span multiple server instances. It is distinct from the BedrockServer class, which handles the specifics of individual server instances.

Key Responsibilities:

  • Providing access to and management of global application settings through an aggregated Settings object.

  • Discovering server instances within the configured base directory and validating their installations.

  • Managing a central player database (players.json), including parsing player data and consolidating information from server logs.

  • Controlling the Web UI application’s lifecycle, including managing its system service (Systemd for Linux, Windows Service for Windows).

  • Listing globally available content files (e.g., .mcworld templates, .mcaddon/.mcpack addons) from the content directory.

  • Checking and reporting on system capabilities (e.g., availability of task schedulers or service managers).

An instance of this class is typically created once per application run. It initializes by loading or accepting a Settings instance and sets up paths based on this configuration. For operations that require interaction with a specific server (like scanning its logs), it will internally instantiate a BedrockServer object.

settings

The application’s global settings object.

Type:

Settings

capabilities

A dictionary indicating the availability of system features like ‘scheduler’ and ‘service_manager’.

Type:

Dict[str, bool]

_config_dir

Absolute path to the application’s configuration directory.

Type:

str

_app_data_dir

Absolute path to the application’s data directory.

Type:

str

_base_dir

Absolute path to the base directory where server installations are stored. Based on settings['paths.servers'].

Type:

Optional[str]

_content_dir

Absolute path to the directory for global content like world templates and addons. Based on settings['paths.content'].

Type:

Optional[str]

_expath

Path to the main BSM executable/script.

Type:

str

_app_version

The application’s version string.

Type:

str

_WEB_SERVER_PID_FILENAME

Filename for the Web UI PID file.

Type:

str

_WEB_SERVICE_SYSTEMD_NAME

Name for the Web UI systemd service.

Type:

str

_WEB_SERVICE_WINDOWS_NAME_INTERNAL

Internal name for the Web UI Windows service.

Type:

str

_WEB_SERVICE_WINDOWS_DISPLAY_NAME

Display name for the Web UI Windows service.

Type:

str

__init__()
get_setting(key: str, default: Any = None) Any

Retrieves a configuration value by its key from the global settings.

This method acts as a proxy to the get() method of the underlying Settings object.

Parameters:
  • key (str) – The dot-separated key of the setting to retrieve (e.g., "web.port", "paths.servers").

  • default (Any) – The value to return if the key is not found. Defaults to None.

Returns:

The value of the setting, or the default value if the key is not found. The actual type depends on the setting being retrieved.

Return type:

Any

set_setting(key: str, value: Any) None

Sets a configuration value by its key in the global settings and saves it.

This method acts as a proxy to the set() method of the underlying Settings object. Changes made through this method are typically persisted to the application’s configuration file.

Parameters:
  • key (str) – The dot-separated key of the setting to set (e.g., "web.port", "logging.level").

  • value (Any) – The new value for the setting.

:raises Various (from Settings): Potentially FileOperationError if saving the settings file fails.

parse_player_cli_argument(player_string: str) List[Dict[str, str]]

Parses a comma-separated string of ‘player_name:xuid’ pairs.

This utility method is designed to process player data provided as a single string, typically from a command-line argument. Each player entry in the string should be in the format “PlayerName:PlayerXUID”, and multiple entries should be separated by commas. Whitespace around names, XUIDs, commas, and colons is generally handled.

Example

"Player One:12345, PlayerTwo:67890"

Parameters:

player_string (str) – The comma-separated string of player data. If empty or not a string, an empty list is returned.

Returns:

A list of dictionaries. Each dictionary represents a player and contains two keys:

  • "name" (str): The player’s name.

  • "xuid" (str): The player’s XUID.

Returns an empty list if the input player_string is empty or invalid.

Return type:

List[Dict[str, str]]

Raises:

UserInputError – If any player pair within the string does not conform to the “name:xuid” format, or if a name or XUID is empty after stripping.

save_player_data(players_data: List[Dict[str, str]]) int

Saves or updates player data in the central players.json file.

This method merges the provided players_data with any existing player data in the players.json file located in the application’s configuration directory (see _get_player_db_path()).

The merging logic is as follows:

  • If a player’s XUID from players_data already exists in the database, their entry (name and XUID) is updated if different.

  • If a player’s XUID is new, their entry is added to the database.

The final list of players is sorted alphabetically by name before being written to the file. The configuration directory is created if it doesn’t exist.

Parameters:

players_data (List[Dict[str, str]]) – A list of player dictionaries. Each dictionary must contain string values for "name" and "xuid" keys. Both name and XUID must be non-empty.

Returns:

The total number of players that were newly added or had their existing entry updated. Returns 0 if no changes were made.

Return type:

int

Raises:
  • UserInputError – If players_data is not a list, or if any dictionary within it does not conform to the required format (missing keys, non-string values, or empty name/XUID).

  • FileOperationError – If creating the configuration directory fails or if writing to the players.json file fails (e.g., due to permission issues).

get_known_players() List[Dict[str, str]]

Retrieves all known players from the central players.json file.

This method reads the players.json file from the application’s configuration directory (obtained via _get_player_db_path()). It expects the file to contain a JSON object with a “players” key, which holds a list of player dictionaries.

Parameters:

None

Returns:

A list of player dictionaries, where each dictionary typically contains "name" and "xuid" keys. Returns an empty list if the players.json file does not exist, is empty, contains invalid JSON, or does not have the expected structure (e.g., missing “players” list). Errors during reading or parsing are logged.

Return type:

List[Dict[str, str]]

discover_and_store_players_from_all_server_logs() Dict[str, Any]

Scans all server logs for player data and updates the central player database.

This comprehensive method performs the following actions:

  1. Iterates through all subdirectories within the application’s base server directory (defined by settings['paths.servers']).

  2. For each subdirectory, it attempts to instantiate a BedrockServer object.

  3. If the server instance is valid and installed, it calls the server’s scan_log_for_players() method to extract player names and XUIDs from its logs.

  4. All player data discovered from all server logs is aggregated.

  5. Unique player entries (based on XUID) are then saved to the central players.json file using save_player_data().

Parameters:

None

Returns:

A dictionary summarizing the discovery and saving operation, containing the following keys:

  • "total_entries_in_logs" (int): The total number of player entries (possibly non-unique) found across all server logs.

  • "unique_players_submitted_for_saving" (int): The number of unique player entries (by XUID) that were attempted to be saved.

  • "actually_saved_or_updated_in_db" (int): The number of players that were newly added or updated in the central players.json by the save_player_data() call.

  • "scan_errors" (List[Dict[str, str]]): A list of dictionaries, where each entry represents an error encountered while scanning a specific server’s logs or saving the global player DB. Each error dictionary contains "server" (str, server name or “GLOBAL_PLAYER_DB”) and "error" (str, error message).

Return type:

Dict[str, Any]

Raises:
  • AppFileNotFoundError – If the main server base directory (settings['paths.servers']) is not configured or does not exist.

  • FileOperationError – If the final save operation to the central players.json (via save_player_data()) fails due to I/O issues. Note that errors during individual server log scans are caught and reported in the "scan_errors" part of the return value.

start_web_ui_direct(host: str | List[str] | None = None, debug: bool = False, threads: int | None = None) None

Starts the Web UI application directly in the current process (blocking).

This method is intended for scenarios where the Web UI is launched with the --mode direct command-line argument. It dynamically imports and calls the run_web_server() function, which in turn starts the Uvicorn server hosting the FastAPI application.

Note

This is a blocking call and will occupy the current process until the web server is shut down.

Parameters:
  • host (Optional[Union[str, List[str]]]) – The host address or list of addresses for the web server to bind to. Passed directly to run_web_server(). Defaults to None.

  • debug (bool) – If True, runs the underlying Uvicorn/FastAPI app in debug mode (e.g., with auto-reload). Passed directly to run_web_server(). Defaults to False.

  • threads (Optional[int]) –

    Specifies the number of worker processes for Uvicorn

    Only used for Windows Service

Raises:
  • RuntimeError – If run_web_server() raises a RuntimeError (e.g., missing authentication environment variables).

  • ImportError – If the web application components (e.g., run_web_server()) cannot be imported.

  • Exception – Re-raises other exceptions from run_web_server() if Uvicorn fails to start.

get_web_ui_pid_path() str

Returns the absolute path to the PID file for the detached Web UI server.

The PID file is typically stored in the application’s configuration directory (_config_dir) with the filename defined by _WEB_SERVER_PID_FILENAME.

Returns:

The absolute path to the Web UI’s PID file.

Return type:

str

get_web_ui_expected_start_arg() List[str]

Returns the list of arguments used to identify a detached Web UI server process.

These arguments (defined by _WEB_SERVER_START_ARG) are typically used by process management utilities to find and identify the correct Web UI server process when it’s run in a detached or background mode.

Returns:

A list of command-line arguments.

Return type:

List[str]

get_web_ui_executable_path() str

Returns the path to the main application executable used for starting the Web UI.

This path, stored in _expath, is essential for constructing commands to start the Web UI, especially for system services.

Returns:

The path to the application executable.

Return type:

str

Raises:

ConfigurationError – If the application executable path (_expath) is not configured or is empty.

create_web_service_file() None

Creates or updates the system service file/entry for the Web UI.

This method handles the OS-specific logic for creating a system service that will run the Bedrock Server Manager Web UI.

The start command for the service is constructed by _build_web_service_start_command(). The application data directory (_app_data_dir) is typically used as the working directory for the service.

Raises:
  • SystemError – If the current operating system is not supported (not Linux or Windows), or if underlying system utility commands fail during service creation.

  • AppFileNotFoundError – If the main manager executable path (_expath) is not found or configured.

  • FileOperationError – If file or directory operations fail (e.g., creating the working directory for the service, or writing the systemd file).

  • PermissionsError – On Windows, if the operation is not performed with Administrator privileges. On Linux, if user service directories are not writable.

  • CommandNotFoundError – If essential system commands like systemctl (Linux) or sc.exe (Windows) are not found in the system’s PATH.

  • MissingArgumentError – If required internal values for service creation are missing.

check_web_service_exists() bool

Checks if the system service for the Web UI has been created.

Delegates to OS-specific checks: - On Linux, uses check_service_exists() with _WEB_SERVICE_SYSTEMD_NAME. - On Windows, uses check_service_exists() with _WEB_SERVICE_WINDOWS_NAME_INTERNAL.

Returns:

True if the Web UI service definition exists on the system, False otherwise or if the OS is not supported.

Return type:

bool

enable_web_service() None

Enables the Web UI system service to start automatically.

On Linux, this typically means enabling the systemd service to start on boot or user login. Uses enable_systemd_service(). On Windows, this sets the service’s start type to “Automatic”. Uses enable_windows_service().

Raises:
  • SystemError – If the OS is not supported or if the underlying system command (e.g., systemctl, sc.exe) fails.

  • CommandNotFoundError – If system utilities are not found.

  • PermissionsError – On Windows, if not run with Administrator privileges.

disable_web_service() None

Disables the Web UI system service from starting automatically.

On Linux, this typically means disabling the systemd service. Uses disable_systemd_service(). On Windows, this sets the service’s start type to “Manual” or “Disabled”. Uses disable_windows_service().

Raises:
remove_web_service_file() bool

Removes the Web UI system service definition.

Warning

This is a destructive operation. The service should ideally be stopped and disabled before removal. After removal, it must be recreated using create_web_service_file() if needed again.

On Linux, this removes the systemd user service file and reloads the systemd daemon.

Uses os.remove() and systemctl --user daemon-reload.

On Windows, this deletes the service using delete_windows_service().

Returns:

bool

True if the service was successfully removed or if it was already not found (considered idempotent for removal).

Raises:
  • SystemError – If the OS is not supported.

  • FileOperationError – On Linux, if removing the service file fails.

  • CommandNotFoundError – If system utilities are not found.

  • PermissionsError – On Windows, if not run with Administrator privileges. Details of what “Various” includes, for example, it can include SubprocessError if sc.exe delete fails.

is_web_service_active() bool

Checks if the Web UI system service is currently active (running).

Delegates to OS-specific checks:

Returns False if the OS is not supported, if system utilities (systemctl, sc.exe) are not found, or if the service is not active. Errors during the check are logged.

Returns:

True if the Web UI service is determined to be active, False otherwise.

Return type:

bool

is_web_service_enabled() bool

Checks if the Web UI system service is enabled for automatic startup.

Delegates to OS-specific checks:

Returns False if the OS is not supported, if system utilities (systemctl, sc.exe) are not found, or if the service is not enabled. Errors during the check are logged.

Returns:

True if the Web UI service is determined to be enabled for automatic startup, False otherwise.

Return type:

bool

list_available_worlds() List[str]

Lists available .mcworld template files from the global content directory.

This method scans the worlds sub-folder within the application’s global content directory (see _content_dir and settings['paths.content']) for files with the .mcworld extension. It relies on _list_content_files() for the actual scanning.

These .mcworld files typically represent world templates that can be imported to create new server worlds or overwrite existing ones.

Returns:

A sorted list of absolute paths to all found .mcworld files. Returns an empty list if the directory doesn’t exist or no .mcworld files are present.

Return type:

List[str]

Raises:
  • AppFileNotFoundError – If the main content directory is not configured or found (from _list_content_files()).

  • FileOperationError – If an OS error occurs during directory scanning (from _list_content_files()).

list_available_addons() List[str]

Lists available addon files (.mcpack, .mcaddon) from the global content directory.

This method scans the addons sub-folder within the application’s global content directory (see _content_dir and settings['paths.content']) for files with .mcpack or .mcaddon extensions. It uses _list_content_files() for scanning.

These files represent behavior packs, resource packs, or bundled addons that can be installed onto server instances.

Returns:

A sorted list of absolute paths to all found .mcpack and .mcaddon files. Returns an empty list if the directory doesn’t exist or no such files are present.

Return type:

List[str]

Raises:
  • AppFileNotFoundError – If the main content directory is not configured or found (from _list_content_files()).

  • FileOperationError – If an OS error occurs during directory scanning (from _list_content_files()).

get_app_version() str

Returns the application’s version string.

The version is typically derived from the application’s settings during manager initialization and stored in _app_version.

Returns:

The application version string (e.g., “1.2.3”).

Return type:

str

get_os_type() str

Returns the current operating system type string.

This method uses platform.system() to determine the OS. Common return values include “Linux”, “Windows”, “Darwin” (for macOS).

Returns:

A string representing the current operating system.

Return type:

str

property can_schedule_tasks: bool

Indicates if a system task scheduler (crontab or schtasks) is available.

This property reflects the ‘scheduler’ capability checked during manager initialization by _check_system_capabilities(). If True, features related to scheduled tasks (like automated backups) can be expected to work.

Type:

bool

property can_manage_services: bool

Indicates if a system service manager (systemctl or sc.exe) is available.

This property reflects the ‘service_manager’ capability checked during manager initialization by _check_system_capabilities(). If True, features related to managing system services (for the Web UI or game servers) can be expected to work.

Type:

bool

validate_server(server_name: str) bool

Validates if a given server name corresponds to a valid installation.

This method checks for the existence and basic integrity of a server installation. It instantiates a BedrockServer object for the given server_name and then calls its is_installed() method.

Any exceptions raised during the instantiation or validation process (e.g., InvalidServerNameError, ConfigurationError) are caught, logged as a warning, and result in a False return value, making this a safe check.

Parameters:

server_name (str) – The name of the server to validate. This should correspond to a subdirectory within the main server base directory.

Returns:

True if the server exists and is a valid installation (i.e., its directory and executable are found), False otherwise.

Return type:

bool

Raises:

MissingArgumentError – If server_name is an empty string.

get_servers_data() Tuple[List[Dict[str, Any]], List[str]]

Discovers and retrieves status data for all valid server instances.

This method scans the main server base directory (defined by settings['paths.servers']) for subdirectories that represent server installations. For each potential server, it:

  1. Instantiates a BedrockServer object.

  2. Validates the installation using the server’s is_installed() method.

  3. If valid, it queries the server’s status and version using get_status() and get_version().

Errors encountered while processing individual servers are collected and returned separately, allowing the method to succeed even if some server directories are corrupted or misconfigured. The final list of server data is sorted alphabetically by server name.

Returns:

A tuple containing two lists:

  • The first list contains dictionaries, one for each successfully processed server. Each dictionary has the keys:

    • "name" (str): The name of the server.

    • "status" (str): The server’s current status (e.g., “RUNNING”, “STOPPED”).

    • "version" (str): The detected version of the server.

  • The second list contains string messages describing any errors that occurred while processing specific server candidates.

Return type:

Tuple[List[Dict[str, Any]], List[str]]

Raises:

AppFileNotFoundError – If the main server base directory (settings['paths.servers']) is not configured or does not exist.