serverwatcher 6.dev61__py3-none-any.whl → 7.dev2__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.
serverwatcher/__init__.py CHANGED
@@ -6,14 +6,12 @@ try:
6
6
  except PackageNotFoundError:
7
7
  __version__ = '0.0.0'
8
8
 
9
- from .watcher import ServerWatcher
10
- from .configclasses.config import GlobalConfig
11
- from .configclasses.messages import MessagesConfig
12
- from .configclasses.watcher import WatcherConfig
9
+ from serverwatcher.watcher import ServerWatcher
10
+ from serverwatcher.configclasses.config import GlobalConfig
11
+ from serverwatcher.configclasses.watcher import WatcherConfig
13
12
 
14
- __all__ = [
13
+ __all__: list[str] = [
15
14
  'ServerWatcher',
16
15
  'GlobalConfig',
17
- 'MessagesConfig',
18
16
  'WatcherConfig',
19
17
  ]
serverwatcher/__main__.py CHANGED
@@ -1,101 +1,10 @@
1
- import time
2
- import asyncio
3
- import threading
4
-
5
- from mapres import rprint, setGlobalMaps, ascii_colors
6
-
7
- from hungerlib.validator import (
8
- ValidationError,
9
- FatalError,
10
- TypeMismatchError,
11
- FallbackError,
12
- RecommendedError,
13
- )
14
-
15
1
  from .watcher import ServerWatcher
16
- from .validator import validate_all
17
- from .watchercli import WatcherCLI
18
-
19
-
20
- setGlobalMaps(ascii_colors)
21
-
22
-
23
- def pretty_report(report: str) -> str:
24
- lines = report.splitlines()
25
- out = []
26
- for line in lines:
27
- stripped = line.strip()
28
- if stripped.startswith('errors:'):
29
- out.append('<red>Errors:')
30
- continue
31
- if stripped.startswith('recommended:'):
32
- out.append('<yellow>Recommended:')
33
- continue
34
- if stripped.startswith('fallbacks:'):
35
- out.append('<yellow>Fallbacks:')
36
- continue
37
- if stripped.startswith('warnings:'):
38
- out.append('<aqua>Warnings:')
39
- continue
40
- if stripped.startswith('- '):
41
- out.append(f' {stripped}')
42
- continue
43
- out.append(line)
44
- return '\n'.join(out)
45
-
46
-
47
- def main():
48
- try:
49
- validate_all()
50
-
51
- except FatalError as e:
52
- rprint('<bold><red>FATAL CONFIG ERROR:')
53
- rprint(pretty_report(e.report))
54
- rprint('\nIt looks like ServerWatcher is not configured yet.')
55
- rprint('<aqua>Please edit your config files in config/ and try again.')
56
- return
57
-
58
- except TypeMismatchError as e:
59
- rprint('<bold><red>TYPE MISMATCH ERROR:')
60
- rprint(pretty_report(e.report))
61
- rprint('\nYour configuration contains values of the wrong type.')
62
- rprint('<aqua>Please fix your config files and try again.')
63
- return
64
-
65
- except FallbackError as e:
66
- rprint('<bold><yellow>FALLBACKS IN USE:')
67
- rprint(pretty_report(e.report))
68
- rprint('\nIt looks like you have not configured ServerWatcher yet.')
69
- rprint('<aqua>Please edit your config files in config/ and try again.')
70
- return
71
-
72
- except RecommendedError as e:
73
- rprint('<bold><yellow>RECOMMENDED KEYS MISSING:')
74
- rprint(pretty_report(e.report))
75
- rprint('\nYour configuration is missing recommended keys.')
76
- rprint('<aqua>Continuing in 5 seconds...')
77
- time.sleep(5)
78
-
79
- except ValidationError as e:
80
- rprint('<bold><red>CONFIG ERROR:')
81
- rprint(pretty_report(e.report))
82
- rprint('\nYour configuration is invalid.')
83
- rprint('<aqua>Please edit your config files and try again.')
84
- return
85
2
 
86
- except Exception as e:
87
- rprint('<bold><red>UNEXPECTED ERROR:')
88
- rprint(str(e))
89
- rprint('\nSomething went wrong before ServerWatcher could start.')
90
- rprint('<aqua>Please check your configuration and environment.')
91
- return
92
3
 
93
- # Start watcher thread
4
+ def main() -> None:
94
5
  watcher = ServerWatcher()
95
- threading.Thread(target=watcher.run, daemon=True).start()
6
+ watcher.run()
96
7
 
97
- cli = WatcherCLI(watcher)
98
- asyncio.run(cli.run())
99
8
 
100
- if __name__ == '__main__':
9
+ if __name__ == "__main__":
101
10
  main()
@@ -0,0 +1,143 @@
1
+ import time
2
+ from zoneinfo import ZoneInfo
3
+ from hungerlib 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
+ # immediate restart
36
+ def _restart_now(self):
37
+ self.router.info('Performing immediate restart...')
38
+ self.webhook.send(event='restart_now')
39
+
40
+ # send restart command
41
+ self.server.restartServer()
42
+ self.router.info('Restart action sent. Waiting...')
43
+ self.webhook.send(event='restart_action_sent')
44
+
45
+ # wait before checking status
46
+ time.sleep(self.cfg.restart_wait_seconds)
47
+
48
+ self.router.warn('Checking server status...')
49
+
50
+ alive = utils.waitForOnline(
51
+ self.server,
52
+ timeout=self.cfg.restart_timeout,
53
+ interval=self.cfg.restart_online_interval,
54
+ )
55
+
56
+ if alive:
57
+ self.router.info('Server is back online!')
58
+ self.router.destination('ServerWatcher successfully restarted the server.')
59
+ self.webhook.send(event='server_back_online')
60
+ else:
61
+ self.router.error('Server failed to restart!')
62
+ self.webhook.send(event='server_failed_restart')
63
+
64
+ return alive
65
+
66
+ # scheduled restart (with snapping)
67
+ def _schedule_restart(self, minutes):
68
+ self.router.info('Scheduling restart...')
69
+
70
+ info = utils.snapSchedule(
71
+ minimumMinutes=minutes,
72
+ snapMinutes=tuple(sorted(self.cfg.snap_minutes))
73
+ )
74
+ scheduled = info['scheduled']
75
+
76
+ local_time = scheduled.astimezone(self.tz)
77
+ time_str = local_time.strftime('%I:%M %p')
78
+
79
+ # broadcast restart time
80
+ self.router.broadcast(f'[Server Watcher] The server will restart at {time_str} CDT.')
81
+ self.webhook.send(event='restart_scheduled', time=time_str)
82
+
83
+ # build minute + second callbacks
84
+ minute_callbacks = self._build_minute_callbacks()
85
+ second_callbacks = self._build_second_callbacks()
86
+
87
+ # run countdown
88
+ utils.runCountdownEvents(
89
+ target_time=scheduled,
90
+ minute_callbacks=minute_callbacks,
91
+ second_callbacks=second_callbacks
92
+ )
93
+
94
+ # After countdown, perform restart
95
+ return self._restart_now()
96
+
97
+ # no action
98
+ def _no_action(self):
99
+ self.router.info('No restart required.')
100
+ self.webhook.send(event='no_action')
101
+ return True
102
+
103
+ # helpers for countdown events
104
+ def _build_minute_callbacks(self):
105
+ '''
106
+ Creates callbacks for minute announcements.
107
+ Example: 'Restart in 30 minutes', 'Restart in 1 minute'
108
+ '''
109
+ def plural(n):
110
+ return '' if n == 1 else 's'
111
+
112
+ def minute_msg(n):
113
+ return f'[Server Watcher] Restart in {n} minute{plural(n)}!'
114
+
115
+ callbacks = {
116
+ n: (lambda n=n: (
117
+ self.router.broadcast(minute_msg(n + 1)),
118
+ self.router.origin(minute_msg(n + 1))
119
+ ))
120
+ for n in self.cfg.snap_minutes
121
+ }
122
+
123
+ return callbacks
124
+
125
+ def _build_second_callbacks(self):
126
+ '''
127
+ Creates callbacks for final 10-second countdown.
128
+ '''
129
+ def plural(n):
130
+ return '' if n == 1 else 's'
131
+
132
+ def second_msg(n):
133
+ return f'[Server Watcher] Restarting in {n} second{plural(n)}!'
134
+
135
+ callbacks = {
136
+ n: (lambda n=n: (
137
+ self.router.broadcast(second_msg(n)),
138
+ self.router.origin(second_msg(n))
139
+ ))
140
+ for n in range(1, 11)
141
+ }
142
+
143
+ return callbacks
@@ -1,9 +1,13 @@
1
1
  from .config import GlobalConfig
2
- from .messages import MessagesConfig
2
+ from .discord import DiscordConfig
3
+ from .environment import EnvironmentConfig
4
+ from .evaluation import EvaluatorConfig
3
5
  from .watcher import WatcherConfig
4
6
 
5
- __all__ = [
7
+ __all__: list[str] = [
6
8
  'GlobalConfig',
7
- 'MessagesConfig',
9
+ 'DiscordConfig',
10
+ 'EnvironmentConfig',
11
+ 'EvaluatorConfig',
8
12
  'WatcherConfig',
9
13
  ]
@@ -8,22 +8,10 @@ class GlobalConfig:
8
8
  debug: bool = 'debug'
9
9
  timezone: str = 'timezone'
10
10
 
11
- panel_name: str = 'panel.name'
12
- panel_url: str = 'panel.url'
13
- panel_api_key: str = 'panel.api_key'
14
-
15
11
  server_name: str = 'server.name'
16
- server_id: str = 'server.server_id'
17
12
  server_domain: str = 'server.domain'
18
13
  server_port: int = 'server.port'
19
14
 
20
- bridge_token: str = 'hungerbridge.token'
21
- bridge_url: str = 'hungerbridge.url'
22
-
23
- discord_enabled: bool = 'discord.enabled'
24
- discord_token: str = 'discord.token'
25
- discord_url: str = 'discord.url'
26
-
27
15
  enable_logging: bool = 'logger.enabled'
28
16
  logger_name: str = 'logger.name'
29
17
  log_path: str = 'logger.log_path'
@@ -31,6 +19,7 @@ class GlobalConfig:
31
19
  info_prefix: str = 'logger.prefixes.info'
32
20
  warn_prefix: str = 'logger.prefixes.warn'
33
21
  error_prefix: str = 'logger.prefixes.error'
22
+ fatal_prefix: str = 'logger.prefixes.fatal'
34
23
  debug_prefix: str = 'logger.prefixes.debug'
35
24
 
36
25
  clear_terminal: bool = 'terminal.enable_clearing'
@@ -41,22 +30,10 @@ class fallbacks:
41
30
  debug = False
42
31
  timezone = 'America/Chicago'
43
32
 
44
- panel_name = 'My Panel'
45
- panel_url = 'https://example.com'
46
- panel_api_key = 'CHANGE_ME'
47
-
48
33
  server_name = 'My SMP'
49
- server_id = 'CHANGE_ME'
50
34
  server_domain = 'mc.example.com'
51
35
  server_port = 25565
52
36
 
53
- bridge_token = 'CHANGE_ME'
54
- bridge_url = 'https://api.example.com'
55
-
56
- discord_enabled = True
57
- discord_token = 'CHANGE_ME'
58
- discord_url = 'https://bot.example.com/webhook'
59
-
60
37
  enable_logging = True
61
38
  logger_name = 'Server Watcher'
62
39
  log_path = '/home/container/logs/'
@@ -64,6 +41,7 @@ class fallbacks:
64
41
  info_prefix = '<white>[%hh%:%mm%:%ss%] [INFO]: '
65
42
  warn_prefix = '<yellow>[%hh%:%mm%:%ss%] [WARN]: '
66
43
  error_prefix = '<red>[%hh%:%mm%:%ss%] [ERROR]: '
44
+ fatal_prefix = '<dark_red>[%hh%:%mm%:%ss%] [FATAL]: '
67
45
  debug_prefix = '<aqua>[%hh%:%mm%:%ss%] [DEBUG]: '
68
46
 
69
47
  clear_terminal = True
@@ -71,18 +49,4 @@ class fallbacks:
71
49
 
72
50
 
73
51
  class rules:
74
- panel_url = 'required'
75
- panel_api_key = 'required'
76
- server_id = 'required'
77
- server_domain = 'required'
78
- bridge_token = 'required'
79
-
80
- timezone = 'recommended'
81
- panel_name = 'recommended'
82
- server_port = 'recommended'
83
- bridge_url = 'recommended'
84
-
85
- discord_url = 'recommended'
86
- discord_token = 'recommended'
87
-
88
- # everything else defaults to optional
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'
@@ -5,95 +5,38 @@ class WatcherConfig:
5
5
  __user_config_path__ = 'config/watcher.yaml'
6
6
  __default_config_path__ = 'defaultconfigs/watcher.yaml'
7
7
 
8
- watch_interval: int = 'watch_interval'
9
-
10
- sample_duration: float | int = 'sampling.duration'
11
- sample_interval: float | int = 'sampling.interval'
12
- sample_outlier_drop: int = 'sampling.drop_outliers'
13
-
14
- threshold_ram: int = 'thresholds.ram'
15
- threshold_cpu: int = 'thresholds.cpu'
16
- threshold_uptime: int = 'thresholds.uptime'
17
- threshold_tps: float = 'thresholds.tps'
18
- threshold_min_uptime: int = 'thresholds.min_uptime'
19
- threshold_low_gap: int = 'thresholds.low_gap'
20
-
21
- weight_restart_soon: int = 'weights.restart_soon'
22
- weight_ram: int = 'weights.ram'
23
- weight_cpu: int = 'weights.cpu'
24
- weight_uptime: int = 'weights.uptime'
25
- weight_tps: int = 'weights.tps'
26
-
27
- weight_low_uptime: int = 'weights.low_uptime'
28
- weight_per_player: int = 'weights.per_player'
29
-
30
- low_gap_minutes: int = 'gaps.low_gap_minutes'
31
- high_gap_minutes: int = 'gaps.high_gap_minutes'
32
-
33
- snap_minutes: list = 'snap_minutes'
34
-
8
+ # Restart behavior
35
9
  restart_wait_seconds: int = 'restart.wait_seconds'
36
- restart_timeout: int = 'restart.online_timeout'
10
+ restart_timeout: int = 'restart.timeout'
37
11
  restart_online_interval: int = 'restart.online_interval'
38
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'
39
19
 
40
- class fallbacks:
41
- watch_interval = 300
42
20
 
43
- sample_duration = 5
44
- sample_interval = 1
45
- sample_outlier_drop = 1
21
+ class fallbacks:
22
+ restart_wait_seconds = 30
23
+ restart_timeout = 120
24
+ restart_online_interval = 2
46
25
 
47
- threshold_ram = 6
48
- threshold_cpu = 150
49
- threshold_uptime = 12
50
- threshold_tps = 19.5
51
- threshold_min_uptime = 30
52
26
  threshold_low_gap = 2
53
-
54
- weight_restart_soon = 3
55
- weight_ram = 1
56
- weight_cpu = 1
57
- weight_uptime = 1
58
- weight_tps = 1
59
-
60
- weight_low_uptime = 5
61
- weight_per_player = 1
62
-
63
27
  low_gap_minutes = 120
64
28
  high_gap_minutes = 60
65
-
66
29
  snap_minutes = [0, 30]
67
-
68
- restart_wait_seconds = 30
69
- restart_timeout = 120
70
- restart_online_interval = 2
30
+ watch_interval = 300
71
31
 
72
32
 
73
33
  class rules:
74
- threshold_ram = 'required'
75
- threshold_cpu = 'required'
76
- threshold_uptime = 'required'
77
- threshold_tps = 'required'
78
-
79
34
  restart_wait_seconds = 'required'
80
35
  restart_timeout = 'required'
81
36
  restart_online_interval = 'required'
82
37
 
83
- watch_interval = 'recommended'
84
- sample_duration = 'recommended'
85
- sample_interval = 'recommended'
86
- sample_outlier_drop = 'recommended'
87
- threshold_min_uptime = 'recommended'
88
38
  threshold_low_gap = 'recommended'
89
- snap_minutes = 'recommended'
90
39
  low_gap_minutes = 'recommended'
91
40
  high_gap_minutes = 'recommended'
92
-
93
- weight_restart_soon = 'optional'
94
- weight_ram = 'optional'
95
- weight_cpu = 'optional'
96
- weight_uptime = 'optional'
97
- weight_tps = 'optional'
98
- weight_low_uptime = 'optional'
99
- weight_per_player = 'optional'
41
+ snap_minutes = 'recommended'
42
+ watch_interval = 'recommended'