serverwatcher 1__py3-none-any.whl → 1.dev5__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.
Files changed (47) hide show
  1. old/__init__.py +17 -0
  2. old/__main__.py +10 -0
  3. old/actionperformer.py +147 -0
  4. old/configclasses/__init__.py +13 -0
  5. old/configclasses/config.py +52 -0
  6. old/configclasses/discord.py +23 -0
  7. old/configclasses/environment.py +38 -0
  8. old/configclasses/evaluation.py +110 -0
  9. old/configclasses/messages.py +89 -0
  10. old/configclasses/watcher.py +42 -0
  11. old/configmanager.py +146 -0
  12. old/evaluator.py +60 -0
  13. old/exceptions.py +4 -0
  14. old/metricfetcher.py +92 -0
  15. old/router.py +102 -0
  16. old/targetserver.py +154 -0
  17. old/watcher.py +152 -0
  18. serverwatcher/__init__.py +2 -31
  19. serverwatcher/__main__.py +5 -0
  20. serverwatcher/actionperformer.py +105 -0
  21. serverwatcher/app.py +122 -0
  22. serverwatcher/configclasses/__init__.py +13 -0
  23. serverwatcher/configclasses/config.py +22 -0
  24. serverwatcher/configclasses/evaluation.py +54 -0
  25. serverwatcher/configclasses/logging.py +15 -0
  26. serverwatcher/configclasses/messages.py +45 -0
  27. serverwatcher/configclasses/watcher.py +18 -0
  28. serverwatcher/connection.py +37 -0
  29. serverwatcher/defaultconfigs/config.yaml +30 -0
  30. serverwatcher/defaultconfigs/evaluation.yaml +47 -0
  31. serverwatcher/defaultconfigs/messages.yaml +85 -0
  32. serverwatcher/defaultconfigs/watcher.yaml +12 -0
  33. serverwatcher/evaluator.py +61 -0
  34. serverwatcher/metricfetcher.py +91 -0
  35. serverwatcher/router.py +66 -0
  36. serverwatcher/settings.py +18 -0
  37. serverwatcher-1.dev5.dist-info/METADATA +76 -0
  38. serverwatcher-1.dev5.dist-info/RECORD +42 -0
  39. {serverwatcher-1.dist-info → serverwatcher-1.dev5.dist-info}/WHEEL +1 -1
  40. serverwatcher-1.dev5.dist-info/entry_points.txt +2 -0
  41. {serverwatcher-1.dist-info → serverwatcher-1.dev5.dist-info}/top_level.txt +1 -0
  42. serverwatcher/config.py +0 -33
  43. serverwatcher/messages.py +0 -42
  44. serverwatcher/watcher.py +0 -162
  45. serverwatcher-1.dist-info/METADATA +0 -41
  46. serverwatcher-1.dist-info/RECORD +0 -9
  47. {serverwatcher-1.dist-info → serverwatcher-1.dev5.dist-info}/licenses/LICENSE +0 -0
