pymcsc 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mcsc/__init__.py +79 -0
- mcsc/config.py +91 -0
- mcsc/download.py +38 -0
- mcsc/exceptions.py +49 -0
- mcsc/files.py +81 -0
- mcsc/manager.py +195 -0
- mcsc/monitor.py +107 -0
- mcsc/py.typed +0 -0
- mcsc/servers/__init__.py +30 -0
- mcsc/servers/base.py +352 -0
- mcsc/servers/forge.py +103 -0
- mcsc/servers/paper.py +24 -0
- mcsc/servers/vanilla.py +10 -0
- mcsc/system.py +18 -0
- mcsc/versions.py +123 -0
- pymcsc-0.1.0.dist-info/METADATA +132 -0
- pymcsc-0.1.0.dist-info/RECORD +19 -0
- pymcsc-0.1.0.dist-info/WHEEL +5 -0
- pymcsc-0.1.0.dist-info/top_level.txt +1 -0
mcsc/__init__.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""mcsc - create, run and manage Minecraft servers.
|
|
2
|
+
|
|
3
|
+
Quick start::
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from mcsc import ServerManager, ServerType
|
|
7
|
+
|
|
8
|
+
manager = ServerManager("servers")
|
|
9
|
+
manager.load()
|
|
10
|
+
server = manager.create("My server", "1.21.4", ServerType.PAPER, accept_eula=True)
|
|
11
|
+
|
|
12
|
+
async def main():
|
|
13
|
+
server.add_output_listener(lambda srv, line: print(line))
|
|
14
|
+
await server.start()
|
|
15
|
+
...
|
|
16
|
+
await server.stop()
|
|
17
|
+
|
|
18
|
+
asyncio.run(main())
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import logging
|
|
22
|
+
|
|
23
|
+
from mcsc.config import ServerConfig, ServerState, ServerType
|
|
24
|
+
from mcsc.exceptions import (
|
|
25
|
+
DownloadError,
|
|
26
|
+
EulaNotAcceptedError,
|
|
27
|
+
InstallError,
|
|
28
|
+
JavaNotFoundError,
|
|
29
|
+
MCSCError,
|
|
30
|
+
ServerNotFoundError,
|
|
31
|
+
ServerNotRunningError,
|
|
32
|
+
ServerRunningError,
|
|
33
|
+
ServerStateError,
|
|
34
|
+
UnsupportedVersionError,
|
|
35
|
+
VersionNotFoundError,
|
|
36
|
+
)
|
|
37
|
+
from mcsc.manager import ServerManager
|
|
38
|
+
from mcsc.monitor import ProcessMonitor, ResourceUsage
|
|
39
|
+
from mcsc.servers import (
|
|
40
|
+
ForgeServer,
|
|
41
|
+
MinecraftServer,
|
|
42
|
+
PaperServer,
|
|
43
|
+
VanillaServer,
|
|
44
|
+
server_from_config,
|
|
45
|
+
)
|
|
46
|
+
from mcsc.system import suggested_ram_gb, total_ram_gb
|
|
47
|
+
from mcsc.versions import VersionCatalog
|
|
48
|
+
|
|
49
|
+
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
|
50
|
+
|
|
51
|
+
__version__ = "0.1.0"
|
|
52
|
+
|
|
53
|
+
__all__ = [
|
|
54
|
+
"DownloadError",
|
|
55
|
+
"EulaNotAcceptedError",
|
|
56
|
+
"ForgeServer",
|
|
57
|
+
"InstallError",
|
|
58
|
+
"JavaNotFoundError",
|
|
59
|
+
"MCSCError",
|
|
60
|
+
"MinecraftServer",
|
|
61
|
+
"PaperServer",
|
|
62
|
+
"ProcessMonitor",
|
|
63
|
+
"ResourceUsage",
|
|
64
|
+
"ServerConfig",
|
|
65
|
+
"ServerManager",
|
|
66
|
+
"ServerNotFoundError",
|
|
67
|
+
"ServerNotRunningError",
|
|
68
|
+
"ServerRunningError",
|
|
69
|
+
"ServerState",
|
|
70
|
+
"ServerStateError",
|
|
71
|
+
"ServerType",
|
|
72
|
+
"UnsupportedVersionError",
|
|
73
|
+
"VanillaServer",
|
|
74
|
+
"VersionCatalog",
|
|
75
|
+
"VersionNotFoundError",
|
|
76
|
+
"server_from_config",
|
|
77
|
+
"suggested_ram_gb",
|
|
78
|
+
"total_ram_gb",
|
|
79
|
+
]
|
mcsc/config.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Server configuration model."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass, field, fields
|
|
6
|
+
from enum import IntEnum, StrEnum
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
from uuid import uuid4
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ServerType(IntEnum):
|
|
13
|
+
"""Supported server distributions.
|
|
14
|
+
|
|
15
|
+
Values match the legacy ``jar_type`` integers used by minecraft-server-creator.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
VANILLA = 0
|
|
19
|
+
PAPER = 1
|
|
20
|
+
FORGE = 2
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def label(self) -> str:
|
|
24
|
+
"""Display name of the server type."""
|
|
25
|
+
return self.name.capitalize()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ServerState(StrEnum):
|
|
29
|
+
"""Lifecycle state of a server process."""
|
|
30
|
+
|
|
31
|
+
STOPPED = "stopped"
|
|
32
|
+
STARTING = "starting"
|
|
33
|
+
RUNNING = "running"
|
|
34
|
+
STOPPING = "stopping"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# Legacy keys (minecraft-server-creator servers.json) -> ServerConfig fields
|
|
38
|
+
_LEGACY_KEYS = {
|
|
39
|
+
"jar_type": "server_type",
|
|
40
|
+
"dedicated_ram": "ram_gb",
|
|
41
|
+
"folder_path": "path",
|
|
42
|
+
"uuid": "id",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class ServerConfig:
|
|
48
|
+
"""Persistent settings of a single server.
|
|
49
|
+
|
|
50
|
+
``path`` is the server's root folder. It is assigned by
|
|
51
|
+
:class:`mcsc.ServerManager` when the server is created.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
name: str
|
|
55
|
+
version: str
|
|
56
|
+
server_type: ServerType = ServerType.VANILLA
|
|
57
|
+
ram_gb: int = 2
|
|
58
|
+
port: int = 25565
|
|
59
|
+
address: str | None = None
|
|
60
|
+
java_path: str = "java"
|
|
61
|
+
jvm_args: list[str] = field(default_factory=list)
|
|
62
|
+
id: str = field(default_factory=lambda: str(uuid4()))
|
|
63
|
+
path: Path | None = None
|
|
64
|
+
|
|
65
|
+
def __post_init__(self) -> None:
|
|
66
|
+
self.server_type = ServerType(self.server_type)
|
|
67
|
+
self.ram_gb = int(self.ram_gb)
|
|
68
|
+
self.port = int(self.port)
|
|
69
|
+
if self.path is not None:
|
|
70
|
+
self.path = Path(self.path)
|
|
71
|
+
if self.address in ("", "default"):
|
|
72
|
+
self.address = None
|
|
73
|
+
|
|
74
|
+
def to_dict(self) -> dict[str, Any]:
|
|
75
|
+
"""JSON-serializable representation."""
|
|
76
|
+
data = asdict(self)
|
|
77
|
+
data["server_type"] = int(self.server_type)
|
|
78
|
+
data["path"] = str(self.path) if self.path is not None else None
|
|
79
|
+
return data
|
|
80
|
+
|
|
81
|
+
@classmethod
|
|
82
|
+
def from_dict(cls, data: dict[str, Any]) -> ServerConfig:
|
|
83
|
+
"""Build a config from :meth:`to_dict` output or a legacy servers.json entry.
|
|
84
|
+
|
|
85
|
+
Unknown keys are ignored.
|
|
86
|
+
"""
|
|
87
|
+
normalized: dict[str, Any] = {}
|
|
88
|
+
for key, value in data.items():
|
|
89
|
+
normalized.setdefault(_LEGACY_KEYS.get(key, key), value)
|
|
90
|
+
known = {f.name for f in fields(cls)}
|
|
91
|
+
return cls(**{k: v for k, v in normalized.items() if k in known})
|
mcsc/download.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""HTTP download helper."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import requests
|
|
10
|
+
|
|
11
|
+
from mcsc.exceptions import DownloadError
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def download_file(url: str, destination: Path, *, timeout: float = 30) -> Path:
|
|
17
|
+
"""Stream ``url`` to ``destination``.
|
|
18
|
+
|
|
19
|
+
Writes to a temporary file first, so a failed download never leaves a
|
|
20
|
+
truncated file at ``destination``.
|
|
21
|
+
"""
|
|
22
|
+
destination = Path(destination)
|
|
23
|
+
tmp = destination.with_name(destination.name + ".part")
|
|
24
|
+
try:
|
|
25
|
+
with requests.get(url, stream=True, timeout=timeout) as response:
|
|
26
|
+
response.raise_for_status()
|
|
27
|
+
with open(tmp, "wb") as file:
|
|
28
|
+
for chunk in response.iter_content(chunk_size=64 * 1024):
|
|
29
|
+
file.write(chunk)
|
|
30
|
+
os.replace(tmp, destination)
|
|
31
|
+
except requests.RequestException as e:
|
|
32
|
+
tmp.unlink(missing_ok=True)
|
|
33
|
+
raise DownloadError(f"Error downloading {url}: {e}") from e
|
|
34
|
+
except OSError:
|
|
35
|
+
tmp.unlink(missing_ok=True)
|
|
36
|
+
raise
|
|
37
|
+
logger.info("Downloaded %s to %s", url, destination)
|
|
38
|
+
return destination
|
mcsc/exceptions.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Exceptions raised by mcsc.
|
|
2
|
+
|
|
3
|
+
Messages are plain English; applications that need localized messages
|
|
4
|
+
should catch these types and translate them.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MCSCError(Exception):
|
|
9
|
+
"""Base class for every error raised by mcsc."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ServerNotFoundError(MCSCError, KeyError):
|
|
13
|
+
"""No server with the requested id is registered."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ServerStateError(MCSCError):
|
|
17
|
+
"""The operation is not allowed in the server's current state."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ServerRunningError(ServerStateError):
|
|
21
|
+
"""The operation requires the server to be stopped."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ServerNotRunningError(ServerStateError):
|
|
25
|
+
"""The operation requires the server to be running."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class EulaNotAcceptedError(ServerStateError):
|
|
29
|
+
"""The server cannot start until the Minecraft EULA is accepted."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class JavaNotFoundError(MCSCError, FileNotFoundError):
|
|
33
|
+
"""The configured Java executable could not be found."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class VersionNotFoundError(MCSCError, LookupError):
|
|
37
|
+
"""The requested Minecraft version is not available for the server type."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class UnsupportedVersionError(MCSCError):
|
|
41
|
+
"""The version is known, but mcsc cannot install or run it."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class DownloadError(MCSCError):
|
|
45
|
+
"""A file could not be downloaded."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class InstallError(MCSCError):
|
|
49
|
+
"""Server installation failed."""
|
mcsc/files.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Readers and writers for server configuration files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def read_properties(path: Path) -> dict[str, str]:
|
|
13
|
+
"""Parse a Java ``.properties`` file (``key=value`` lines, ``#`` comments)."""
|
|
14
|
+
result: dict[str, str] = {}
|
|
15
|
+
with open(path, encoding="utf-8") as file:
|
|
16
|
+
for raw in file:
|
|
17
|
+
line = raw.strip()
|
|
18
|
+
if not line or line.startswith(("#", "!")):
|
|
19
|
+
continue
|
|
20
|
+
key, sep, value = line.partition("=")
|
|
21
|
+
if sep:
|
|
22
|
+
result[key.strip()] = value.strip()
|
|
23
|
+
return result
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def write_properties(path: Path, values: dict[str, Any]) -> None:
|
|
27
|
+
"""Write ``values`` as ``key=value`` lines, keeping the file's leading comments."""
|
|
28
|
+
path = Path(path)
|
|
29
|
+
header: list[str] = []
|
|
30
|
+
if path.exists():
|
|
31
|
+
with open(path, encoding="utf-8") as file:
|
|
32
|
+
for line in file:
|
|
33
|
+
if not line.startswith("#"):
|
|
34
|
+
break
|
|
35
|
+
header.append(line.rstrip("\n"))
|
|
36
|
+
with open(path, "w", encoding="utf-8") as file:
|
|
37
|
+
for line in header:
|
|
38
|
+
file.write(line + "\n")
|
|
39
|
+
for key, value in values.items():
|
|
40
|
+
if isinstance(value, bool):
|
|
41
|
+
value = str(value).lower()
|
|
42
|
+
file.write(f"{key}={value}\n")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def read_yaml(path: Path) -> Any:
|
|
46
|
+
"""Load a YAML document (``{}`` for an empty file)."""
|
|
47
|
+
with open(path, encoding="utf-8") as file:
|
|
48
|
+
return yaml.safe_load(file) or {}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def write_yaml(path: Path, data: Any) -> None:
|
|
52
|
+
"""Dump ``data`` as YAML, preserving key order."""
|
|
53
|
+
with open(path, "w", encoding="utf-8") as file:
|
|
54
|
+
yaml.safe_dump(data, file, sort_keys=False, allow_unicode=True)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def read_config_file(path: Path) -> Any:
|
|
58
|
+
"""Read a config file, choosing the format from the extension."""
|
|
59
|
+
suffix = Path(path).suffix.lower()
|
|
60
|
+
if suffix == ".properties":
|
|
61
|
+
return read_properties(path)
|
|
62
|
+
if suffix in (".yml", ".yaml"):
|
|
63
|
+
return read_yaml(path)
|
|
64
|
+
if suffix == ".json":
|
|
65
|
+
with open(path, encoding="utf-8") as file:
|
|
66
|
+
return json.load(file)
|
|
67
|
+
raise ValueError(f"Unsupported config file type: {path}")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def write_config_file(path: Path, data: Any) -> None:
|
|
71
|
+
"""Write a config file, choosing the format from the extension."""
|
|
72
|
+
suffix = Path(path).suffix.lower()
|
|
73
|
+
if suffix == ".properties":
|
|
74
|
+
write_properties(path, data)
|
|
75
|
+
elif suffix in (".yml", ".yaml"):
|
|
76
|
+
write_yaml(path, data)
|
|
77
|
+
elif suffix == ".json":
|
|
78
|
+
with open(path, "w", encoding="utf-8") as file:
|
|
79
|
+
json.dump(data, file, indent=2)
|
|
80
|
+
else:
|
|
81
|
+
raise ValueError(f"Unsupported config file type: {path}")
|
mcsc/manager.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Registry of servers persisted to a JSON file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
from collections.abc import Iterator
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from mcsc.config import ServerConfig, ServerType
|
|
15
|
+
from mcsc.exceptions import ServerNotFoundError, ServerRunningError
|
|
16
|
+
from mcsc.servers import MinecraftServer, server_from_config
|
|
17
|
+
from mcsc.system import suggested_ram_gb
|
|
18
|
+
from mcsc.versions import VersionCatalog
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ServerManager:
|
|
24
|
+
"""Creates, loads, persists and deletes servers.
|
|
25
|
+
|
|
26
|
+
Every server gets its own folder under ``servers_dir``; their configs are
|
|
27
|
+
stored together in ``registry_file`` (default ``servers_dir/servers.json``).
|
|
28
|
+
The registry also reads the legacy minecraft-server-creator format.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
servers_dir: str | os.PathLike[str],
|
|
34
|
+
registry_file: str | os.PathLike[str] | None = None,
|
|
35
|
+
*,
|
|
36
|
+
catalog: VersionCatalog | None = None,
|
|
37
|
+
output_buffer: int = 300,
|
|
38
|
+
) -> None:
|
|
39
|
+
self.servers_dir = Path(servers_dir)
|
|
40
|
+
self.registry_file = Path(registry_file) if registry_file else self.servers_dir / "servers.json"
|
|
41
|
+
self.catalog = catalog or VersionCatalog()
|
|
42
|
+
self.output_buffer = output_buffer
|
|
43
|
+
self._servers: dict[str, MinecraftServer] = {}
|
|
44
|
+
|
|
45
|
+
# -------------------------------------------------------------- access
|
|
46
|
+
|
|
47
|
+
def __iter__(self) -> Iterator[MinecraftServer]:
|
|
48
|
+
return iter(list(self._servers.values()))
|
|
49
|
+
|
|
50
|
+
def __len__(self) -> int:
|
|
51
|
+
return len(self._servers)
|
|
52
|
+
|
|
53
|
+
def __contains__(self, item: object) -> bool:
|
|
54
|
+
server_id = item.id if isinstance(item, MinecraftServer) else item
|
|
55
|
+
return server_id in self._servers
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def servers(self) -> list[MinecraftServer]:
|
|
59
|
+
return list(self._servers.values())
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def active_servers(self) -> list[MinecraftServer]:
|
|
63
|
+
"""Servers with a running process."""
|
|
64
|
+
return [s for s in self._servers.values() if s.is_active]
|
|
65
|
+
|
|
66
|
+
def get(self, server_id: str) -> MinecraftServer:
|
|
67
|
+
try:
|
|
68
|
+
return self._servers[server_id]
|
|
69
|
+
except KeyError:
|
|
70
|
+
raise ServerNotFoundError(f"No server with id {server_id!r}") from None
|
|
71
|
+
|
|
72
|
+
def find(self, server_id: str) -> MinecraftServer | None:
|
|
73
|
+
return self._servers.get(server_id)
|
|
74
|
+
|
|
75
|
+
def find_by_name(self, name: str) -> MinecraftServer | None:
|
|
76
|
+
return next((s for s in self._servers.values() if s.name == name), None)
|
|
77
|
+
|
|
78
|
+
# --------------------------------------------------------- persistence
|
|
79
|
+
|
|
80
|
+
def load(self) -> list[MinecraftServer]:
|
|
81
|
+
"""Load servers from the registry file. Already loaded servers are kept as they are."""
|
|
82
|
+
self.servers_dir.mkdir(parents=True, exist_ok=True)
|
|
83
|
+
if not self.registry_file.exists():
|
|
84
|
+
return self.servers
|
|
85
|
+
|
|
86
|
+
with open(self.registry_file, encoding="utf-8") as file:
|
|
87
|
+
data: dict[str, dict[str, Any]] = json.load(file)
|
|
88
|
+
|
|
89
|
+
for key, entry in data.items():
|
|
90
|
+
try:
|
|
91
|
+
config = ServerConfig.from_dict({"id": key, **entry})
|
|
92
|
+
if config.path is None:
|
|
93
|
+
config.path = self.servers_dir / config.id
|
|
94
|
+
if config.id not in self._servers:
|
|
95
|
+
self._servers[config.id] = server_from_config(
|
|
96
|
+
config, output_buffer=self.output_buffer
|
|
97
|
+
)
|
|
98
|
+
except Exception: # noqa: BLE001 - one broken entry must not hide the others
|
|
99
|
+
logger.exception("Can't load server %s", key)
|
|
100
|
+
logger.info("Loaded %d servers from %s", len(self._servers), self.registry_file)
|
|
101
|
+
return self.servers
|
|
102
|
+
|
|
103
|
+
def save(self) -> None:
|
|
104
|
+
"""Write all server configs to the registry file (atomically)."""
|
|
105
|
+
self.registry_file.parent.mkdir(parents=True, exist_ok=True)
|
|
106
|
+
data = {s.id: s.config.to_dict() for s in self._servers.values()}
|
|
107
|
+
tmp = self.registry_file.with_name(self.registry_file.name + ".tmp")
|
|
108
|
+
with open(tmp, "w", encoding="utf-8") as file:
|
|
109
|
+
json.dump(data, file, indent=4)
|
|
110
|
+
os.replace(tmp, self.registry_file)
|
|
111
|
+
|
|
112
|
+
# ----------------------------------------------------------- mutations
|
|
113
|
+
|
|
114
|
+
def register(self, config: ServerConfig) -> MinecraftServer:
|
|
115
|
+
"""Add an already installed server (e.g. imported or migrated) and save."""
|
|
116
|
+
if config.path is None:
|
|
117
|
+
config.path = self.servers_dir / config.id
|
|
118
|
+
if config.id in self._servers:
|
|
119
|
+
raise ValueError(f"Server {config.id!r} already registered")
|
|
120
|
+
server = server_from_config(config, output_buffer=self.output_buffer)
|
|
121
|
+
self._servers[config.id] = server
|
|
122
|
+
self.save()
|
|
123
|
+
return server
|
|
124
|
+
|
|
125
|
+
def create(
|
|
126
|
+
self,
|
|
127
|
+
name: str,
|
|
128
|
+
version: str,
|
|
129
|
+
server_type: ServerType = ServerType.VANILLA,
|
|
130
|
+
*,
|
|
131
|
+
accept_eula: bool = False,
|
|
132
|
+
ram_gb: int | None = None,
|
|
133
|
+
**config_options: Any,
|
|
134
|
+
) -> MinecraftServer:
|
|
135
|
+
"""Download, install and register a new server. Blocking.
|
|
136
|
+
|
|
137
|
+
``config_options`` are passed to :class:`ServerConfig` (port, java_path, ...).
|
|
138
|
+
The server can only start once the EULA is accepted, either here or
|
|
139
|
+
later with :meth:`MinecraftServer.accept_eula`.
|
|
140
|
+
"""
|
|
141
|
+
name = name.strip()
|
|
142
|
+
if not name:
|
|
143
|
+
raise ValueError("Server name can't be empty")
|
|
144
|
+
if not version:
|
|
145
|
+
raise ValueError("Server version can't be empty")
|
|
146
|
+
|
|
147
|
+
server_type = ServerType(server_type)
|
|
148
|
+
url = self.catalog.download_url(server_type, version)
|
|
149
|
+
config = ServerConfig(
|
|
150
|
+
name=name,
|
|
151
|
+
version=version,
|
|
152
|
+
server_type=server_type,
|
|
153
|
+
ram_gb=ram_gb or suggested_ram_gb(),
|
|
154
|
+
**config_options,
|
|
155
|
+
)
|
|
156
|
+
config.path = self.servers_dir / config.id
|
|
157
|
+
server = server_from_config(config, output_buffer=self.output_buffer)
|
|
158
|
+
|
|
159
|
+
config.path.mkdir(parents=True)
|
|
160
|
+
try:
|
|
161
|
+
server.install(url, accept_eula=accept_eula)
|
|
162
|
+
except BaseException:
|
|
163
|
+
shutil.rmtree(config.path, ignore_errors=True)
|
|
164
|
+
raise
|
|
165
|
+
|
|
166
|
+
self._servers[config.id] = server
|
|
167
|
+
self.save()
|
|
168
|
+
logger.info("Created %r", server)
|
|
169
|
+
return server
|
|
170
|
+
|
|
171
|
+
async def create_async(self, *args: Any, **kwargs: Any) -> MinecraftServer:
|
|
172
|
+
""":meth:`create` in a worker thread, so the event loop isn't blocked."""
|
|
173
|
+
return await asyncio.to_thread(self.create, *args, **kwargs)
|
|
174
|
+
|
|
175
|
+
def delete(self, server: MinecraftServer | str, *, delete_files: bool = False) -> None:
|
|
176
|
+
"""Unregister a stopped server, optionally removing its folder."""
|
|
177
|
+
if isinstance(server, str):
|
|
178
|
+
server = self.get(server)
|
|
179
|
+
if server.is_active:
|
|
180
|
+
raise ServerRunningError(f"Can't delete server {server.name!r} while it's {server.state}")
|
|
181
|
+
if server.id not in self._servers:
|
|
182
|
+
raise ServerNotFoundError(f"No server with id {server.id!r}")
|
|
183
|
+
|
|
184
|
+
del self._servers[server.id]
|
|
185
|
+
self.save()
|
|
186
|
+
if delete_files and server.path.exists():
|
|
187
|
+
shutil.rmtree(server.path)
|
|
188
|
+
logger.info("Deleted %r (files removed: %s)", server, delete_files)
|
|
189
|
+
|
|
190
|
+
async def stop_all(self, timeout: float | None = 60) -> None:
|
|
191
|
+
"""Stop every running server concurrently."""
|
|
192
|
+
servers = self.active_servers
|
|
193
|
+
if servers:
|
|
194
|
+
logger.info("Stopping %d servers", len(servers))
|
|
195
|
+
await asyncio.gather(*(s.stop(timeout) for s in servers), return_exceptions=True)
|
mcsc/monitor.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Resource usage monitoring for server processes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
import psutil
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
_MB = 1024 * 1024
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class ResourceUsage:
|
|
18
|
+
"""Resource usage of a process tree over the last sampling interval."""
|
|
19
|
+
|
|
20
|
+
ram_mb: float = 0.0
|
|
21
|
+
cpu_percent: float = 0.0
|
|
22
|
+
disk_read_mb: float = 0.0
|
|
23
|
+
disk_write_mb: float = 0.0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ProcessMonitor:
|
|
27
|
+
"""Periodically samples RAM/CPU/disk usage of a process and its children.
|
|
28
|
+
|
|
29
|
+
Read :attr:`usage` for the latest sample; it resets to zeros when the
|
|
30
|
+
monitor stops.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, interval: float = 1.0) -> None:
|
|
34
|
+
self.interval = interval
|
|
35
|
+
self.usage = ResourceUsage()
|
|
36
|
+
self.active = False
|
|
37
|
+
self._procs: dict[int, psutil.Process] = {}
|
|
38
|
+
self._prev_io: tuple[int, int] | None = None
|
|
39
|
+
|
|
40
|
+
def __repr__(self) -> str:
|
|
41
|
+
return f"ProcessMonitor(active={self.active}, usage={self.usage})"
|
|
42
|
+
|
|
43
|
+
def _tree(self, root: psutil.Process) -> list[psutil.Process]:
|
|
44
|
+
# Reuse Process objects so cpu_percent() measures since the previous sample.
|
|
45
|
+
current = [root, *root.children(recursive=True)]
|
|
46
|
+
tree = []
|
|
47
|
+
for proc in current:
|
|
48
|
+
tree.append(self._procs.setdefault(proc.pid, proc))
|
|
49
|
+
alive = {p.pid for p in current}
|
|
50
|
+
for pid in list(self._procs):
|
|
51
|
+
if pid not in alive:
|
|
52
|
+
del self._procs[pid]
|
|
53
|
+
return tree
|
|
54
|
+
|
|
55
|
+
def _sample(self, root: psutil.Process) -> ResourceUsage:
|
|
56
|
+
ram = cpu = 0.0
|
|
57
|
+
read = write = 0
|
|
58
|
+
for proc in self._tree(root):
|
|
59
|
+
try:
|
|
60
|
+
with proc.oneshot():
|
|
61
|
+
ram += proc.memory_info().rss
|
|
62
|
+
cpu += proc.cpu_percent(interval=None)
|
|
63
|
+
try:
|
|
64
|
+
io = proc.io_counters()
|
|
65
|
+
read += io.read_bytes
|
|
66
|
+
write += io.write_bytes
|
|
67
|
+
except (AttributeError, psutil.AccessDenied):
|
|
68
|
+
pass # io_counters is unavailable on macOS
|
|
69
|
+
except psutil.NoSuchProcess:
|
|
70
|
+
continue
|
|
71
|
+
|
|
72
|
+
prev_read, prev_write = self._prev_io or (read, write)
|
|
73
|
+
self._prev_io = (read, write)
|
|
74
|
+
return ResourceUsage(
|
|
75
|
+
ram_mb=round(ram / _MB, 2),
|
|
76
|
+
cpu_percent=round(cpu, 2),
|
|
77
|
+
disk_read_mb=round(max(read - prev_read, 0) / _MB, 2),
|
|
78
|
+
disk_write_mb=round(max(write - prev_write, 0) / _MB, 2),
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
async def run(self, pid: int) -> None:
|
|
82
|
+
"""Sample process ``pid`` every :attr:`interval` seconds until it exits or :meth:`stop` is called."""
|
|
83
|
+
if self.active:
|
|
84
|
+
return
|
|
85
|
+
try:
|
|
86
|
+
root = psutil.Process(pid)
|
|
87
|
+
except psutil.NoSuchProcess:
|
|
88
|
+
return
|
|
89
|
+
self.active = True
|
|
90
|
+
self._procs.clear()
|
|
91
|
+
self._prev_io = None
|
|
92
|
+
try:
|
|
93
|
+
while self.active and root.is_running():
|
|
94
|
+
self.usage = self._sample(root)
|
|
95
|
+
await asyncio.sleep(self.interval)
|
|
96
|
+
except psutil.NoSuchProcess:
|
|
97
|
+
pass
|
|
98
|
+
except Exception: # noqa: BLE001 - monitoring must never crash the server task
|
|
99
|
+
logger.exception("Error monitoring process %s", pid)
|
|
100
|
+
finally:
|
|
101
|
+
self.stop()
|
|
102
|
+
|
|
103
|
+
def stop(self) -> None:
|
|
104
|
+
"""Stop sampling and reset :attr:`usage`."""
|
|
105
|
+
self.active = False
|
|
106
|
+
self.usage = ResourceUsage()
|
|
107
|
+
self._procs.clear()
|
mcsc/py.typed
ADDED
|
File without changes
|
mcsc/servers/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Server types."""
|
|
2
|
+
|
|
3
|
+
from mcsc.config import ServerConfig, ServerType
|
|
4
|
+
from mcsc.servers.base import MinecraftServer, OutputListener, StateListener
|
|
5
|
+
from mcsc.servers.forge import ForgeServer
|
|
6
|
+
from mcsc.servers.paper import PaperServer
|
|
7
|
+
from mcsc.servers.vanilla import VanillaServer
|
|
8
|
+
|
|
9
|
+
SERVER_CLASSES: dict[ServerType, type[MinecraftServer]] = {
|
|
10
|
+
ServerType.VANILLA: VanillaServer,
|
|
11
|
+
ServerType.PAPER: PaperServer,
|
|
12
|
+
ServerType.FORGE: ForgeServer,
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def server_from_config(config: ServerConfig, **kwargs) -> MinecraftServer:
|
|
17
|
+
"""Instantiate the right :class:`MinecraftServer` subclass for ``config``."""
|
|
18
|
+
return SERVER_CLASSES[config.server_type](config, **kwargs)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"SERVER_CLASSES",
|
|
23
|
+
"ForgeServer",
|
|
24
|
+
"MinecraftServer",
|
|
25
|
+
"OutputListener",
|
|
26
|
+
"PaperServer",
|
|
27
|
+
"StateListener",
|
|
28
|
+
"VanillaServer",
|
|
29
|
+
"server_from_config",
|
|
30
|
+
]
|