Bedrock Server Core Documentation
- class bedrock_server_manager.BedrockServer(server_name: str, settings_instance: Settings = None)
Bases:
ServerStateMixin
,ServerProcessMixin
,ServerInstallationMixin
,ServerWorldMixin
,ServerAddonMixin
,ServerBackupMixin
,ServerPlayerMixin
,ServerConfigManagementMixin
,ServerInstallUpdateMixin
,BedrockServerBaseMixin
Represents and manages a single Minecraft Bedrock Server instance.
This class is the primary interface for all server-specific operations within the Bedrock Server Manager. It consolidates a wide range of functionalities by inheriting from the various specialized mixin classes listed above. Each instance of
BedrockServer
is tied to a unique server name and provides methods to control, configure, and maintain that server.The order of mixin inheritance is significant for Python’s Method Resolution Order (MRO), ensuring that methods are overridden and extended correctly. The
BedrockServerBaseMixin
provides core attributes and foundational initialization logic.- server_name
The unique name identifying this server instance.
- Type:
str
- base_dir
The base directory where all server installation directories reside (from settings:
paths.servers
).- Type:
str
- server_dir
The full path to this specific server’s installation directory (e.g.,
<base_dir>/<server_name>
).- Type:
str
- app_config_dir
Path to the application’s global configuration directory (from settings:
_config_dir
).- Type:
str
- os_type
The current operating system, e.g., “Linux”, “Windows”.
- Type:
str
- logger
A logger instance specific to this server instance.
- Type:
logging.Logger
Note
Many other attributes related to specific functionalities (e.g., server state, process information, world data paths) are available from the inherited mixin classes. Refer to the documentation of individual mixins for more details.
Key Methods (Illustrative list, grouped by typical functionality):
- Installation & Validation (from
ServerInstallationMixin
): is_installed()
validate_installation()
set_filesystem_permissions()
delete_all_data()
- State Management (from
ServerStateMixin
): get_status()
get_version()
set_version()
get_world_name()
get_custom_config_value()
set_custom_config_value()
- Process Management (from
ServerProcessMixin
): is_running()
get_process_info()
start()
stop()
send_command()
- World Management (from
ServerWorldMixin
): export_world_directory_to_mcworld()
import_active_world_from_mcworld()
delete_active_world_directory()
- Addon Management (from
ServerAddonMixin
): process_addon_file()
list_world_addons()
export_addon()
remove_addon()
- Backup & Restore (from
ServerBackupMixin
): backup_all_data()
restore_all_data_from_latest()
prune_server_backups()
list_backups()
- Player Log Scanning (from
ServerPlayerMixin
): scan_log_for_players()
- Config File Management (from
ServerConfigManagementMixin
): get_allowlist()
add_to_allowlist()
set_player_permission()
get_server_properties()
set_server_property()
- Installation & Updates (from
ServerInstallUpdateMixin
): is_update_needed()
install_or_update()
Note
This is not an exhaustive list of all available methods. Many more specialized methods are accessible from the respective mixin classes. Please consult the documentation for each individual mixin for a comprehensive list of its capabilities.
- __init__(server_name: str, settings_instance: Settings = None) None
Initializes a BedrockServer instance.
This constructor is responsible for setting up a
BedrockServer
object, which represents a specific Minecraft Bedrock server. It callssuper().__init__(...)
, triggering the initialization methods of all inherited mixin classes according to Python’s Method Resolution Order (MRO). This process starts with the first mixin in the inheritance list (currentlyServerStateMixin
) and culminates withBedrockServerBaseMixin
, which establishes fundamental server attributes.- Parameters:
server_name (str) – The unique name for this server instance. This name is also used as the directory name for the server’s files under the application’s base server directory (defined by
paths.servers_base_dir
in settings).settings_instance (
Settings
) – An instance of the application’s globalSettings
object. This is a required dependency.
- get_summary_info() Dict[str, Any]
Aggregates and returns a comprehensive summary of the server’s current state.
This method gathers information from various other status and configuration methods of the
BedrockServer
instance and consolidates it into a single dictionary. This is particularly useful for API endpoints or UI displays that require a snapshot of the server’s status.The method attempts to fetch all pieces of information gracefully, logging warnings for parts that cannot be retrieved (e.g., process details if the server isn’t running, or world name if not installed) and providing default/error values in such cases.
- Returns:
A dictionary containing a summary of the server.
Key keys include:
"name"
(str): The unique name of the server."server_directory"
(str): Absolute path to the server’s installation directory."is_installed"
(bool):True
if the server files appear to be installed,False
otherwise."status"
(str): A textual description of the server’s current status (e.g., “Running”, “Stopped”, “Not Installed”). Derived fromget_status()
."is_actually_running_process"
(bool):True
if a server process is currently running, based onis_running()
."process_details"
(Optional[Dict[str, Any]]): Information about the running process (e.g., PID, CPU, memory) if available, otherwiseNone
. Fromget_process_info()
."version"
(str): The installed version of the Bedrock server, or “N/A”. Fromget_version()
."world_name"
(str): The name of the currently active world, “N/A” if not determinable, or an error string if reading fails. Fromget_world_name()
."has_world_icon"
(bool):True
if aworld_icon.jpeg
exists for the active world. Fromhas_world_icon()
."os_type"
(str): The operating system type (e.g., “Linux”, “Windows”)."systemd_service_file_exists"
(Optional[bool]): (Linux-only)True
if a systemd service file exists,False
if not,None
if not Linux or check fails."systemd_service_enabled"
(Optional[bool]): (Linux-only)True
if systemd service is enabled,False
if not,None
if not applicable."systemd_service_active"
(Optional[bool]): (Linux-only)True
if systemd service is active,False
if not,None
if not applicable.
- Return type:
Dict[str, Any]
- add_to_allowlist(players_to_add: List[Dict[str, Any]]) int
Adds one or more players to the server’s
allowlist.json
file.This method loads the current allowlist, then iterates through the players_to_add. For each player, it checks if a player with the same name (case-insensitive) already exists in the allowlist. If not, the new player entry is added. The ignoresPlayerLimit key is defaulted to False if not present in the input player dictionary, conforming to Bedrock standards. Finally, the updated allowlist is written back to
allowlist.json
.- Parameters:
players_to_add (List[Dict[str, Any]]) – A list of player dictionaries to add. Each dictionary must contain a “name” key (str). It can optionally include “xuid” (str) and “ignoresPlayerLimit” (bool). Example:
[{"name": "Player1", "xuid": "12345", "ignoresPlayerLimit": False}]
- Returns:
The number of players that were actually added to the allowlist (i.e., those not already present).
- Return type:
int
- Raises:
TypeError – If players_to_add is not a list.
AppFileNotFoundError – If the server’s installation directory (
server_dir
) does not exist.ConfigParseError – If the existing
allowlist.json
is malformed (fromget_allowlist()
).FileOperationError – If reading from or writing to
allowlist.json
fails.
- property allowlist_json_path: str
The absolute path to this server’s
allowlist.json
file.- Type:
str
- backup_all_data() Dict[str, str | None]
Performs a full backup of the server’s active world and standard configuration files.
This method orchestrates the backup of the following components:
The active world: Determined by
self.get_world_name()
(fromServerStateMixin
), then backed up to a.mcworld
file via_backup_world_data_internal()
.allowlist.json
: Backed up via_backup_config_file_internal()
.permissions.json
: Backed up via_backup_config_file_internal()
.server.properties
: Backed up via_backup_config_file_internal()
.
Each component is backed up individually. The server’s specific backup directory (derived from
server_backup_directory
) is created if it doesn’t already exist.If the critical world backup fails, a
BackupRestoreError
is raised after attempting to back up all configuration files. Failures in backing up individual configuration files are logged as errors, and their corresponding entry in the returned dictionary will beNone
, but they do not stop the backup of other components.- Returns:
A dictionary mapping component names (e.g., “world”, “allowlist.json”) to the absolute path of their backup file. If a component’s backup failed or was skipped (e.g., the original file was not found), its value will be
None
.- Return type:
Dict[str, Optional[str]]
- Raises:
ConfigurationError – If the server’s backup directory path (
server_backup_directory
) is not configured in settings.FileOperationError – If creation of the main server backup directory (under the global backup path) fails.
BackupRestoreError – If the critical world backup operation fails. Other underlying errors from helper methods (like
AppFileNotFoundError
from_backup_world_data_internal()
if the world directory is missing) can also propagate.AttributeError – If required methods from other mixins (e.g.,
get_world_name()
fromServerStateMixin
orexport_world_directory_to_mcworld()
fromServerWorldMixin
) are not available.
- property bedrock_executable_name: str
The platform-specific name of the Bedrock server executable. Returns “bedrock_server.exe” on Windows, “bedrock_server” otherwise.
- Type:
str
- property bedrock_executable_path: str
The full, absolute path to this server’s Bedrock executable. Constructed by joining self.server_dir and self.bedrock_executable_name.
- Type:
str
- delete_active_world_directory() bool
Deletes the server’s currently active world directory.
Warning
This is a DESTRUCTIVE operation. The active world’s data will be permanently removed. The server will typically generate a new world with the same name on its next startup if the
level-name
inserver.properties
is not changed.This method determines the active world’s directory path using
_get_active_world_directory_path()
and then uses the robust deletion utilitydelete_path_robustly()
to remove it.- Returns:
True
if the active world directory was successfully deleted or if it did not exist initially.- Return type:
bool
- Raises:
FileOperationError – If determining the world path fails (e.g., due to issues with
server.properties
or if the path is not a directory), or if the deletion itself fails critically (though delete_path_robustly attempts to handle many common issues).AppFileNotFoundError – If
server.properties
is missing (propagated from_get_active_world_directory_path()
via get_world_name).ConfigParseError – If
level-name
is missing fromserver.properties
(propagated).AttributeError – If
get_world_name()
method (from StateMixin) is not available.
- delete_all_data() None
Deletes ALL data associated with this Bedrock server instance.
Danger
This is a HIGHLY DESTRUCTIVE operation and is irreversible.
It removes:
The server’s main installation directory (
BedrockServerBaseMixin.server_dir
).The server’s JSON configuration subdirectory (
BedrockServerBaseMixin.server_config_dir
).The server’s entire backup directory (derived from
paths.backups
setting).The server’s PID file.
The method will attempt to stop a running server (using
self.stop()
, expected fromServerProcessMixin
) before proceeding with deletions. If any part of the deletion process fails, it raises aFileOperationError
with details of the failed items.- Raises:
FileOperationError – If deleting one or more essential directories or files fails. The error message will summarize which items failed.
ServerStopError – If the server is running and fails to stop prior to deletion.
AttributeError – If essential methods from other mixins (like is_running or stop) are not available on the instance.
- delete_server_files(item_description_prefix: str = 'server installation files for') bool
Deletes the server’s entire installation directory (
BedrockServerBaseMixin.server_dir
).Warning
This is a DESTRUCTIVE operation. It will permanently remove the server’s main directory and all its contents.
It uses the
delete_path_robustly()
utility, which attempts to handle read-only files that might otherwise prevent deletion.- Parameters:
item_description_prefix (str, optional) – A prefix for logging messages to provide context. Defaults to “server installation files for”.
- Returns:
True
if the deletion was successful or if the directory did not exist initially.False
if the deletion failed.- Return type:
bool
- export_addon(pack_uuid: str, pack_type: str, export_dir: str, world_name: str | None = None) str
Exports a specific installed addon from a world into a
.mcpack
file.This method locates an installed behavior or resource pack within the specified world by its UUID, then archives its contents into a new
.mcpack
file. The exported file is named using the pack’s name and version (e.g.,MyPack_1.0.0.mcpack
) and saved in theexport_dir
.- Parameters:
pack_uuid (str) – The UUID of the pack to export.
pack_type (str) – The type of pack; must be either
"behavior"
or"resource"
.export_dir (str) – The absolute path to the directory where the
.mcpack
file will be saved. This directory will be created if it does not already exist.world_name (Optional[str]) – The name of the world from which to export the addon. If
None
(default), uses the server’s currently active world name.
- Returns:
The absolute path to the created
.mcpack
file.- Return type:
str
- Raises:
MissingArgumentError – If
pack_uuid
,pack_type
, orexport_dir
are empty or not provided.UserInputError – If
pack_type
is not"behavior"
or"resource"
.AppFileNotFoundError – If the specified pack (by UUID and type) cannot be found in the physical
behavior_packs
orresource_packs
folder of the world, or if the world directory itself is missing.FileOperationError – If any OS-level error occurs during directory creation, file scanning, or
.mcpack
archive creation (e.g., permission issues, disk full).AttributeError – If methods like
get_world_name()
are unavailable whenworld_name
isNone
.
- export_world_directory_to_mcworld(world_dir_name: str, target_mcworld_file_path: str) None
Exports a specified world directory into a
.mcworld
archive file.This method takes the name of a world directory (located within the server’s “worlds” folder), archives its entire contents into a ZIP file, and then renames this ZIP file to have a
.mcworld
extension, saving it to target_mcworld_file_path.The parent directory for target_mcworld_file_path will be created if it does not exist. If target_mcworld_file_path itself already exists, it will be overwritten. A temporary
.zip
file is created during the process and is cleaned up.- Parameters:
world_dir_name (str) – The name of the world directory to export, relative to the server’s “worlds” folder (e.g., “MyFavoriteWorld”).
target_mcworld_file_path (str) – The absolute path where the resulting
.mcworld
archive file should be saved.
- Raises:
MissingArgumentError – If world_dir_name or target_mcworld_file_path are empty or not strings.
AppFileNotFoundError – If the source world directory (
<server_dir>/worlds/<world_dir_name>
) does not exist or is not a directory.FileOperationError – If creating the parent directory for the target_mcworld_file_path fails due to an
OSError
.BackupRestoreError – If creating the ZIP archive (via
shutil.make_archive
) or renaming it to.mcworld
fails, or for other unexpected errors during the export process. This can wrap underlyingOSError
or other exceptions.
- extract_mcworld_to_directory(mcworld_file_path: str, target_world_dir_name: str) str
Extracts a
.mcworld
archive file into a specified world directory name.The extraction target is a subdirectory named target_world_dir_name within the server’s main “worlds” folder (see
_worlds_base_dir_in_server
).Warning
If the target_world_dir_name directory already exists, it will be deleted before extraction to ensure a clean import.
- Parameters:
mcworld_file_path (str) – The absolute path to the
.mcworld
file to be extracted.target_world_dir_name (str) – The desired name for the world directory that will be created inside the server’s “worlds” folder to contain the extracted content.
- Returns:
The absolute path to the directory where the world was extracted (e.g.,
<server_dir>/worlds/<target_world_dir_name>
).- Return type:
str
- Raises:
MissingArgumentError – If mcworld_file_path or target_world_dir_name are empty or not strings.
AppFileNotFoundError – If the source mcworld_file_path does not exist or is not a file.
FileOperationError – If creating the target directory structure or clearing a pre-existing target directory fails (e.g., due to permissions or other
OSError
).ExtractError – If the
.mcworld
file is not a valid ZIP archive or if an error occurs during the extraction process itself.
- get_allowlist() List[Dict[str, Any]]
Loads and returns the content of the server’s
allowlist.json
file.The
allowlist.json
file typically contains a list of player objects, where each object has keys like “name”, “xuid”, and “ignoresPlayerLimit”.- Returns:
A list of player dictionaries parsed from the
allowlist.json
file. Returns an empty list if the file does not exist, is empty, or if its content is not a valid JSON list.- Return type:
List[Dict[str, Any]]
- Raises:
AppFileNotFoundError – If the server’s installation directory (
server_dir
) does not exist.ConfigParseError – If the
allowlist.json
file contains malformed JSON that cannot be parsed.FileOperationError – If an OS-level error occurs while trying to read the file (e.g., permission issues).
- get_autostart() bool
Retrieves the ‘autostart’ setting from the server’s JSON config.
Accesses
settings.autostart
via_manage_json_config()
.- Returns:
The autostart status (
True
orFalse
). Defaults toFalse
if the setting is not found or an error occurs during retrieval.- Return type:
bool
- get_autoupdate() bool
Retrieves the ‘autoupdate’ setting from the server’s JSON config.
Accesses
settings.autoupdate
via_manage_json_config()
.- Returns:
The autoupdate status (
True
orFalse
). Defaults toFalse
if the setting is not found or an error occurs during retrieval.- Return type:
bool
- get_custom_config_value(key: str) Any | None
Retrieves a custom value from the ‘custom’ section of the server’s JSON config.
Accesses
custom.<key>
via_manage_json_config()
.- Parameters:
key (str) – The key of the custom value to retrieve.
- Returns:
The retrieved custom value, or
None
if the key is not found or an error occurs.- Return type:
Optional[Any]
- Raises:
UserInputError – If key is not a non-empty string.
- get_formatted_permissions(player_xuid_to_name_map: Dict[str, str]) List[Dict[str, Any]]
Reads
permissions.json
, enriches entries with player names, and sorts them.This method loads the raw data from the server’s
permissions.json
file. For each permission entry (which typically contains “xuid” and “permission”), it attempts to find the corresponding player’s gamertag using the provided player_xuid_to_name_map. If a name is found, it’s added to the entry; otherwise, a default placeholder like “Unknown (XUID: <xuid>)” is used.The resulting list of enriched permission entries is then sorted alphabetically by player name (case-insensitive).
- Parameters:
player_xuid_to_name_map (Dict[str, str]) – A dictionary mapping player XUIDs (str) to their last known gamertags (str). This is used to populate the “name” field in the returned permission entries.
- Returns:
A sorted list of player permission dictionaries.
Each dictionary in the list will contain:
”xuid” (str): The player’s XUID.
”name” (str): The player’s gamertag (from the map or a default).
”permission_level” (str): The player’s permission level (e.g., “operator”).
Returns an empty list if
permissions.json
does not exist, is empty, or contains no valid entries.- Return type:
List[Dict[str, Any]]
- Raises:
AppFileNotFoundError – If the server’s installation directory or the
permissions.json
file itself does not exist.ConfigParseError – If the
permissions.json
file contains malformed JSON or its top-level structure is not a list.FileOperationError – If an OS-level error occurs while reading the file.
- get_pid_file_path() str
Gets the full, absolute path to this server’s primary PID file.
This file is conventionally used to store the process ID of the running Bedrock server instance, especially when it’s managed as a background process or service. The path is constructed using this server’s
server_config_dir
and the filename generated by_get_server_pid_filename_default()
.- Returns:
The absolute path to the PID file.
- Return type:
str
- get_process_info() Dict[str, Any] | None
Gets resource usage information (PID, CPU, Memory, Uptime) for the running server process.
This method first uses
get_verified_bedrock_process()
to locate and verify the Bedrock server process associated with this server instance. If a valid process is found, it then uses the_resource_monitor
(an instance ofResourceMonitor
from the base mixin) to calculate its current resource statistics.- Returns:
A dictionary containing process information if the server is running, verified, and
psutil
is available. The dictionary has keys: “pid”, “cpu_percent”, “memory_mb”, “uptime”. ReturnsNone
if the server is not running, cannot be verified,psutil
is unavailable, or if an error occurs during statistics retrieval. Example:{"pid": 1234, "cpu_percent": 15.2, "memory_mb": 256.5, "uptime": "0:10:30"}
- Return type:
Optional[Dict[str, Any]]
- get_server_properties() Dict[str, str]
Reads and parses the server’s
server.properties
file into a dictionary.Each line in the format
key=value
is parsed. Lines starting with#
(comments) and blank lines are ignored. If a line is malformed (e.g., does not contain an “=”), a warning is logged, and the line is skipped.- Returns:
A dictionary where keys are property names and values are their corresponding string values from the
server.properties
file. An empty dictionary is returned if the file is empty or contains no valid properties.- Return type:
Dict[str, str]
- Raises:
AppFileNotFoundError – If the
server.properties
file (atServerStateMixin.server_properties_path
) does not exist.ConfigParseError – If an
OSError
occurs while trying to read the file (e.g., permission issues), effectively making it unparseable.
- get_server_property(property_key: str, default: Any | None = None) Any | None
Retrieves a specific property value from
server.properties
.This method first calls
get_server_properties()
to parse the entire file, then returns the value associated with property_key. If the key is not found or if theserver.properties
file itself does not exist (or is unreadable), the specified default value is returned.- Parameters:
property_key (str) – The key of the property to retrieve (e.g., “level-name”).
default (Optional[Any], optional) – The value to return if the key is not found or if the properties file cannot be accessed. Defaults to
None
.
- Returns:
The value of the property (typically a string), or the default value if the property is not found or an error occurs during file access/parsing.
- Return type:
Optional[Any]
- get_status() str
Determines and returns the current reconciled operational status of the server.
This method attempts to determine if the server process is actually running (by calling
self.is_running()
, which is expected to be provided by another mixin likeProcessMixin
). It then compares this live status with the status stored in the server’s JSON configuration file (retrieved viaget_status_from_config()
).If a discrepancy is found (e.g., process is running but config says “STOPPED”, or vice-versa when config said “RUNNING”), it updates the stored status in the JSON config to reflect the actual state.
- Returns:
The reconciled operational status of the server as a string (e.g., “RUNNING”, “STOPPED”). If
self.is_running()
is not available or fails, it falls back to returning the last known status from config.- Return type:
str
- get_status_from_config() str
Retrieves the stored ‘status’ from the server’s JSON config.
Accesses
server_info.status
via_manage_json_config()
. This reflects the last known status written to the config, not necessarily the live process status. For live status, useget_status()
.- Returns:
The stored status string (e.g., “RUNNING”, “STOPPED”), or “UNKNOWN” if not set or on error.
- Return type:
str
- get_target_version() str
Retrieves the ‘target_version’ from the server’s JSON config.
Accesses
settings.target_version
(note: schema v2 location) via_manage_json_config()
. This indicates the version the server aims to be on, often “LATEST” or a specific version string.- Returns:
The target version string, or “LATEST” if not set or on error.
- Return type:
str
- get_version() str
Retrieves the ‘installed_version’ from the server’s JSON config.
Accesses
server_info.installed_version
via_manage_json_config()
.- Returns:
The installed version string, or “UNKNOWN” if not set or on error.
- Return type:
str
- get_world_name() str
Reads the
level-name
property from the server’sserver.properties
file.- Returns:
The name of the world as specified in
server.properties
.- Return type:
str
- Raises:
AppFileNotFoundError – If the
server.properties
file does not exist at the expected path (server_properties_path
).ConfigParseError – If the file cannot be read (e.g., due to permissions) or if the
level-name
key is missing, malformed, or has an empty value.
- has_world_icon() bool
Checks if the standard world icon file (
world_icon.jpeg
) exists for the active world.This method uses
world_icon_filesystem_path
to determine the expected location of the icon and checks if a file exists at that path.- Returns:
True
if the world icon file exists and is a regular file,False
otherwise (e.g., path cannot be determined, file does not exist, or is not a file).- Return type:
bool
- import_active_world_from_mcworld(mcworld_backup_file_path: str) str
Imports a
.mcworld
file, replacing the server’s currently active world.Warning
This is a DESTRUCTIVE operation. The existing active world directory will be deleted before the new world is imported.
This method first determines the name of the server’s active world by calling
self.get_world_name()
(expected fromServerStateMixin
). It then usesextract_mcworld_to_directory()
to extract the contents of the provided mcworld_backup_file_path into a directory with that active world name, effectively replacing it.- Parameters:
mcworld_backup_file_path (str) – The absolute path to the source
.mcworld
file that contains the world data to import.- Returns:
The name of the world directory (which is the active world name) that the
.mcworld
file was imported into.- Return type:
str
- Raises:
MissingArgumentError – If mcworld_backup_file_path is empty or not a string.
AppFileNotFoundError – If the source mcworld_backup_file_path does not exist.
BackupRestoreError – If any part of the import process fails, including failure to determine the active world name, or errors during extraction (which can wrap
ExtractError
,FileOperationError
, etc.).AttributeError – If
get_world_name()
is missing.
- install_or_update(target_version_specification: str, force_reinstall: bool = False, server_zip_path: str | None = None) None
Installs or updates the Bedrock server to a specified version or dynamic target.
This is the primary method for managing server software versions. It orchestrates the entire workflow:
Checks if an update is needed using
is_update_needed()
(unless force_reinstall isTrue
or the server isn’t installed).If the server is running, stops it using
self.stop()
(expected fromServerProcessMixin
).Updates the server’s persisted status to “INSTALLING” or “UPDATING” (via
self.set_status_in_config()
fromServerStateMixin
).If it’s a new installation, sets the target version in the config.
Initializes a
BedrockDownloader
for the target_version_specification.Calls
BedrockDownloader.prepare_download_assets()
to download/verify files.Calls the internal helper
_perform_server_files_setup()
to extract the archive and set permissions. This helper, in turn, relies onself.set_filesystem_permissions()
(expected from another mixin).Updates the server’s persisted installed version (via
self.set_version()
fromServerStateMixin
) and final status (“INSTALLED” or “UPDATED”).Cleans up the downloaded ZIP archive.
- Parameters:
target_version_specification (str) – The target version to install or update to. Can be a specific version string (e.g., “1.20.10.01”), “LATEST” (for the latest stable release), or “PREVIEW” (for the latest preview release).
force_reinstall (bool, optional) – If
True
, the server software will be reinstalled/extracted even ifis_update_needed()
reports that the current version matches the target. Defaults toFalse
.
- Raises:
MissingArgumentError – If target_version_specification is empty.
ServerStopError – If the server is running and fails to stop.
DownloadError – If the server software download fails.
ExtractError – If the downloaded server archive cannot be extracted.
PermissionsError – If filesystem permissions cannot be set after extraction.
FileOperationError – For other unexpected file I/O errors during the process.
AttributeError – If essential methods from other mixins (like is_installed, stop, set_status_in_config, set_version, set_filesystem_permissions) are not available on the instance.
BSMError – For other known application-specific errors during the process.
- is_installed() bool
Checks if the server installation is valid, without raising exceptions.
This is a convenience method that calls
validate_installation()
and catchesAppFileNotFoundError
if validation fails, returningFalse
in such cases.- Returns:
True
if the installation is valid (directory and executable exist),False
otherwise.- Return type:
bool
- is_running() bool
Checks if the Bedrock server process is currently running and verified.
- is_update_needed(target_version_specification: str) bool
Checks if the server’s installed version requires an update to meet the target.
This method compares the server’s currently installed version (obtained via
self.get_version()
, expected fromServerStateMixin
) against the target_version_specification. The target can be:A specific version string (e.g., “1.20.10.01”).
“LATEST” (for the latest stable release).
“PREVIEW” (for the latest preview release).
If the target is “LATEST” or “PREVIEW”, this method uses
BedrockDownloader
to fetch the actual latest version number corresponding to that specification for comparison. If the target is a specific version, it’s compared directly.- Parameters:
target_version_specification (str) – The target version to check against (e.g., “1.20.10.01”, “LATEST”, “PREVIEW”).
- Returns:
True
if an update is determined to be needed,False
otherwise. ReturnsTrue
as a fail-safe if the current version is “UNKNOWN” or if there are errors fetching remote version information for “LATEST”/”PREVIEW”.- Return type:
bool
- Raises:
MissingArgumentError – If target_version_specification is empty or not a string.
AttributeError – If
self.get_version()
method is not available.
- list_backups(backup_type: str) List[str] | Dict[str, List[str]]
Retrieves a list of available backup files for this server, sorted newest first.
This method scans the server’s specific backup directory (obtained via
server_backup_directory
) for backup files matching the specifiedbackup_type
. Backups are sorted by their modification time, with the most recent backup appearing first.Valid
backup_type
options (case-insensitive):"world"
: Lists*.mcworld
files (world backups)."properties"
: Listsserver_backup_*.properties
files."allowlist"
: Listsallowlist_backup_*.json
files."permissions"
: Listspermissions_backup_*.json
files."all"
: Returns a dictionary categorizing all found backup types.
- Parameters:
backup_type (str) – The type of backups to list. Must be one of “world”, “properties”, “allowlist”, “permissions”, or “all”.
- Returns:
If
backup_type
is specific (e.g., “world”), returns a list of absolute backup file paths, sorted by modification time (newest first). An empty list is returned if no matching backups are found or if the server’s backup directory doesn’t exist.If
backup_type
is “all”, returns a dictionary where keys are backup categories (e.g., “world_backups”, “properties_backups”) and values are the corresponding sorted lists of file paths. An empty dictionary is returned if the backup directory doesn’t exist or no backups of any type are found.
- Return type:
Union[List[str], Dict[str, List[str]]]
- Raises:
MissingArgumentError – If
backup_type
is empty or not a string.UserInputError – If
backup_type
is not one of the valid options.ConfigurationError – If the server’s backup directory is not configured (i.e.,
server_backup_directory
isNone
).FileOperationError – If an
OSError
occurs during filesystem listing (e.g., permission issues).
- list_world_addons(world_name: str | None = None) Dict[str, List[Dict[str, Any]]]
Lists all behavior and resource packs for a specified world.
This method provides a detailed inventory of addons by:
Scanning the physical pack folders (
behavior_packs
andresource_packs
) within the specified world’s directory to find all installed packs by reading theirmanifest.json
files.Reading the world’s activation JSON files (
world_behavior_packs.json
andworld_resource_packs.json
) to determine which packs are active.Comparing these two sets of information to determine the status of each pack.
- The status can be:
ACTIVE
: The pack is physically present and listed in the activation file.INACTIVE
: The pack is physically present but not listed in the activation file.ORPHANED
: The pack is listed in the activation file but not physically present.
- Parameters:
world_name (Optional[str]) – The name of the world to inspect. If
None
(default), uses the server’s currently active world name obtained viaget_world_name()
.- Returns:
A dictionary with two keys:
"behavior_packs"
and"resource_packs"
. Each key maps to a list of dictionaries, where each dictionary represents an addon with the following string keys:"name"
(str): The display name of the pack from its manifest."uuid"
(str): The UUID of the pack from its manifest."version"
(List[int]): The version of the pack (e.g.,[1, 0, 0]
)."status"
(str): The activation status: ‘ACTIVE’, ‘INACTIVE’, or ‘ORPHANED’.
The lists of pack dictionaries are sorted by pack name.
- Return type:
Dict[str, List[Dict[str, Any]]]
- Raises:
AppFileNotFoundError – If the directory for the specified
world_name
does not exist.AttributeError – If
get_world_name()
is not available whenworld_name
isNone
.
- property permissions_json_path: str
The absolute path to this server’s
permissions.json
file.- Type:
str
- process_addon_file(addon_file_path: str) None
Processes a given addon file (
.mcaddon
or.mcpack
).This method acts as a high-level dispatcher. It inspects the file extension of the provided
addon_file_path
to determine if it’s an.mcaddon
or.mcpack
file. It then delegates the actual processing to the corresponding internal helper methods:_process_mcaddon_archive()
for.mcaddon
files or_process_mcpack_archive()
for.mcpack
files.- Parameters:
addon_file_path (str) – The absolute path to the addon file (
.mcaddon
or.mcpack
) to be processed.- Raises:
MissingArgumentError – If
addon_file_path
is empty or not provided.AppFileNotFoundError – If the file specified by
addon_file_path
does not exist or is not a file.UserInputError – If the file extension is not
.mcaddon
or.mcpack
(case-insensitive).
- prune_server_backups(component_prefix: str, file_extension: str) None
Removes the oldest backups for a specific component to adhere to retention policies.
This method targets backup files within this server’s specific backup directory
(see
server_backup_directory
) that match a givencomponent_prefix
(e.g.,MyActiveWorld_backup_
,server_backup_
) andfile_extension
(e.g.,mcworld
,properties
,json
).It retrieves the number of backups to keep from the application settings (key:
retention.backups
, defaulting to 3 if not set or invalid). If more backups than this configured number are found (sorted by modification time), the oldest ones are deleted until the retention count is met.- Parameters:
component_prefix (str) – The prefix part of the backup filenames to target (e.g.,
MyActiveWorld_backup_
for world backups,server_backup_
for server.properties backups). Should not be empty.file_extension (str) – The extension of the backup files, without the leading dot (e.g., “mcworld”, “json”, “properties”). Should not be empty.
- Raises:
ConfigurationError – If the server’s backup directory path (
server_backup_directory
) is not configured in settings.MissingArgumentError – If
component_prefix
orfile_extension
are empty or not strings.UserInputError – If the
retention.backups
setting value from application settings is invalid (e.g., not a non-negative integer).FileOperationError – If an
OSError
occurs during file listing or deletion (e.g., permission issues), or if not all required old backups could be deleted successfully.
- remove_addon(pack_uuid: str, pack_type: str, world_name: str | None = None) None
Removes a specific addon from a world.
Warning
This is a destructive operation. It permanently deletes the addon’s files from the world’s
behavior_packs
orresource_packs
directory and deactivates the addon by removing its entry from the world’s corresponding activation JSON file (e.g.,world_behavior_packs.json
).If the addon’s files are not found, it will still attempt to remove its entry from the activation JSON file.
- Parameters:
pack_uuid (str) – The UUID of the pack to remove.
pack_type (str) – The type of pack; must be either
"behavior"
or"resource"
.world_name (Optional[str]) – The name of the world from which to remove the addon. If
None
(default), uses the server’s currently active world name.
- Raises:
MissingArgumentError – If
pack_uuid
orpack_type
are empty or not provided.UserInputError – If
pack_type
is not"behavior"
or"resource"
.FileOperationError – If an OS-level error occurs during file/directory deletion or when updating the world’s activation JSON file.
AttributeError – If methods like
get_world_name()
are unavailable whenworld_name
isNone
.
- remove_from_allowlist(player_name_to_remove: str) bool
Removes a player from the server’s
allowlist.json
by their gamertag.This method loads the current allowlist, filters out the player whose name matches player_name_to_remove (case-insensitively), and then writes the modified allowlist back to the file.
- Parameters:
player_name_to_remove (str) – The gamertag of the player to remove from the allowlist.
- Returns:
True
if a player with the given name was found and removed,False
otherwise (e.g., if the player was not on the allowlist).- Return type:
bool
- Raises:
MissingArgumentError – If player_name_to_remove is empty or not a string.
AppFileNotFoundError – If the server’s installation directory does not exist.
ConfigParseError – If the existing
allowlist.json
is malformed.FileOperationError – If reading from or writing to
allowlist.json
fails.
- restore_all_data_from_latest() Dict[str, str | None]
Restores the server’s active world and standard configuration files from their latest backups.
This method attempts to restore the following components by finding their most recent backup file (sorted by modification time) in the server’s specific backup directory (see
server_backup_directory
):The active world: Restored using
import_active_world_from_mcworld()
after finding the latest.mcworld
backup matching the active world’s name.server.properties
: Restored via_restore_config_file_internal()
.allowlist.json
: Restored via_restore_config_file_internal()
.permissions.json
: Restored via_restore_config_file_internal()
.
Each component is restored individually. If a backup for a specific component is not found, or if the restore operation for that component fails, the issue is logged, and the process continues with other components. A
BackupRestoreError
is raised at the end if any component failed to restore, summarizing all failures.The server’s main installation directory (
server_dir
) is created if it doesn’t exist before attempting to restore files into it.Warning
This operation overwrites current world data and configuration files in the server’s installation directory with content from the backups. Ensure this is the desired action before proceeding.
- Returns:
A dictionary mapping component names (e.g., “world”, “server.properties”) to the absolute path where they were restored in the server’s installation directory. If a component’s restore was skipped (e.g., no backup found) or failed, its value in the dictionary will be
None
. Returns an empty dictionary if the server’s backup directory itself is not found or is inaccessible.- Return type:
Dict[str, Optional[str]]
- Raises:
ConfigurationError – If the server’s backup directory path (
server_backup_directory
) is not configured in settings.FileOperationError – If creation of the server’s main installation directory (
self.server_dir
) fails.BackupRestoreError – If one or more components (world or configuration files) fail to restore. The error message will summarize all failures.
AttributeError – If required methods from other mixins (e.g.,
get_world_name()
orimport_active_world_from_mcworld()
) are not available on the server instance.
- scan_log_for_players() List[Dict[str, str]]
Scans the server’s log file for player connection entries to extract gamertags and XUIDs.
This method reads the server’s primary output log file (obtained via
server_log_path
) line by line. It uses a regular expression to find lines matching the standard Bedrock server message for player connections, which typically looks like: “Player connected: <Gamertag>, xuid: <XUID>”.It collects unique players based on their XUID to avoid duplicates from multiple connections by the same player within the log.
- Returns:
A list of unique player data dictionaries found in the log. Each dictionary has two keys:
”name” (str): The player’s gamertag.
”xuid” (str): The player’s Xbox User ID (XUID).
Returns an empty list if the log file doesn’t exist, is empty, or if no player connection entries are found.
- Return type:
List[Dict[str, str]]
- Raises:
FileOperationError – If an OS-level error occurs while trying to read the log file (e.g., permission issues).
- send_command(command: str) None
Sends a command string to the running Bedrock server process.
- property server_backup_directory: str | None
The absolute path to this server’s specific backup directory.
This path is constructed by joining the global backup directory path (from
settings.get("paths.backups")
) with the server’s name (server_name
). The directory itself is created by backup methods if it doesn’t exist.- Returns:
The absolute path to the backup directory if
paths.backups
is configured in settings, otherwiseNone
(and a warning is logged).- Type:
Optional[str]
- property server_config_dir: str
The absolute path to this server instance’s dedicated configuration subdirectory. This is usually
<app_config_dir>/<server_name>/
, and is intended to store server-specific configuration files, PID files, etc. The directory itself is not created by this property.- Type:
str
- property server_log_path: str
The expected absolute path to the server’s main output log file. Typically
<server_dir>/server_output.txt
.- Type:
str
- property server_properties_path: str
The absolute path to this server’s
server.properties
file.- Type:
str
- set_autostart(value: bool) None
Sets the ‘autostart’ setting in the server’s JSON config.
Updates
settings.autostart
via_manage_json_config()
.- Parameters:
value (bool) – The boolean value to set for autostart.
- Raises:
UserInputError – If value is not a boolean.
- set_autoupdate(value: bool) None
Sets the ‘autoupdate’ setting in the server’s JSON config.
Updates
settings.autoupdate
via_manage_json_config()
.- Parameters:
value (bool) – The boolean value to set for autoupdate.
- Raises:
UserInputError – If value is not a boolean.
- set_custom_config_value(key: str, value: Any) None
Sets a custom key-value pair in the ‘custom’ section of the server’s JSON config.
Updates
custom.<key>
via_manage_json_config()
.- Parameters:
key (str) – The key for the custom value.
value (Any) – The value to set. Must be JSON serializable.
- Raises:
UserInputError – If key is not a non-empty string.
ConfigParseError – If value is not JSON serializable (from underlying save).
- set_filesystem_permissions() None
Sets appropriate filesystem permissions for the server’s installation directory.
This method first validates the server installation using
is_installed()
. If valid, it delegates to the platform-agnosticset_server_folder_permissions()
utility to apply the necessary permissions recursively toBedrockServerBaseMixin.server_dir
. This is crucial for proper server operation, especially on Linux.- Raises:
AppFileNotFoundError – If the server is not installed (i.e.,
is_installed()
returnsFalse
).PermissionsError – If setting permissions fails (propagated from
set_server_folder_permissions()
).MissingArgumentError – If server_dir is somehow invalid (propagated).
- set_player_permission(xuid: str, permission_level: str, player_name: str | None = None) None
Sets or updates a player’s permission level in
permissions.json
.This method manages entries in the server’s
permissions.json
file. If a player with the given xuid already exists in the file, their permission level is updated to permission_level. If a player_name is provided and differs from an existing entry for that XUID, the name is also updated. If the player (by XUID) does not exist, a new entry is created with the specified xuid, permission_level, and player_name (or XUID if name is not provided).Valid permission levels are “operator”, “member”, and “visitor”.
- Parameters:
xuid (str) – The player’s Xbox User ID (XUID).
permission_level (str) – The permission level to set. Must be one of “operator”, “member”, or “visitor” (case-insensitive).
player_name (Optional[str], optional) – The player’s gamertag. If provided, it will be included in the permissions entry for reference. Defaults to
None
(in which case XUID might be used as name for new entries).
- Raises:
AppFileNotFoundError – If the server’s installation directory does not exist.
MissingArgumentError – If xuid or permission_level are empty or not strings.
UserInputError – If permission_level is not one of the valid options.
FileOperationError – If reading from or writing to
permissions.json
fails.ConfigParseError – If the existing
permissions.json
is malformed.
- set_server_property(property_key: str, property_value: Any) None
Modifies or adds a property in the server’s
server.properties
file.This method reads the entire
server.properties
file line by line. If a line starting with property_key= is found, it’s replaced with the new property_key=property_value. If the key is not found, the new property line is appended to the end of the file. Comments and blank lines are preserved. Duplicate entries for the same key (if any) will result in the first being updated and subsequent ones being commented out.The property_value is converted to a string before writing.
- Parameters:
property_key (str) – The property key to set (e.g., “level-name”, “max-players”).
property_value (Any) – The value to set for the property. It will be converted to a string.
- Raises:
MissingArgumentError – If property_key is empty or not a string.
UserInputError – If property_value, when converted to a string, contains invalid control characters (excluding tab).
AppFileNotFoundError – If the
server.properties
file (atServerStateMixin.server_properties_path
) does not exist.FileOperationError – If reading from or writing to
server.properties
fails.
- set_status_in_config(status_string: str) None
Sets the ‘status’ in the server’s JSON config.
Updates
server_info.status
via_manage_json_config()
. This is used to persist the server’s state.- Parameters:
status_string (str) – The status string to set (e.g., “RUNNING”, “STOPPED”).
- Raises:
UserInputError – If status_string is not a string.
- set_target_version(version_string: str) None
Sets the ‘target_version’ in the server’s JSON config.
Updates
settings.target_version
(note: schema v2 location) via_manage_json_config()
.- Parameters:
version_string (str) – The target version string to set (e.g., “LATEST”, “1.20.30.02”).
- Raises:
UserInputError – If version_string is not a string.
- set_version(version_string: str) None
Sets the ‘installed_version’ in the server’s JSON config.
Updates
server_info.installed_version
via_manage_json_config()
.- Parameters:
version_string (str) – The version string to set (e.g., “1.20.30.02”).
- Raises:
UserInputError – If version_string is not a string.
- start() None
Starts the Bedrock server process.
- stop() None
Stops the Bedrock server process gracefully, with a forceful fallback.
- validate_installation() bool
Validates that the server installation directory and executable exist.
This method checks for the presence of:
The server’s main installation directory (
BedrockServerBaseMixin.server_dir
).The Bedrock server executable within that directory (path from
BedrockServerBaseMixin.bedrock_executable_path
).
- Returns:
True
if both the server directory and executable file exist.- Return type:
bool
- Raises:
AppFileNotFoundError – If the server directory or the executable file does not exist at their expected locations.
- property world_icon_filename: str
The standard filename for a world’s icon image (
world_icon.jpeg
).- Type:
str
- property world_icon_filesystem_path: str | None
The absolute filesystem path to the world icon for the active world.
This is constructed by joining the active world’s directory path (from
_get_active_world_directory_path()
) with the standard icon filename (world_icon_filename
).Returns
None
if the active world directory path cannot be determined (e.g., ifget_world_name()
fails or is unavailable).- Type:
Optional[str]