old/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ from importlib.metadata import version as _pkg_version, PackageNotFoundError
2
+
3
+ # Package version
4
+ try:
5
+ __version__ = _pkg_version('serverwatcher')
6
+ except PackageNotFoundError:
7
+ __version__ = '0.0.0'
8
+
9
+ from serverwatcher.watcher import ServerWatcher
10
+ from serverwatcher.configclasses.config import GlobalConfig
11
+ from serverwatcher.configclasses.watcher import WatcherConfig
12
+
13
+ __all__: list[str] = [
14
+ 'ServerWatcher',
15
+ 'GlobalConfig',
16
+ 'WatcherConfig',
17
+ ]
old/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ from .watcher import ServerWatcher
2
+
3
+
4
+ def main() -> None:
5
+ watcher = ServerWatcher()
6
+ watcher.run()
7
+
8
+
9
+ if __name__ == "__main__":
10
+ main()
old/actionperformer.py ADDED
@@ -0,0 +1,147 @@
1
+ import time
2
+ from zoneinfo import ZoneInfo
3
+ from hungercore import utils
4
+
5
+
6
+ class ActionPerformer:
7
+ '''
8
+ Executes actions chosen by ServerWatcher:
9
+ - restart_now
10
+ - schedule_restart
11
+ - none
12
+ '''
13
+
14
+ def __init__(self, server, router, webhook, config):
15
+ self.server = server
16
+ self.router = router
17
+ self.webhook = webhook
18
+ self.cfg = config
19
+ self.tz = ZoneInfo(getattr(self.cfg, 'timezone', 'UTC'))
20
+
21
+ # public entry point
22
+ def perform(self, action: str, **ctx):
23
+ if action == 'restart_now':
24
+ return self._restart_now()
25
+
26
+ if action == 'schedule_restart':
27
+ minutes = ctx.get('minutes')
28
+ return self._schedule_restart(minutes)
29
+
30
+ if action == 'none':
31
+ return self._no_action()
32
+
33
+ raise ValueError(f'Unknown action: {action}')
34
+
35
+ def notifyWebhook(self, event: str, **ctx):
36
+ if self.webhook is not None:
37
+ self.webhook.send(event=event, **ctx)
38
+
39
+ # immediate restart
40
+ def _restart_now(self):
41
+ self.router.info('Performing immediate restart...')
42
+ self.notifyWebhook(event='restart_now')
43
+
44
+ # send restart command
45
+ self.server.restartServer()
46
+ self.router.info('Restart action sent. Waiting...')
47
+ self.notifyWebhook(event='restart_action_sent')
48
+
49
+ # wait before checking status
50
+ time.sleep(self.cfg.restart_wait_seconds)
51
+
52
+ self.router.warn('Checking server status...')
53
+
54
+ alive = utils.waitForOnline(
55
+ self.server,
56
+ timeout=self.cfg.restart_timeout,
57
+ interval=self.cfg.restart_online_interval,
58
+ )
59
+
60
+ if alive:
61
+ self.router.info('Server is back online!')
62
+ self.router.destination('ServerWatcher successfully restarted the server.')
63
+ self.notifyWebhook(event='server_back_online')
64
+ else:
65
+ self.router.error('Server failed to restart!')
66
+ self.notifyWebhook(event='server_failed_restart')
67
+
68
+ return alive
69
+
70
+ # scheduled restart (with snapping)
71
+ def _schedule_restart(self, minutes):
72
+ self.router.info('Scheduling restart...')
73
+
74
+ info = utils.snapSchedule(
75
+ minimumMinutes=minutes,
76
+ snapMinutes=tuple(sorted(self.cfg.snap_minutes))
77
+ )
78
+ scheduled = info['scheduled']
79
+
80
+ local_time = scheduled.astimezone(self.tz)
81
+ time_str = local_time.strftime('%I:%M %p')
82
+
83
+ # broadcast restart time
84
+ self.router.broadcast(f'[Server Watcher] The server will restart at {time_str} CDT.')
85
+ self.notifyWebhook(event='restart_scheduled', time=time_str)
86
+
87
+ # build minute + second callbacks
88
+ minute_callbacks = self._build_minute_callbacks()
89
+ second_callbacks = self._build_second_callbacks()
90
+
91
+ # run countdown
92
+ utils.runCountdownEvents(
93
+ target_time=scheduled,
94
+ minute_callbacks=minute_callbacks,
95
+ second_callbacks=second_callbacks
96
+ )
97
+
98
+ # After countdown, perform restart
99
+ return self._restart_now()
100
+
101
+ # no action
102
+ def _no_action(self):
103
+ self.router.info('No restart required.')
104
+ self.notifyWebhook(event='no_action')
105
+ return True
106
+
107
+ # helpers for countdown events
108
+ def _build_minute_callbacks(self):
109
+ '''
110
+ Creates callbacks for minute announcements.
111
+ Example: 'Restart in 30 minutes', 'Restart in 1 minute'
112
+ '''
113
+ def plural(n):
114
+ return '' if n == 1 else 's'
115
+
116
+ def minute_msg(n):
117
+ return f'[Server Watcher] Restart in {n} minute{plural(n)}!'
118
+
119
+ callbacks = {
120
+ n: (lambda n=n: (
121
+ self.router.broadcast(minute_msg(n + 1)),
122
+ self.router.origin(minute_msg(n + 1))
123
+ ))
124
+ for n in self.cfg.snap_minutes
125
+ }
126
+
127
+ return callbacks
128
+
129
+ def _build_second_callbacks(self):
130
+ '''
131
+ Creates callbacks for final 10-second countdown.
132
+ '''
133
+ def plural(n):
134
+ return '' if n == 1 else 's'
135
+
136
+ def second_msg(n):
137
+ return f'[Server Watcher] Restarting in {n} second{plural(n)}!'
138
+
139
+ callbacks = {
140
+ n: (lambda n=n: (
141
+ self.router.broadcast(second_msg(n)),
142
+ self.router.origin(second_msg(n))
143
+ ))
144
+ for n in range(1, 11)
145
+ }
146
+
147
+ return callbacks
@@ -0,0 +1,13 @@
1
+ from .config import GlobalConfig
2
+ from .discord import DiscordConfig
3
+ from .environment import EnvironmentConfig
4
+ from .evaluation import EvaluatorConfig
5
+ from .watcher import WatcherConfig
6
+
7
+ __all__: list[str] = [
8
+ 'GlobalConfig',
9
+ 'DiscordConfig',
10
+ 'EnvironmentConfig',
11
+ 'EvaluatorConfig',
12
+ 'WatcherConfig',
13
+ ]
@@ -0,0 +1,52 @@
1
+ from mapres import datamap
2
+
3
+ @datamap.braces.config(recursive=True)
4
+ class GlobalConfig:
5
+ __user_config_path__ = 'config/config.yaml'
6
+ __default_config_path__ = 'defaultconfigs/config.yaml'
7
+
8
+ debug: bool = 'debug'
9
+ timezone: str = 'timezone'
10
+
11
+ server_name: str = 'server.name'
12
+ server_domain: str = 'server.domain'
13
+ server_port: int = 'server.port'
14
+
15
+ enable_logging: bool = 'logger.enabled'
16
+ logger_name: str = 'logger.name'
17
+ log_path: str = 'logger.log_path'
18
+
19
+ info_prefix: str = 'logger.prefixes.info'
20
+ warn_prefix: str = 'logger.prefixes.warn'
21
+ error_prefix: str = 'logger.prefixes.error'
22
+ fatal_prefix: str = 'logger.prefixes.fatal'
23
+ debug_prefix: str = 'logger.prefixes.debug'
24
+
25
+ clear_terminal: bool = 'terminal.enable_clearing'
26
+ handle_keyboard_interrupt: bool = 'terminal.handle_keyboard_interrupt'
27
+
28
+
29
+ class fallbacks:
30
+ debug = False
31
+ timezone = 'America/Chicago'
32
+
33
+ server_name = 'My SMP'
34
+ server_domain = 'mc.example.com'
35
+ server_port = 25565
36
+
37
+ enable_logging = True
38
+ logger_name = 'Server Watcher'
39
+ log_path = '/home/container/logs/'
40
+
41
+ info_prefix = '<white>[%hh%:%mm%:%ss%] [INFO]: '
42
+ warn_prefix = '<yellow>[%hh%:%mm%:%ss%] [WARN]: '
43
+ error_prefix = '<red>[%hh%:%mm%:%ss%] [ERROR]: '
44
+ fatal_prefix = '<dark_red>[%hh%:%mm%:%ss%] [FATAL]: '
45
+ debug_prefix = '<aqua>[%hh%:%mm%:%ss%] [DEBUG]: '
46
+
47
+ clear_terminal = True
48
+ handle_keyboard_interrupt = True
49
+
50
+
51
+ class rules:
52
+ pass # everything defaults to optional
@@ -0,0 +1,23 @@
1
+ from mapres import datamap
2
+
3
+ @datamap.braces.config(recursive=True)
4
+ class DiscordConfig:
5
+ __user_config_path__ = 'config/discord.yaml'
6
+ __default_config_path__ = 'defaultconfigs/discord.yaml'
7
+
8
+ discord_enabled: bool = 'discord.enabled'
9
+ discord_token: str = 'discord.token'
10
+ discord_url: str = 'discord.url'
11
+
12
+
13
+ class fallbacks:
14
+ discord_enabled = True
15
+ discord_token = 'CHANGE_ME'
16
+ discord_url = 'https://bot.example.com/webhook'
17
+
18
+
19
+ class rules:
20
+ discord_enabled = 'recommended'
21
+ discord_token = 'recommended'
22
+ discord_url = 'recommended'
23
+ # everything else defaults to optional
@@ -0,0 +1,38 @@
1
+ from mapres import datamap
2
+
3
+ @datamap.braces.config(recursive=True)
4
+ class EnvironmentConfig:
5
+ __user_config_path__ = 'config/environment.yaml'
6
+ __default_config_path__ = 'defaultconfigs/environment.yaml'
7
+
8
+ bridge_url: str = 'hungerbridge.url'
9
+ bridge_token_id: str = 'hungerbridge.token_id'
10
+ bridge_token_secret: str = 'hungerbridge.token_secret'
11
+
12
+ ptero_enabled: bool = 'pterodactyl.enabled'
13
+ ptero_url: str = 'pterodactyl.url'
14
+ ptero_api_key: str = 'pterodactyl.api_key'
15
+ ptero_server_id: str = 'pterodactyl.server_id'
16
+
17
+
18
+ class fallbacks:
19
+ bridge_token_id = 'CHANGE_ME'
20
+ bridge_token_secret = 'CHANGE_ME'
21
+ bridge_url = 'https://api.example.com'
22
+
23
+ ptero_enabled = False
24
+ ptero_url = 'https://example.com'
25
+ ptero_api_key = 'CHANGE_ME'
26
+ ptero_server_id = 'CHANGE_ME'
27
+
28
+
29
+ class rules:
30
+ bridge_token_id = 'required'
31
+ bridge_token_secret = 'required'
32
+ bridge_url = 'required'
33
+
34
+ ptero_enabled = 'recommended'
35
+ ptero_url = 'recommended'
36
+ ptero_api_key = 'recommended'
37
+ ptero_server_id = 'recommended'
38
+ # everything else defaults to optional
@@ -0,0 +1,110 @@
1
+ from mapres import datamap
2
+
3
+ @datamap.braces.config(recursive=True)
4
+ class EvaluatorConfig:
5
+ __user_config_path__ = 'config/evaluation.yaml'
6
+ __default_config_path__ = 'defaultconfigs/evaluation.yaml'
7
+
8
+ # Sampling
9
+ sample_duration: float | int = 'sampling.duration'
10
+ sample_interval: float | int = 'sampling.interval'
11
+ sample_outlier_drop: int = 'sampling.drop_outliers'
12
+
13
+ # Thresholds
14
+ threshold_ram: float = 'thresholds.ram'
15
+ threshold_cpu: float = 'thresholds.cpu'
16
+ threshold_uptime: float = 'thresholds.uptime'
17
+ threshold_min_uptime: float = 'thresholds.min_uptime'
18
+
19
+ threshold_players: int = 'thresholds.players'
20
+ threshold_max_players: int = 'thresholds.max_players'
21
+
22
+ threshold_tps: float = 'thresholds.tps'
23
+ threshold_tps_1m: float = 'thresholds.tps_1m'
24
+ threshold_tps_5m: float = 'thresholds.tps_5m'
25
+ threshold_tps_15m: float = 'thresholds.tps_15m'
26
+
27
+ threshold_mspt: float = 'thresholds.mspt'
28
+
29
+ threshold_loaded_chunks: int = 'thresholds.loaded_chunks'
30
+ threshold_loaded_entities: int = 'thresholds.loaded_entities'
31
+
32
+ threshold_gc_pause_ms: float = 'thresholds.gc_pause_ms'
33
+ threshold_thread_peak: int = 'thresholds.thread_peak'
34
+
35
+ # Weights
36
+ weight_ram: int = 'weights.ram'
37
+ weight_cpu: int = 'weights.cpu'
38
+ weight_uptime: int = 'weights.uptime'
39
+
40
+ weight_players: int = 'weights.players'
41
+ weight_max_players: int = 'weights.max_players'
42
+
43
+ weight_tps: int = 'weights.tps'
44
+ weight_tps_1m: int = 'weights.tps_1m'
45
+ weight_tps_5m: int = 'weights.tps_5m'
46
+ weight_tps_15m: int = 'weights.tps_15m'
47
+
48
+ weight_mspt: int = 'weights.mspt'
49
+
50
+ weight_loaded_chunks: int = 'weights.loaded_chunks'
51
+ weight_loaded_entities: int = 'weights.loaded_entities'
52
+
53
+ weight_gc_pause_ms: int = 'weights.gc_pause_ms'
54
+ weight_thread_peak: int = 'weights.thread_peak'
55
+
56
+
57
+ class fallbacks:
58
+ sample_duration = 5
59
+ sample_interval = 1
60
+ sample_outlier_drop = 1
61
+
62
+ threshold_ram = 6
63
+ threshold_cpu = 150
64
+ threshold_uptime = 12
65
+ threshold_min_uptime = 30
66
+
67
+ threshold_players = 0
68
+ threshold_max_players = 0
69
+
70
+ threshold_tps = 19.5
71
+ threshold_tps_1m = 19.5
72
+ threshold_tps_5m = 19.5
73
+ threshold_tps_15m = 19.5
74
+
75
+ threshold_mspt = 50
76
+
77
+ threshold_loaded_chunks = 0
78
+ threshold_loaded_entities = 0
79
+
80
+ threshold_gc_pause_ms = 200
81
+ threshold_thread_peak = 500
82
+
83
+ weight_ram = 2
84
+ weight_cpu = 2
85
+ weight_uptime = 1
86
+
87
+ weight_players = 1
88
+ weight_max_players = 0
89
+
90
+ weight_tps = 3
91
+ weight_tps_1m = 1
92
+ weight_tps_5m = 1
93
+ weight_tps_15m = 1
94
+
95
+ weight_mspt = 3
96
+
97
+ weight_loaded_chunks = 0
98
+ weight_loaded_entities = 0
99
+
100
+ weight_gc_pause_ms = 2
101
+ weight_thread_peak = 2
102
+
103
+
104
+ class rules:
105
+ threshold_ram = 'required'
106
+ threshold_cpu = 'required'
107
+ threshold_tps = 'required'
108
+ threshold_mspt = 'required'
109
+ threshold_uptime = 'required'
110
+ threshold_min_uptime = 'required'
@@ -0,0 +1,89 @@
1
+ from mapres import datamap
2
+
3
+ @datamap.braces.config(recursive=True)
4
+ class MessagesConfig:
5
+ __user_config_path__ = 'config/messages.yaml'
6
+ __default_config_path__ = 'defaultconfigs/messages.yaml'
7
+
8
+ prefix: str = 'prefix'
9
+ bullet: str = 'bullet'
10
+
11
+ broadcast_restart_at: str = 'broadcast_restart_at'
12
+
13
+ minute_template: str = 'broadcast_templates.minutes'
14
+ second_template: str = 'broadcast_templates.seconds'
15
+
16
+ startup: str = 'logging.startup'
17
+ status_check: str = 'logging.status_check'
18
+ validation_fail: str = 'logging.validation_fail'
19
+ validation_ok: str = 'logging.validation_ok'
20
+ sampling_start: str = 'logging.sampling_start'
21
+ shutdown: str = 'logging.shutdown'
22
+ immediate_restart: str = 'logging.immediate_restart'
23
+ no_restart: str = 'logging.no_restart'
24
+ scheduled: str = 'logging.scheduled'
25
+ gap_low: str = 'logging.gap_low'
26
+ gap_high: str = 'logging.gap_high'
27
+
28
+ pro_restart_splash: str = 'reasons.pro_splash'
29
+ anti_restart_splash: str = 'reasons.anti_splash'
30
+
31
+ reason_restart_soon: str = 'reasons.restart_soon'
32
+ reason_ram: str = 'reasons.ram'
33
+ reason_cpu: str = 'reasons.cpu'
34
+ reason_uptime: str = 'reasons.uptime'
35
+ reason_tps: str = 'reasons.tps'
36
+ reason_low_uptime: str = 'reasons.low_uptime'
37
+ reason_players: str = 'reasons.players'
38
+
39
+ pro_restart_number: str = 'reasons.pro_restart_number'
40
+ anti_restart_number: str = 'reasons.anti_restart_number'
41
+
42
+ restart_action_sent: str = 'restarts.restart_action_sent'
43
+ server_back_online: str = 'restarts.back_online'
44
+ server_back_online_log: str = 'restarts.back_online_log'
45
+ server_failed_restart: str = 'restarts.failed_restart'
46
+
47
+
48
+ class fallbacks:
49
+ prefix = '<aqua>[Server Watcher]'
50
+ bullet = '-'
51
+
52
+ broadcast_restart_at = '{prefix} The server will restart at {time} CDT.'
53
+
54
+ minute_template = '{prefix} Restart in {n} minute{s}!'
55
+ second_template = '{prefix} <red>Restarting in {n} second{s}!'
56
+
57
+ startup = 'ServerWatcher is running!'
58
+ status_check = 'Checking server status...'
59
+ validation_fail = 'Validation FAILED.'
60
+ validation_ok = 'All validation checks succeeded.'
61
+ sampling_start = 'Starting sampling process. This should take about {duration} seconds...'
62
+ shutdown = 'Shutting down ServerWatcher.'
63
+ immediate_restart = 'Restarting immediately.'
64
+ no_restart = 'The server does not need to restart.'
65
+ scheduled = 'Restart needed, but anti-restart factors outweigh it.'
66
+ gap_low = 'Gap {gap}. Scheduling restart in 2 hours.'
67
+ gap_high = 'Gap {gap}. Scheduling restart in 1 hour.'
68
+
69
+ pro_restart_splash = 'PRO-RESTART REASONS:'
70
+ anti_restart_splash = 'ANTI-RESTART REASONS:'
71
+
72
+ reason_restart_soon = 'The server is set to restart soon'
73
+ reason_ram = 'RAM usage ({ram}) is higher than {threshold} GB'
74
+ reason_cpu = 'CPU usage ({cpu}) is higher than {threshold}%'
75
+ reason_uptime = 'Uptime {uptime} exceeds {threshold}h'
76
+ reason_tps = 'TPS {tps} is lower than {threshold}'
77
+ reason_low_uptime = 'Uptime {uptime} is shorter than 30m'
78
+ reason_players = 'There {verb} {count} {plural} online'
79
+
80
+ pro_restart_number = 'Pro-restart: '
81
+ anti_restart_number = 'Anti-restart:'
82
+
83
+ restart_action_sent = 'Restart action sent. Waiting...'
84
+ server_back_online = 'Server is back online!'
85
+ server_back_online_log = 'ServerWatcher successfully restarted the server.'
86
+ server_failed_restart = 'Server failed to restart!'
87
+
88
+ class rules:
89
+ pass
@@ -0,0 +1,42 @@
1
+ from mapres import datamap
2
+
3
+ @datamap.braces.config(recursive=True)
4
+ class WatcherConfig:
5
+ __user_config_path__ = 'config/watcher.yaml'
6
+ __default_config_path__ = 'defaultconfigs/watcher.yaml'
7
+
8
+ # Restart behavior
9
+ restart_wait_seconds: int = 'restart.wait_seconds'
10
+ restart_timeout: int = 'restart.timeout'
11
+ restart_online_interval: int = 'restart.online_interval'
12
+
13
+ # Scheduling behavior
14
+ threshold_low_gap: int = 'schedule.threshold_low_gap'
15
+ low_gap_minutes: int = 'schedule.low_gap_minutes'
16
+ high_gap_minutes: int = 'schedule.high_gap_minutes'
17
+ snap_minutes: list = 'schedule.snap_minutes'
18
+ watch_interval: int = 'watch_interval'
19
+
20
+
21
+ class fallbacks:
22
+ restart_wait_seconds = 30
23
+ restart_timeout = 120
24
+ restart_online_interval = 2
25
+
26
+ threshold_low_gap = 2
27
+ low_gap_minutes = 120
28
+ high_gap_minutes = 60
29
+ snap_minutes = [0, 30]
30
+ watch_interval = 300
31
+
32
+
33
+ class rules:
34
+ restart_wait_seconds = 'required'
35
+ restart_timeout = 'required'
36
+ restart_online_interval = 'required'
37
+
38
+ threshold_low_gap = 'recommended'
39
+ low_gap_minutes = 'recommended'
40
+ high_gap_minutes = 'recommended'
41
+ snap_minutes = 'recommended'
42
+ watch_interval = 'recommended'
old/configmanager.py ADDED
@@ -0,0 +1,146 @@
1
+ from typing import Any
2
+ import os
3
+ import shutil
4
+ from dataclasses import fields
5
+
6
+ from hungercore import utils, loadConfig, Validator
7
+
8
+ from serverwatcher.configclasses.config import GlobalConfig
9
+ from serverwatcher.configclasses.discord import DiscordConfig
10
+ from serverwatcher.configclasses.environment import EnvironmentConfig
11
+ from serverwatcher.configclasses.evaluation import EvaluatorConfig
12
+ from serverwatcher.configclasses.watcher import WatcherConfig
13
+
14
+
15
+ class ConfigManager:
16
+ def __init__(self):
17
+ utils.clearTerminal()
18
+ self.validator = Validator()
19
+
20
+ self.config = loadConfig(GlobalConfig)
21
+ self.discordcfg = loadConfig(DiscordConfig)
22
+ self.env = loadConfig(EnvironmentConfig)
23
+ self.evaluatorcfg = loadConfig(EvaluatorConfig)
24
+ self.watchercfg = loadConfig(WatcherConfig)
25
+
26
+ self.ALL_CONFIG_CLASSES: list[Any] = [
27
+ GlobalConfig,
28
+ DiscordConfig,
29
+ EnvironmentConfig,
30
+ EvaluatorConfig,
31
+ WatcherConfig
32
+ ]
33
+
34
+ self.ALL_LOADED_CONFIGS: list[Any] = [
35
+ self.config,
36
+ self.discordcfg,
37
+ self.env,
38
+ self.evaluatorcfg,
39
+ self.watchercfg,
40
+ ]
41
+
42
+ self.CONFIG_DICT: dict[Any] = {
43
+ GlobalConfig: self.config,
44
+ DiscordConfig: self.discordcfg,
45
+ EnvironmentConfig: self.env,
46
+ EvaluatorConfig: self.evaluatorcfg,
47
+ WatcherConfig: self.watchercfg
48
+ }
49
+
50
+
51
+
52
+ # existence checking
53
+ def checkExistence(self, *config_classes):
54
+ for cls in config_classes:
55
+ user_path: Any | None = getattr(cls, '__user_config_path__', None)
56
+ if not user_path or not os.path.exists(user_path):
57
+ return False
58
+ return True
59
+
60
+ def checkAllExistence(self):
61
+ return self.checkExistence(*self.ALL_CONFIG_CLASSES)
62
+
63
+ # config generation
64
+ def generateConfigs(self, overwrite=False, *config_classes):
65
+ for cls in config_classes:
66
+ user_path: Any | None = getattr(cls, '__user_config_path__', None)
67
+ default_path: Any | None = getattr(cls, '__default_config_path__', None)
68
+
69
+ if not user_path or not default_path:
70
+ continue
71
+
72
+ if os.path.exists(user_path) and not overwrite:
73
+ continue
74
+
75
+ os.makedirs(os.path.dirname(user_path), exist_ok=True)
76
+ shutil.copy(default_path, user_path)
77
+
78
+ def generateAllConfigs(self, overwrite=False):
79
+ self.generateConfigs(overwrite, *self.ALL_CONFIG_CLASSES)
80
+
81
+ # validation helpers
82
+ def _validate_fields(self, config_obj, config_cls):
83
+ for f in fields(config_cls):
84
+ if not f.name.startswith('__'):
85
+ self.validator.check_field(config_obj, f.name)
86
+
87
+ # validation rules
88
+ def validate_config(self):
89
+ c = self.config
90
+ self._validate_fields(c, GlobalConfig)
91
+
92
+ def validate_discordcfg(self):
93
+ c = self.discordcfg
94
+ self._validate_fields(c, DiscordConfig)
95
+
96
+ if c.discord_enabled:
97
+ if c.discord_token == 'CHANGE_ME':
98
+ self.validator.errors.append('discord_token: must be configured (got "CHANGE_ME")')
99
+ if c.discord_url == 'https://bot.example.com/webhook':
100
+ self.validator.errors.append('discord_url: must be configured (got placeholder URL)')
101
+
102
+ def validate_env(self):
103
+ c = self.env
104
+ self._validate_fields(c, EnvironmentConfig)
105
+
106
+ if c.bridge_url == 'https://api.example.com':
107
+ self.validator.errors.append('bridge_url: must be configured (got placeholder URL)')
108
+ if c.bridge_token_id == 'CHANGE_ME':
109
+ self.validator.errors.append('bridge_token_id: must be configured (got "CHANGE_ME")')
110
+ if c.bridge_token_secret == 'CHANGE_ME':
111
+ self.validator.errors.append('bridge_token_secret: must be configured (got "CHANGE_ME")')
112
+
113
+ if c.ptero_enabled:
114
+ if c.ptero_url == 'https://example.com':
115
+ self.validator.errors.append('ptero_url: must be configured (got placeholder URL)')
116
+ if c.ptero_api_key == 'CHANGE_ME':
117
+ self.validator.errors.append('ptero_api_key: must be configured (got "CHANGE_ME")')
118
+ if c.ptero_server_id == 'CHANGE_ME':
119
+ self.validator.errors.append('ptero_server_id: must be configured (got "CHANGE_ME")')
120
+
121
+ def validate_watchercfg(self):
122
+ c = self.watchercfg
123
+ self._validate_fields(c, WatcherConfig)
124
+
125
+ # full validation
126
+ def validateAll(self):
127
+ # type validation
128
+ for config_cls, config_obj in self.CONFIG_DICT.items():
129
+ self.validator.validate_key_types(config_obj, config_cls)
130
+
131
+ # field validation
132
+ self.validate_config()
133
+ self.validate_discordcfg()
134
+ self.validate_env()
135
+ self.validate_watchercfg()
136
+
137
+ # return final validation result
138
+ return self.validator.run(
139
+ self.config,
140
+ self.discordcfg,
141
+ self.env,
142
+ self.evaluatorcfg,
143
+ self.watchercfg
144
+ )
145
+
146
+ config_manager = ConfigManager()