dismanager 1.0.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.
- dismanager/__init__.py +0 -0
- dismanager/classes/__init__.py +8 -0
- dismanager/classes/addon.py +43 -0
- dismanager/classes/plugin.py +33 -0
- dismanager/cli.py +41 -0
- dismanager/core/__init__.py +0 -0
- dismanager/core/bootstrap/__init__.py +20 -0
- dismanager/core/bootstrap/config.py +112 -0
- dismanager/core/bootstrap/i18n.py +28 -0
- dismanager/core/bootstrap/logs.py +117 -0
- dismanager/core/bootstrap/paths.py +14 -0
- dismanager/core/commands/__init__.py +15 -0
- dismanager/core/commands/dispatcher.py +137 -0
- dismanager/core/extensions/__init__.py +19 -0
- dismanager/core/extensions/loader.py +109 -0
- dismanager/core/files/__init__.py +57 -0
- dismanager/core/files/archive_operations.py +236 -0
- dismanager/core/files/file_operations.py +150 -0
- dismanager/core/files/file_preview.py +94 -0
- dismanager/core/files/sandbox_paths.py +121 -0
- dismanager/core/files/text_files.py +120 -0
- dismanager/core/format/__init__.py +5 -0
- dismanager/core/format/bytes.py +10 -0
- dismanager/core/logs/__init__.py +6 -0
- dismanager/core/logs/buffer.py +43 -0
- dismanager/core/logs/writer.py +72 -0
- dismanager/core/managed_process/__init__.py +6 -0
- dismanager/core/managed_process/managers/__init__.py +16 -0
- dismanager/core/managed_process/managers/backups.py +145 -0
- dismanager/core/managed_process/managers/console_thread.py +231 -0
- dismanager/core/managed_process/managers/logger.py +61 -0
- dismanager/core/managed_process/managers/plugins.py +113 -0
- dismanager/core/managed_process/managers/runner.py +252 -0
- dismanager/core/managed_process/process.py +201 -0
- dismanager/core/process_store/__init__.py +11 -0
- dismanager/core/process_store/config.py +22 -0
- dismanager/core/process_store/store.py +218 -0
- dismanager/core/system/__init__.py +6 -0
- dismanager/core/system/metrics.py +92 -0
- dismanager/discord/__init__.py +0 -0
- dismanager/discord/client/__init__.py +5 -0
- dismanager/discord/client/client.py +165 -0
- dismanager/discord/client/cogs/__init__.py +18 -0
- dismanager/discord/client/cogs/commands.py +127 -0
- dismanager/discord/client/cogs/events.py +74 -0
- dismanager/discord/client/managers/__init__.py +8 -0
- dismanager/discord/client/managers/addons.py +107 -0
- dismanager/discord/client/managers/console.py +175 -0
- dismanager/discord/client/managers/panel.py +129 -0
- dismanager/discord/client/managers/processes.py +126 -0
- dismanager/discord/panel/__init__.py +6 -0
- dismanager/discord/panel/backups/__init__.py +5 -0
- dismanager/discord/panel/backups/views.py +297 -0
- dismanager/discord/panel/embed.py +216 -0
- dismanager/discord/panel/files/__init__.py +5 -0
- dismanager/discord/panel/files/actions.py +330 -0
- dismanager/discord/panel/files/embed.py +115 -0
- dismanager/discord/panel/files/modals.py +319 -0
- dismanager/discord/panel/files/preview.py +92 -0
- dismanager/discord/panel/files/views.py +226 -0
- dismanager/discord/panel/guide/__init__.py +3 -0
- dismanager/discord/panel/guide/embed.py +211 -0
- dismanager/discord/panel/guide/views.py +91 -0
- dismanager/discord/panel/processes/__init__.py +5 -0
- dismanager/discord/panel/processes/embed.py +24 -0
- dismanager/discord/panel/processes/modals.py +168 -0
- dismanager/discord/panel/processes/views.py +95 -0
- dismanager/discord/panel/views.py +112 -0
- dismanager/discord/utils/__init__.py +6 -0
- dismanager/discord/utils/confirm.py +45 -0
- dismanager/discord/utils/threads.py +26 -0
- dismanager/locales/es/LC_MESSAGES/app.mo +0 -0
- dismanager/main.py +55 -0
- dismanager/py.typed +0 -0
- dismanager/templates/config.yml +33 -0
- dismanager-1.0.0.dist-info/METADATA +86 -0
- dismanager-1.0.0.dist-info/RECORD +81 -0
- dismanager-1.0.0.dist-info/WHEEL +5 -0
- dismanager-1.0.0.dist-info/entry_points.txt +2 -0
- dismanager-1.0.0.dist-info/licenses/LICENSE +165 -0
- dismanager-1.0.0.dist-info/top_level.txt +1 -0
dismanager/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from ..core.managed_process import ManagedProcess
|
|
4
|
+
from ..discord.client import DisManagerClient
|
|
5
|
+
from .addon import BaseAddon
|
|
6
|
+
from .plugin import BasePlugin
|
|
7
|
+
|
|
8
|
+
__all__ = ['BaseAddon', 'BasePlugin', 'DisManagerClient', 'ManagedProcess']
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from ..core.managed_process import ManagedProcess
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class BaseAddon:
|
|
7
|
+
"""Optional base class providing typed hook signatures for DisManager addons."""
|
|
8
|
+
|
|
9
|
+
def unload(self) -> object:
|
|
10
|
+
"""Called when the addon is unloaded or reloaded."""
|
|
11
|
+
return None
|
|
12
|
+
|
|
13
|
+
async def on_addons_load(self) -> object:
|
|
14
|
+
"""Called after all addons have been imported."""
|
|
15
|
+
return None
|
|
16
|
+
|
|
17
|
+
async def on_addons_unload(self) -> object:
|
|
18
|
+
"""Called before addons are unloaded."""
|
|
19
|
+
return None
|
|
20
|
+
|
|
21
|
+
async def on_plugins_load(self, process: ManagedProcess) -> object:
|
|
22
|
+
"""Called when a process finishes loading its plugins."""
|
|
23
|
+
return None
|
|
24
|
+
|
|
25
|
+
async def on_plugins_unload(self, process: ManagedProcess) -> object:
|
|
26
|
+
"""Called before a process unloads its plugins."""
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
async def on_process_start(self, process: ManagedProcess) -> object:
|
|
30
|
+
"""Called when a managed process starts."""
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
async def on_process_stop(self, process: ManagedProcess) -> object:
|
|
34
|
+
"""Called when a managed process is requested to stop or kill."""
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
async def on_process_crash(self, process: ManagedProcess) -> object:
|
|
38
|
+
"""Called when a managed process exits unexpectedly with a non-zero code."""
|
|
39
|
+
return None
|
|
40
|
+
|
|
41
|
+
async def on_process_log(self, process: ManagedProcess, log: str) -> object:
|
|
42
|
+
"""Called for each filtered console output line emitted by ``process``."""
|
|
43
|
+
return None
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class BasePlugin:
|
|
5
|
+
"""Optional base class providing typed hook signatures for per-process plugins."""
|
|
6
|
+
|
|
7
|
+
def unload(self) -> object:
|
|
8
|
+
"""Called when the plugin is unloaded or reloaded."""
|
|
9
|
+
return None
|
|
10
|
+
|
|
11
|
+
async def on_plugins_load(self) -> object:
|
|
12
|
+
"""Called after this process's plugins have been imported."""
|
|
13
|
+
return None
|
|
14
|
+
|
|
15
|
+
async def on_plugins_unload(self) -> object:
|
|
16
|
+
"""Called before this process's plugins are unloaded."""
|
|
17
|
+
return None
|
|
18
|
+
|
|
19
|
+
async def on_process_start(self) -> object:
|
|
20
|
+
"""Called when the owning process starts."""
|
|
21
|
+
return None
|
|
22
|
+
|
|
23
|
+
async def on_process_stop(self) -> object:
|
|
24
|
+
"""Called when the owning process is requested to stop or kill."""
|
|
25
|
+
return None
|
|
26
|
+
|
|
27
|
+
async def on_process_crash(self) -> object:
|
|
28
|
+
"""Called when the owning process exits unexpectedly with a non-zero code."""
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
async def on_process_log(self, log: str) -> object:
|
|
32
|
+
"""Called for each filtered console output line emitted by the process."""
|
|
33
|
+
return None
|
dismanager/cli.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import shutil
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from .main import run
|
|
8
|
+
|
|
9
|
+
_TEMPLATES_DIR = Path(__file__).resolve().parent / 'templates'
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def init() -> None:
|
|
13
|
+
"""Initialize the project by copying the default configuration template."""
|
|
14
|
+
target = Path('config.yml')
|
|
15
|
+
source = _TEMPLATES_DIR / 'config.yml'
|
|
16
|
+
if not target.exists():
|
|
17
|
+
shutil.copy(source, target)
|
|
18
|
+
|
|
19
|
+
print('✔ Successfully generated config.yml.')
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def main() -> None:
|
|
23
|
+
"""Parse CLI arguments and dispatch the requested subcommand."""
|
|
24
|
+
parser = argparse.ArgumentParser(description='DisManager CLI')
|
|
25
|
+
subparsers = parser.add_subparsers(dest='command')
|
|
26
|
+
|
|
27
|
+
init_parser = subparsers.add_parser('init', help='Initialize the project')
|
|
28
|
+
init_parser.set_defaults(func=init)
|
|
29
|
+
|
|
30
|
+
run_parser = subparsers.add_parser('run', help='Run DisManager')
|
|
31
|
+
run_parser.set_defaults(func=run)
|
|
32
|
+
|
|
33
|
+
args = parser.parse_args()
|
|
34
|
+
if args.command:
|
|
35
|
+
args.func()
|
|
36
|
+
else:
|
|
37
|
+
parser.print_help()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
if __name__ == '__main__':
|
|
41
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .config import ConfigError, DisManagerConfig, load_config
|
|
4
|
+
from .i18n import _, init_i18n
|
|
5
|
+
from .logs import LogSession
|
|
6
|
+
from .paths import ADDONS_DIR, BACKUPS_DIR, DATA_DIR, LOGS_DIR, ensure_workspace_dirs
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
'ADDONS_DIR',
|
|
10
|
+
'BACKUPS_DIR',
|
|
11
|
+
'ConfigError',
|
|
12
|
+
'DATA_DIR',
|
|
13
|
+
'DisManagerConfig',
|
|
14
|
+
'LOGS_DIR',
|
|
15
|
+
'LogSession',
|
|
16
|
+
'_',
|
|
17
|
+
'ensure_workspace_dirs',
|
|
18
|
+
'init_i18n',
|
|
19
|
+
'load_config',
|
|
20
|
+
]
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, TypeGuard
|
|
7
|
+
|
|
8
|
+
from ruamel.yaml import YAML
|
|
9
|
+
from ruamel.yaml.error import YAMLError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ConfigError(Exception):
|
|
13
|
+
"""Raised when the DisManager configuration file cannot be read or is invalid."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class DisManagerConfig:
|
|
18
|
+
"""Validated runtime configuration for DisManager."""
|
|
19
|
+
|
|
20
|
+
bot_token : str
|
|
21
|
+
bot_prefix : str
|
|
22
|
+
panel_id : int
|
|
23
|
+
language : str
|
|
24
|
+
backups : int
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def load_config() -> DisManagerConfig:
|
|
28
|
+
"""Load and validate a YAML configuration file from disk."""
|
|
29
|
+
config_path = Path('config.yml')
|
|
30
|
+
yaml = YAML(typ='safe')
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
content = config_path.read_text(encoding='utf-8')
|
|
34
|
+
except OSError as exc:
|
|
35
|
+
raise ConfigError(f"The file '{config_path}' could not be opened: {exc}") from exc
|
|
36
|
+
|
|
37
|
+
try:
|
|
38
|
+
raw: object = yaml.load(content)
|
|
39
|
+
except YAMLError as exc:
|
|
40
|
+
raise ConfigError(f"The file '{config_path}' contains invalid YAML: {exc}") from exc
|
|
41
|
+
|
|
42
|
+
return _validate_config(raw)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# =========================================
|
|
46
|
+
# Internal Helpers
|
|
47
|
+
# =========================================
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _validate_config(raw: object) -> DisManagerConfig:
|
|
51
|
+
if not isinstance(raw, Mapping):
|
|
52
|
+
raise ConfigError('Configuration root must be a YAML mapping.')
|
|
53
|
+
|
|
54
|
+
return DisManagerConfig(
|
|
55
|
+
bot_token=_require_non_empty_str(raw, 'Bot Token'),
|
|
56
|
+
bot_prefix=_parse_bot_prefix(raw),
|
|
57
|
+
panel_id=_parse_panel_id(raw),
|
|
58
|
+
language=_parse_language(raw),
|
|
59
|
+
backups=_parse_backups(raw),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _is_strict_int(value: object) -> TypeGuard[int]:
|
|
64
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _require_non_empty_str(data: Mapping[str, Any], key: str) -> str:
|
|
68
|
+
value = data.get(key)
|
|
69
|
+
if not isinstance(value, str) or not value.strip():
|
|
70
|
+
raise ConfigError(f"The '{key}' variable must be a non-empty string.")
|
|
71
|
+
return value.strip()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _parse_bot_prefix(data: Mapping[str, Any]) -> str:
|
|
75
|
+
default_prefix = '!!'
|
|
76
|
+
value = data.get('Bot Prefix')
|
|
77
|
+
if value is None:
|
|
78
|
+
return default_prefix
|
|
79
|
+
if not isinstance(value, str) or not value.strip():
|
|
80
|
+
raise ConfigError("The 'Bot Prefix' variable must be a non-empty string or null.")
|
|
81
|
+
return value
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _parse_panel_id(data: Mapping[str, Any]) -> int:
|
|
85
|
+
value = data.get('Panel ID')
|
|
86
|
+
if not _is_strict_int(value) or value <= 0:
|
|
87
|
+
raise ConfigError("The 'Panel ID' variable must be a positive integer.")
|
|
88
|
+
return value
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _parse_language(data: Mapping[str, Any]) -> str:
|
|
92
|
+
allowed_languages: tuple[str, ...] = ('en', 'es')
|
|
93
|
+
value = data.get('Language')
|
|
94
|
+
if not isinstance(value, str) or value not in allowed_languages:
|
|
95
|
+
allowed = ', '.join(allowed_languages)
|
|
96
|
+
raise ConfigError(f"The 'Language' variable must be one of the following: {allowed}.")
|
|
97
|
+
return value
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _parse_backups(data: Mapping[str, Any]) -> int:
|
|
101
|
+
min_backups = 1
|
|
102
|
+
max_backups = 5
|
|
103
|
+
value = data.get('Backups')
|
|
104
|
+
if not _is_strict_int(value):
|
|
105
|
+
raise ConfigError(
|
|
106
|
+
f"The 'Backups' variable must be an integer between {min_backups} and {max_backups}."
|
|
107
|
+
)
|
|
108
|
+
if not (min_backups <= value <= max_backups):
|
|
109
|
+
raise ConfigError(
|
|
110
|
+
f"The 'Backups' variable must be between {min_backups} and {max_backups}, not {value}."
|
|
111
|
+
)
|
|
112
|
+
return value
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import gettext
|
|
4
|
+
import logging
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
_LOCALES_DIR = Path(__file__).resolve().parent.parent.parent / 'locales'
|
|
8
|
+
_logger = logging.getLogger(__name__)
|
|
9
|
+
_translations: gettext.NullTranslations = gettext.NullTranslations()
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def init_i18n(language: str) -> None:
|
|
13
|
+
"""Load gettext translations for ``language`` into the active module translator."""
|
|
14
|
+
global _translations
|
|
15
|
+
if language == 'en':
|
|
16
|
+
_translations = gettext.NullTranslations()
|
|
17
|
+
return
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
_translations = gettext.translation('app', localedir=str(_LOCALES_DIR), languages=[language])
|
|
21
|
+
except (OSError, ValueError) as exc:
|
|
22
|
+
_logger.warning("Could not load translations for '%s': %s", language, exc)
|
|
23
|
+
_translations = gettext.NullTranslations()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _(text: str) -> str:
|
|
27
|
+
"""Translate ``text`` using the active DisManager language."""
|
|
28
|
+
return _translations.gettext(text)
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import sys
|
|
5
|
+
from typing import TextIO
|
|
6
|
+
|
|
7
|
+
from ..logs import ByteRingBuffer, SessionLogWriter
|
|
8
|
+
from .paths import LOGS_DIR
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class LogSession:
|
|
12
|
+
"""Active logging session for a single DisManager execution."""
|
|
13
|
+
|
|
14
|
+
_console_handler: logging.StreamHandler[TextIO] | None
|
|
15
|
+
|
|
16
|
+
def __init__(self) -> None:
|
|
17
|
+
console_handler = logging.StreamHandler(sys.stderr)
|
|
18
|
+
self._writer = SessionLogWriter(LOGS_DIR)
|
|
19
|
+
self._file_handler = _CappedFileHandler(self._writer)
|
|
20
|
+
self._memory_handler = _MemoryRingHandler()
|
|
21
|
+
self._console_handler = console_handler
|
|
22
|
+
self._dismanager_logger = logging.getLogger('dismanager')
|
|
23
|
+
self._discord_logger = logging.getLogger('discord')
|
|
24
|
+
self._attach_handlers(console_handler)
|
|
25
|
+
|
|
26
|
+
def _attach_handlers(self, console_handler: logging.StreamHandler[TextIO]) -> None:
|
|
27
|
+
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
|
|
28
|
+
self._file_handler.setFormatter(formatter)
|
|
29
|
+
self._memory_handler.setFormatter(formatter)
|
|
30
|
+
|
|
31
|
+
console_handler.setLevel(logging.WARNING)
|
|
32
|
+
console_handler.setFormatter(_ShortConsoleFormatter())
|
|
33
|
+
|
|
34
|
+
self._dismanager_logger.setLevel(logging.INFO)
|
|
35
|
+
self._dismanager_logger.propagate = False
|
|
36
|
+
self._dismanager_logger.addHandler(self._file_handler)
|
|
37
|
+
self._dismanager_logger.addHandler(self._memory_handler)
|
|
38
|
+
self._dismanager_logger.addHandler(console_handler)
|
|
39
|
+
|
|
40
|
+
self._discord_logger.setLevel(logging.WARNING)
|
|
41
|
+
self._discord_logger.propagate = False
|
|
42
|
+
self._discord_logger.addHandler(self._file_handler)
|
|
43
|
+
self._discord_logger.addHandler(self._memory_handler)
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def filename(self) -> str:
|
|
47
|
+
"""Return the active session log filename."""
|
|
48
|
+
return self._writer.path.name
|
|
49
|
+
|
|
50
|
+
def recent_bytes(self) -> bytes:
|
|
51
|
+
"""Return up to the last 8 MB of formatted log records from this session."""
|
|
52
|
+
return self._memory_handler.get_bytes()
|
|
53
|
+
|
|
54
|
+
def mute_console(self) -> None:
|
|
55
|
+
"""Detach and close the temporary startup console handler once the UI is ready."""
|
|
56
|
+
if self._console_handler is None:
|
|
57
|
+
return
|
|
58
|
+
self._dismanager_logger.removeHandler(self._console_handler)
|
|
59
|
+
self._console_handler.close()
|
|
60
|
+
self._console_handler = None
|
|
61
|
+
|
|
62
|
+
def unmute_console(self) -> None:
|
|
63
|
+
"""Re-attach a stderr console handler (e.g. for fatal shutdown errors)."""
|
|
64
|
+
if self._console_handler is not None:
|
|
65
|
+
return
|
|
66
|
+
console_handler = logging.StreamHandler(sys.stderr)
|
|
67
|
+
console_handler.setLevel(logging.WARNING)
|
|
68
|
+
console_handler.setFormatter(_ShortConsoleFormatter())
|
|
69
|
+
self._dismanager_logger.addHandler(console_handler)
|
|
70
|
+
self._console_handler = console_handler
|
|
71
|
+
|
|
72
|
+
def close(self) -> None:
|
|
73
|
+
"""Detach all session handlers from loggers and close underlying streams."""
|
|
74
|
+
self.mute_console()
|
|
75
|
+
for logger in (self._dismanager_logger, self._discord_logger):
|
|
76
|
+
logger.removeHandler(self._file_handler)
|
|
77
|
+
logger.removeHandler(self._memory_handler)
|
|
78
|
+
self._file_handler.close()
|
|
79
|
+
self._memory_handler.close()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# =========================================
|
|
83
|
+
# Internal Helpers
|
|
84
|
+
# =========================================
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class _CappedFileHandler(logging.Handler):
|
|
88
|
+
def __init__(self, writer: SessionLogWriter) -> None:
|
|
89
|
+
super().__init__()
|
|
90
|
+
self._writer = writer
|
|
91
|
+
|
|
92
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
93
|
+
# Format the LogRecord (timestamp, level, module, message/traceback) and write it to disk.
|
|
94
|
+
self._writer.write_line(self.format(record))
|
|
95
|
+
|
|
96
|
+
def close(self) -> None:
|
|
97
|
+
# Close the underlying file first, then release the handler from logging.
|
|
98
|
+
self._writer.close()
|
|
99
|
+
super().close()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class _MemoryRingHandler(logging.Handler):
|
|
103
|
+
def __init__(self) -> None:
|
|
104
|
+
super().__init__()
|
|
105
|
+
self._buffer = ByteRingBuffer()
|
|
106
|
+
|
|
107
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
108
|
+
# Store the formatted line in the in-memory ring buffer.
|
|
109
|
+
self._buffer.append(self.format(record))
|
|
110
|
+
|
|
111
|
+
def get_bytes(self) -> bytes:
|
|
112
|
+
return self._buffer.get_bytes()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class _ShortConsoleFormatter(logging.Formatter):
|
|
116
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
117
|
+
return f'[{record.levelname}] {record.getMessage()}'
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
DATA_DIR = Path('.dismanager')
|
|
6
|
+
LOGS_DIR = DATA_DIR / 'logs'
|
|
7
|
+
BACKUPS_DIR = Path('.backups')
|
|
8
|
+
ADDONS_DIR = Path('.addons')
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def ensure_workspace_dirs() -> None:
|
|
12
|
+
"""Create the runtime workspace directories if they do not exist."""
|
|
13
|
+
for directory in (DATA_DIR, LOGS_DIR, BACKUPS_DIR, ADDONS_DIR):
|
|
14
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .dispatcher import (
|
|
4
|
+
ProcessAction,
|
|
5
|
+
reload_addons_command,
|
|
6
|
+
run_all_processes_action,
|
|
7
|
+
run_process_action,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
'ProcessAction',
|
|
12
|
+
'reload_addons_command',
|
|
13
|
+
'run_all_processes_action',
|
|
14
|
+
'run_process_action',
|
|
15
|
+
]
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
from typing import TYPE_CHECKING, Literal
|
|
6
|
+
|
|
7
|
+
from ..bootstrap.i18n import _
|
|
8
|
+
from ..process_store import ProcessConfigError
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from ...discord.client import DisManagerClient
|
|
12
|
+
from ..managed_process import ManagedProcess
|
|
13
|
+
|
|
14
|
+
ProcessAction = Literal['start', 'stop', 'kill', 'restart', 'plreload']
|
|
15
|
+
|
|
16
|
+
_logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def run_process_action(
|
|
20
|
+
client: DisManagerClient,
|
|
21
|
+
action: ProcessAction,
|
|
22
|
+
name: str,
|
|
23
|
+
*,
|
|
24
|
+
markdown: bool = False,
|
|
25
|
+
source: str = 'unknown',
|
|
26
|
+
) -> tuple[bool, str]:
|
|
27
|
+
"""Resolve a process by name, run ``action``, and return ``(ok, message)``."""
|
|
28
|
+
tick = '`' if markdown else ''
|
|
29
|
+
prefix = client.config.bot_prefix if markdown else ''
|
|
30
|
+
target = name.strip()
|
|
31
|
+
if not target:
|
|
32
|
+
return _format_result(
|
|
33
|
+
False,
|
|
34
|
+
_('Specify the process. E.g.: {0}{1}{2} <name>{0} or {0}{1}{2}-all{0}').format(
|
|
35
|
+
tick, prefix, action
|
|
36
|
+
),
|
|
37
|
+
markdown=markdown,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
process = client.find_process(target)
|
|
41
|
+
if process is None:
|
|
42
|
+
_logger.info("Control action '%s' on '%s' requested by %s -> not found", action, target, source)
|
|
43
|
+
ref = f'`{target}`' if markdown else f"'{target}'"
|
|
44
|
+
return _format_result(False, _('Process {} not found.').format(ref), markdown=markdown)
|
|
45
|
+
|
|
46
|
+
ok, detail = await _execute_process_action(process, action)
|
|
47
|
+
_logger.info(
|
|
48
|
+
"Control action '%s' on '%s' requested by %s -> %s",
|
|
49
|
+
action,
|
|
50
|
+
process.name,
|
|
51
|
+
source,
|
|
52
|
+
'ok' if ok else 'failed',
|
|
53
|
+
)
|
|
54
|
+
return _format_result(ok, f'{tick}[{process.name}]{tick}: {detail}', markdown=markdown)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def run_all_processes_action(
|
|
58
|
+
client: DisManagerClient,
|
|
59
|
+
action: ProcessAction,
|
|
60
|
+
*,
|
|
61
|
+
markdown: bool = False,
|
|
62
|
+
source: str = 'unknown',
|
|
63
|
+
) -> tuple[bool, str]:
|
|
64
|
+
"""Run ``action`` across all configured processes and return ``(ok, summary)``."""
|
|
65
|
+
processes = client.processes
|
|
66
|
+
if not processes:
|
|
67
|
+
_logger.info("Control action '%s-all' requested by %s -> no processes", action, source)
|
|
68
|
+
return _format_result(False, _('No processes configured.'), markdown=markdown)
|
|
69
|
+
|
|
70
|
+
tick = '`' if markdown else ''
|
|
71
|
+
lines: list[str] = []
|
|
72
|
+
any_ok = False
|
|
73
|
+
for process in processes:
|
|
74
|
+
ok, detail = await _execute_process_action(process, action)
|
|
75
|
+
if ok:
|
|
76
|
+
any_ok = True
|
|
77
|
+
if ok or action == 'start':
|
|
78
|
+
_ok, line = _format_result(ok, f'{tick}[{process.name}]{tick}: {detail}', markdown=markdown)
|
|
79
|
+
lines.append(line if markdown else f' {line}')
|
|
80
|
+
|
|
81
|
+
_logger.info("Control action '%s-all' requested by %s -> %s", action, source, 'ok' if any_ok else 'failed')
|
|
82
|
+
if not lines:
|
|
83
|
+
return _format_result(False, _('No eligible processes for {}.').format(action), markdown=markdown)
|
|
84
|
+
return any_ok, '\n'.join(lines)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
async def reload_addons_command(
|
|
88
|
+
client: DisManagerClient,
|
|
89
|
+
*,
|
|
90
|
+
markdown: bool = False,
|
|
91
|
+
source: str = 'unknown',
|
|
92
|
+
) -> str:
|
|
93
|
+
"""Reload all DisManager addons and return the formatted status message."""
|
|
94
|
+
count = await client.reload_addons()
|
|
95
|
+
_logger.info("Control action 'adreload' requested by %s -> reloaded %d addon(s)", source, count)
|
|
96
|
+
_ok, message = _format_result(True, _('Reloaded {} addon(s).').format(count), markdown=markdown)
|
|
97
|
+
return message
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# =========================================
|
|
101
|
+
# Internal Helpers
|
|
102
|
+
# =========================================
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _format_result(ok: bool, message: str, *, markdown: bool) -> tuple[bool, str]:
|
|
106
|
+
if not markdown:
|
|
107
|
+
return ok, message
|
|
108
|
+
marker = '✔' if ok else '✖'
|
|
109
|
+
return ok, f'{marker} {message}'
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
async def _execute_process_action(process: ManagedProcess, action: ProcessAction) -> tuple[bool, str]:
|
|
113
|
+
if action == 'start':
|
|
114
|
+
if process.is_running():
|
|
115
|
+
return False, _('The process is already running.')
|
|
116
|
+
try:
|
|
117
|
+
process.start()
|
|
118
|
+
except ProcessConfigError as exc:
|
|
119
|
+
return False, str(exc)
|
|
120
|
+
return True, _('Initializing process.')
|
|
121
|
+
|
|
122
|
+
if not process.is_running():
|
|
123
|
+
return False, _('The process is not running.')
|
|
124
|
+
|
|
125
|
+
if action == 'stop':
|
|
126
|
+
process.stop()
|
|
127
|
+
return True, _('Stopping process.')
|
|
128
|
+
if action == 'kill':
|
|
129
|
+
process.kill()
|
|
130
|
+
return True, _('Killing process.')
|
|
131
|
+
if action == 'restart':
|
|
132
|
+
asyncio.create_task(process.restart())
|
|
133
|
+
return True, _('Restarting process.')
|
|
134
|
+
if action == 'plreload':
|
|
135
|
+
count = await process.reload_plugins()
|
|
136
|
+
return True, _('Reloaded {} plugin(s).').format(count)
|
|
137
|
+
raise ValueError(f'Unsupported process action: {action}')
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .loader import (
|
|
4
|
+
discover_extension_candidates,
|
|
5
|
+
dispatch_hook,
|
|
6
|
+
ensure_on_sys_path,
|
|
7
|
+
load_extension_module,
|
|
8
|
+
purge_modules_under,
|
|
9
|
+
unload_extensions,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
'discover_extension_candidates',
|
|
14
|
+
'dispatch_hook',
|
|
15
|
+
'ensure_on_sys_path',
|
|
16
|
+
'load_extension_module',
|
|
17
|
+
'purge_modules_under',
|
|
18
|
+
'unload_extensions',
|
|
19
|
+
]
|