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.
@@ -0,0 +1,146 @@
1
+ from typing import Any
2
+ import os
3
+ import shutil
4
+ from dataclasses import fields
5
+
6
+ from hungerlib 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()
@@ -1,37 +1,23 @@
1
1
  debug: False
2
2
  timezone: 'America/Chicago'
3
3
 
4
- panel:
5
- name: 'My Panel'
6
- url: 'https://example.com'
7
- api_key: 'CHANGE_ME'
8
-
9
4
  server:
10
5
  name: 'My SMP'
11
- server_id: 'CHANGE_ME'
12
6
  domain: 'mc.example.com'
13
7
  port: 25565
14
8
 
15
- hungerbridge:
16
- token: 'CHANGE_ME'
17
- url: 'https://api.example.com'
18
-
19
- discord:
20
- enabled: False
21
- token: 'CHANGE_ME'
22
- url: 'https://bot.example.com/webhook'
23
-
24
9
  logger:
25
10
  enabled: True
26
- name: 'Server Watcher'
11
+ name: 'ServerWatcher'
27
12
  log_path: '/home/container/logs/'
28
13
 
29
14
  prefixes:
30
15
  info: '<white>[%hh%:%mm%:%ss%] [INFO]: '
31
16
  warn: '<yellow>[%hh%:%mm%:%ss%] [WARN]: '
32
17
  error: '<red>[%hh%:%mm%:%ss%] [ERROR]: '
18
+ fatal: '<dark_red>[%hh%:%mm%:%ss%] [FATAL]: '
33
19
  debug: '<aqua>[%hh%:%mm%:%ss%] [DEBUG]: '
34
20
 
35
21
  terminal:
36
22
  enable_clearing: True
37
- handle_keyboard_interrupt: True
23
+ handle_keyboard_interrupt: True
@@ -0,0 +1,4 @@
1
+ discord:
2
+ enabled: False
3
+ token: 'CHANGE_ME'
4
+ url: 'https://bot.example.com/webhook'
@@ -0,0 +1,10 @@
1
+ hungerbridge:
2
+ url: 'https://api.example.com'
3
+ token_id: 'CHANGE_ME'
4
+ token_secret: 'CHANGE_ME'
5
+
6
+ pterodactyl:
7
+ enabled: False
8
+ url: 'https://panel.example.com'
9
+ api_key: 'CHANGE_ME'
10
+ server_id: 'CHANGE_ME'
@@ -0,0 +1,47 @@
1
+ sampling:
2
+ duration: 5.0
3
+ interval: 1.0
4
+ drop_outliers: 1
5
+
6
+ thresholds:
7
+ ram: 6 # GiB
8
+ cpu: 150 # %
9
+ uptime: 12 # minutes
10
+ min_uptime: 30 # do not restart if uptime < 30 minutes
11
+
12
+ players: 0 # optional
13
+ max_players: 0 # usually unused
14
+
15
+ tps: 19.5
16
+ tps_1m: 19.5
17
+ tps_5m: 19.5
18
+ tps_15m: 19.5
19
+
20
+ mspt: 50 # mspt > 50 = lag
21
+
22
+ loaded_chunks: 0 # optional
23
+ loaded_entities: 0
24
+
25
+ gc_pause_ms: 200 # last_gc_pause_ms threshold
26
+ thread_peak: 500 # thread leak threshold
27
+
28
+ weights:
29
+ ram: 2
30
+ cpu: 2
31
+ uptime: 1
32
+
33
+ players: 1
34
+ max_players: 0
35
+
36
+ tps: 3
37
+ tps_1m: 1
38
+ tps_5m: 1
39
+ tps_15m: 1
40
+
41
+ mspt: 3
42
+
43
+ loaded_chunks: 0
44
+ loaded_entities: 0
45
+
46
+ gc_pause_ms: 2
47
+ thread_peak: 2
@@ -1,34 +1,12 @@
1
- watch_interval: 300 # in seconds
2
-
3
- sampling:
4
- duration: 5.0 # total seconds to sample
5
- interval: 1.0 # delay between samples (0 = no smoothing)
6
- drop_outliers: 1 # number of highest and lowest samples to drop
7
-
8
- thresholds:
9
- ram: 6
10
- cpu: 150
11
- uptime: 12
12
- tps: 19.5
13
- min_uptime: 30 # will not restart the server if the total uptime is less than 30 minutes
14
- low_gap: 2
15
-
16
- weights:
17
- restart_soon: 3
18
- ram: 1
19
- cpu: 1
20
- uptime: 1
21
- tps: 1
22
- low_uptime: 5
23
- per_player: 1
1
+ restart:
2
+ wait_seconds: 30
3
+ timeout: 120
4
+ online_interval: 2
24
5
 
25
- gaps:
6
+ schedule:
7
+ threshold_low_gap: 2
26
8
  low_gap_minutes: 120
27
9
  high_gap_minutes: 60
10
+ snap_minutes: [0, 30]
28
11
 
