Bedrock Server Manager Core Documentation
- class bedrock_server_manager.BedrockServerManager
Bases:
objectManages global application settings, server discovery, and application-wide data.
The
BedrockServerManagerserves 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 theBedrockServerclass, which handles the specifics of individual server instances.Key Responsibilities:
Providing access to and management of global application settings through an aggregated
Settingsobject.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.,
.mcworldtemplates,.mcaddon/.mcpackaddons) 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
Settingsinstance 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 aBedrockServerobject.- 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 underlyingSettingsobject.- 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
defaultvalue 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 underlyingSettingsobject. 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): PotentiallyFileOperationErrorif 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_stringis 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.jsonfile.This method merges the provided
players_datawith any existing player data in theplayers.jsonfile 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_dataalready 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_datais 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.jsonfile fails (e.g., due to permission issues).
- get_known_players() List[Dict[str, str]]
Retrieves all known players from the central
players.jsonfile.This method reads the
players.jsonfile 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 theplayers.jsonfile 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:
Iterates through all subdirectories within the application’s base server directory (defined by
settings['paths.servers']).For each subdirectory, it attempts to instantiate a
BedrockServerobject.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.All player data discovered from all server logs is aggregated.
Unique player entries (based on XUID) are then saved to the central
players.jsonfile usingsave_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 centralplayers.jsonby thesave_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(viasave_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 directcommand-line argument. It dynamically imports and calls therun_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 toNone.debug (bool) – If
True, runs the underlying Uvicorn/FastAPI app in debug mode (e.g., with auto-reload). Passed directly torun_web_server(). Defaults toFalse.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.
On Linux, it creates a systemd user service file using
create_systemd_service_file(). The service will be named based on_WEB_SERVICE_SYSTEMD_NAME.On Windows, it creates a new Windows Service using
create_windows_service(). The service will be named based on_WEB_SERVICE_WINDOWS_NAME_INTERNALand_WEB_SERVICE_WINDOWS_DISPLAY_NAME.
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) orsc.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, usescheck_service_exists()with_WEB_SERVICE_WINDOWS_NAME_INTERNAL.- Returns:
Trueif the Web UI service definition exists on the system,Falseotherwise 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”. Usesenable_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”. Usesdisable_windows_service().- Raises:
SystemError – If the OS is not supported or if the underlying system command fails.
CommandNotFoundError – If system utilities are not found.
PermissionsError – On Windows, if not run with Administrator privileges.
- 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()andsystemctl --user daemon-reload.On Windows, this deletes the service using
delete_windows_service().- Returns:
- bool
Trueif 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
SubprocessErrorifsc.exe deletefails.
- is_web_service_active() bool
Checks if the Web UI system service is currently active (running).
Delegates to OS-specific checks:
On Linux, uses
systemctl --user is-activefor the service named by_WEB_SERVICE_SYSTEMD_NAME.On Windows, uses
sc queryfor the service named by_WEB_SERVICE_WINDOWS_NAME_INTERNAL.
Returns
Falseif 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:
Trueif the Web UI service is determined to be active,Falseotherwise.- 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:
On Linux, uses
systemctl --user is-enabledfor the service named by_WEB_SERVICE_SYSTEMD_NAME.On Windows, uses
sc qc(query config) for the service named by_WEB_SERVICE_WINDOWS_NAME_INTERNALto check if its start type is “AUTO_START”.
Returns
Falseif 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:
Trueif the Web UI service is determined to be enabled for automatic startup,Falseotherwise.- Return type:
bool
- list_available_worlds() List[str]
Lists available
.mcworldtemplate files from the global content directory.This method scans the
worldssub-folder within the application’s global content directory (see_content_dirandsettings['paths.content']) for files with the.mcworldextension. It relies on_list_content_files()for the actual scanning.These
.mcworldfiles 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
.mcworldfiles. Returns an empty list if the directory doesn’t exist or no.mcworldfiles 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
addonssub-folder within the application’s global content directory (see_content_dirandsettings['paths.content']) for files with.mcpackor.mcaddonextensions. 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
.mcpackand.mcaddonfiles. 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 (
crontaborschtasks) is available.This property reflects the ‘scheduler’ capability checked during manager initialization by
_check_system_capabilities(). IfTrue, 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 (
systemctlorsc.exe) is available.This property reflects the ‘service_manager’ capability checked during manager initialization by
_check_system_capabilities(). IfTrue, 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
BedrockServerobject for the givenserver_nameand then calls itsis_installed()method.Any exceptions raised during the instantiation or validation process (e.g.,
InvalidServerNameError,ConfigurationError) are caught, logged as a warning, and result in aFalsereturn 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:
Trueif the server exists and is a valid installation (i.e., its directory and executable are found),Falseotherwise.- Return type:
bool
- Raises:
MissingArgumentError – If
server_nameis 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:Instantiates a
BedrockServerobject.Validates the installation using the server’s
is_installed()method.If valid, it queries the server’s status and version using
get_status()andget_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.