29
- snap_minutes: [0, 30] # will snap the scheduled time to the nearest hour or half hour
30
-
31
- restart:
32
- wait_seconds: 30
33
- online_timeout: 120
34
- online_interval: 2
12
+ watch_interval: 300
@@ -0,0 +1,60 @@
1
+ class Evaluator:
2
+ def __init__(self, config):
3
+ self.cfg = config
4
+
5
+ def evaluate(self, m: dict):
6
+ score = 0
7
+ flags = []
8
+ reasons = []
9
+
10
+ def check(metric_name, value, threshold, weight, compare='>'):
11
+ nonlocal score, flags, reasons
12
+ if value is None:
13
+ return
14
+ if compare == '>' and value > threshold:
15
+ score += weight
16
+ flags.append(metric_name)
17
+ reasons.append(f"{metric_name}: {value} > {threshold}")
18
+ elif compare == '<' and value < threshold:
19
+ score += weight
20
+ flags.append(metric_name)
21
+ reasons.append(f"{metric_name}: {value} < {threshold}")
22
+
23
+ # RAM / CPU
24
+ check('ram', m['ram'], self.cfg.threshold_ram, self.cfg.weight_ram, '>')
25
+ check('cpu', m['cpu'], self.cfg.threshold_cpu, self.cfg.weight_cpu, '>')
26
+
27
+ # Uptime (low uptime is bad)
28
+ check('uptime', m['uptime'], self.cfg.threshold_uptime, self.cfg.weight_uptime, '<')
29
+
30
+ # Players
31
+ check('players', m['players'], self.cfg.threshold_players, self.cfg.weight_players, '>')
32
+
33
+ # TPS
34
+ check('tps', m['tps'], self.cfg.threshold_tps, self.cfg.weight_tps, '<')
35
+ check('tps_1m', m['tps_1m'], self.cfg.threshold_tps_1m, self.cfg.weight_tps_1m, '<')
36
+ check('tps_5m', m['tps_5m'], self.cfg.threshold_tps_5m, self.cfg.weight_tps_5m, '<')
37
+ check('tps_15m', m['tps_15m'], self.cfg.threshold_tps_15m, self.cfg.weight_tps_15m, '<')
38
+
39
+ # MSPT
40
+ check('mspt', m['mspt'], self.cfg.threshold_mspt, self.cfg.weight_mspt, '>')
41
+
42
+ # Loaded chunks/entities
43
+ check('loaded_chunks', m['loaded_chunks']['total'], self.cfg.threshold_loaded_chunks, self.cfg.weight_loaded_chunks, '>')
44
+ check('loaded_entities', m['loaded_entities']['total'], self.cfg.threshold_loaded_entities, self.cfg.weight_loaded_entities, '>')
45
+
46
+ # GC stats
47
+ gc = m['gc_stats']
48
+ if gc:
49
+ check('gc_pause_ms', gc['last_gc_pause_ms'], self.cfg.threshold_gc_pause_ms, self.cfg.weight_gc_pause_ms, '>')
50
+
51
+ # Thread stats
52
+ threads = m['thread_stats']
53
+ if threads:
54
+ check('thread_peak', threads['peak'], self.cfg.threshold_thread_peak, self.cfg.weight_thread_peak, '>')
55
+
56
+ return {
57
+ 'score': score,
58
+ 'flags': flags,
59
+ 'reasons': reasons
60
+ }
@@ -0,0 +1,4 @@
1
+ class UnsupportedOperationError(NotImplementedError): pass
2
+
3
+ class PteroConnectionError(ConnectionError): pass
4
+ class BridgeConnectionError(ConnectionError): pass
@@ -0,0 +1,92 @@
1
+ import time
2
+ from statistics import mean
3
+ from .targetserver import TargetServer
4
+
5
+
6
+ class MetricFetcher:
7
+ def __init__(self, server: TargetServer):
8
+ self.server = server
9
+
10
+ def snapshot(
11
+ self,
12
+ duration: float = 0.0,
13
+ interval: float = 0.5,
14
+ drop_outliers: int = 0,
15
+ ):
16
+ '''
17
+ Takes a snapshot of server metrics.
18
+
19
+ Only RAM + CPU are smoothed.
20
+ All other metrics are instant snapshots.
21
+
22
+ duration: total seconds to sample (0 = no smoothing)
23
+ interval: delay between samples
24
+ drop_outliers: number of highest and lowest samples to drop (for RAM/CPU only)
25
+ '''
26
+
27
+ # smoothing mode (ram + cpu)
28
+ if duration > 0:
29
+ ram_samples = []
30
+ cpu_samples = []
31
+
32
+ end = time.time() + duration
33
+ while time.time() < end:
34
+ ram_samples.append(self.server.getRAM())
35
+ cpu_samples.append(self.server.getCPULoad())
36
+ time.sleep(interval)
37
+
38
+ def smooth(values):
39
+ if not values:
40
+ return None
41
+ values = sorted(values)
42
+ if drop_outliers > 0:
43
+ values = values[drop_outliers:len(values) - drop_outliers]
44
+ return mean(values) if values else None
45
+
46
+ ram = smooth(ram_samples)
47
+ cpu = smooth(cpu_samples)
48
+
49
+ # instant mode
50
+ else:
51
+ ram = self.server.getRAM()
52
+ cpu = self.server.getCPULoad()
53
+
54
+ # instant metrics (never smoothed)
55
+ uptime = self.server.getUptime()
56
+
57
+ players = self.server.getPlayers('count')
58
+ max_players = self.server.getMaxPlayers()
59
+
60
+ tps = self.server.getTPS()
61
+ tps_1m = self.server.getTPS('1m')
62
+ tps_5m = self.server.getTPS('5m')
63
+ tps_15m = self.server.getTPS('15m')
64
+ mspt = self.server.getMSPT()
65
+
66
+ loaded_chunks = self.server.getLoadedChunks()
67
+ loaded_entities = self.server.getLoadedEntities()
68
+
69
+ gc_stats = self.server.getGCStats()
70
+ thread_stats = self.server.getThreadStats()
71
+
72
+ # final metric dict
73
+ return {
74
+ 'ram': ram,
75
+ 'cpu': cpu,
76
+ 'uptime': uptime,
77
+
78
+ 'players': players,
79
+ 'max_players': max_players,
80
+
81
+ 'tps': tps,
82
+ 'tps_1m': tps_1m,
83
+ 'tps_5m': tps_5m,
84
+ 'tps_15m': tps_15m,
85
+ 'mspt': mspt,
86
+
87
+ 'loaded_chunks': loaded_chunks,
88
+ 'loaded_entities': loaded_entities,
89
+
90
+ 'gc_stats': gc_stats,
91
+ 'thread_stats': thread_stats
92
+ }
@@ -0,0 +1,102 @@
1
+ from zoneinfo import ZoneInfo
2
+
3
+ from hungerlib import servers, MessageRouter
4
+ from mapres import MapResolver, maps
5
+
6
+ from .configmanager import config_manager
7
+ from .targetserver import TargetServer
8
+
9
+ class Router:
10
+ def __init__(self, server: TargetServer):
11
+ self.config_manager = config_manager
12
+ self.config = self.config_manager.config
13
+ self.discordcfg = self.config_manager.discordcfg
14
+ self.env = self.config_manager.env
15
+ self.watchercfg = self.config_manager.watchercfg
16
+
17
+ # resolver for internal mapping
18
+ self.resolver = MapResolver()
19
+ self.res = self.resolver.res
20
+
21
+ # logger name
22
+ logger_name = self.config.logger_name if self.config.logger_name else 'ServerWatcher'
23
+
24
+ # router using mapres
25
+ self.router = MessageRouter(
26
+ name=logger_name,
27
+ Servers=[server],
28
+ log_path=self.config.log_path,
29
+
30
+ origin_maps=[
31
+ maps.ascii_colors,
32
+ maps.time(self.config.timezone),
33
+ self.config,
34
+ self.discordcfg,
35
+ self.env,
36
+ self.watchercfg,
37
+ ],
38
+
39
+ destination_maps=[
40
+ maps.ascii_colors,
41
+ maps.time(self.config.timezone),
42
+ self.config,
43
+ self.discordcfg,
44
+ self.env,
45
+ self.watchercfg,
46
+ ],
47
+
48
+ broadcast_maps=[
49
+ maps.mc_colors,
50
+ maps.time(self.config.timezone),
51
+ self.config,
52
+ self.discordcfg,
53
+ self.env,
54
+ self.watchercfg,
55
+ ],
56
+
57
+ file_maps=[
58
+ maps.strip_colors,
59
+ maps.time(self.config.timezone),
60
+ self.config,
61
+ self.discordcfg,
62
+ self.env,
63
+ self.watchercfg,
64
+ ],
65
+
66
+ prefix_maps=[
67
+ maps.ascii_colors,
68
+ maps.time(self.config.timezone),
69
+ ],
70
+
71
+ info_prefix=self.config.info_prefix,
72
+ warn_prefix=self.config.warn_prefix,
73
+ error_prefix=self.config.error_prefix,
74
+
75
+ buffer_enabled=True,
76
+ origin_output=True
77
+ )
78
+
79
+ self.router.registerLevel(
80
+ name='debug',
81
+ prefix=self.config.debug_prefix,
82
+ file_method='debug',
83
+ routes=['origin']
84
+ )
85
+
86
+ self.router.registerLevel(
87
+ name='fatal',
88
+ prefix=self.config.fatal_prefix,
89
+ file_method='fatal',
90
+ routes=['origin']
91
+ )
92
+
93
+ self.info = self.router.info
94
+ self.warn = self.router.warn
95
+ self.error = self.router.error
96
+ self.fatal = self.router.fatal
97
+ self.debug = self.router.debug
98
+ self.broadcast = self.router.broadcast
99
+ self.origin = self.router.origin
100
+ self.destination = self.router.destination
101
+
102
+ self.tz = ZoneInfo(self.config.timezone)