serverwatcher 6.dev60__py3-none-any.whl → 7.dev1__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.
@@ -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)
@@ -0,0 +1,147 @@
1
+ from hungerlib import Panel, MinecraftServer, BridgeClient
2
+ from hungerlib import utils, methods as m
3
+
4
+ from .configmanager import config_manager
5
+ from .exceptions import UnsupportedOperationError
6
+
7
+ class TargetServer:
8
+ def __init__(self, bridge_start_handler=None, bridge_restart_handler=None, bridge_kill_handler=None):
9
+ self.config_manager = config_manager
10
+ self.env = self.config_manager.env
11
+ self.config = self.config_manager.config
12
+
13
+ self.ptero_enabled = self.env.ptero_enabled
14
+
15
+ self.panel = Panel('Panel', self.env.ptero_url, self.env.ptero_api_key)
16
+ self.mc_server = MinecraftServer(
17
+ 'Minecraft Server',
18
+ self.panel,
19
+ self.env.ptero_server_id,
20
+ self.config.server_domain,
21
+ self.config.server_port,
22
+ None
23
+ )
24
+ self.bridge = BridgeClient(
25
+ url = self.env.bridge_url,
26
+ token_id = self.env.bridge_token_id,
27
+ token_secret = self.env.bridge_token_secret,
28
+ static_delay = 0.5
29
+ )
30
+
31
+ self.bridge_start_handler = bridge_start_handler
32
+ self.bridge_restart_handler = bridge_restart_handler
33
+ self.bridge_kill_handler = bridge_kill_handler
34
+
35
+ m.proxy(self, self.bridge.getTokenInfo)
36
+
37
+ m.proxy(self, self.bridge.getPlatform)
38
+ m.proxy(self, self.bridge.getMinecraftVersion)
39
+ m.proxy(self, self.bridge.getBridgeVersion)
40
+ m.proxy(self, self.bridge.getBridgePort)
41
+
42
+ m.proxy(self, self.bridge.getPlayers)
43
+ m.proxy(self, self.bridge.getMaxPlayers)
44
+
45
+ m.proxy(self, self.bridge.getTPS)
46
+ m.proxy(self, self.bridge.getMSPT)
47
+
48
+ m.proxy(self, self.bridge.getLoadedChunks)
49
+ m.proxy(self, self.bridge.getLoadedEntities)
50
+
51
+ m.proxy(self, self.bridge.getGCStats)
52
+ m.proxy(self, self.bridge.getThreadStats)
53
+ m.proxy(self, self.bridge.getNetworkStats)
54
+
55
+ m.proxy(self, self.bridge.log)
56
+ m.proxy(self, self.bridge.runCommand)
57
+
58
+ self.stream = self.bridge.stream
59
+
60
+ def checkPtero(self):
61
+ '''Check if the panel is reachable and the API key is valid.'''
62
+ return utils.validateAll(self.panel, self.mc_server)
63
+
64
+ def checkBridge(self):
65
+ '''Check if the bridge is reachable and the token is valid.'''
66
+ return self.bridge.isOk()
67
+
68
+ def isOnline(self):
69
+ '''Returns True if online, False if offline'''
70
+ return self.mc_server.isOnline()
71
+
72
+ def isOffline(self):
73
+ '''Returns True if offline, False if online'''
74
+ return self.mc_server.isOffline()
75
+
76
+ def refreshResources(self):
77
+ '''Refreshes the server's resources (ptero only)'''
78
+ if self.ptero_enabled:
79
+ self.mc_server.refresh()
80
+ else:
81
+ raise UnsupportedOperationError('Bridge-only mode: refreshing is not necessary and not supported')
82
+
83
+ def getRAM(self):
84
+ '''Returns current RAM usage'''
85
+ if self.ptero_enabled:
86
+ return self.mc_server.getRAM(rounding=0, gb=False)
87
+ else:
88
+ return self.bridge.getMemoryStats()['process_used']
89
+
90
+ def getDisk(self):
91
+ '''Returns current disk usage'''
92
+ if self.ptero_enabled:
93
+ return self.mc_server.getDisk(rounding=0, gb=False)
94
+ else:
95
+ raise UnsupportedOperationError('Bridge-only mode: getting disk usage is not supported')
96
+
97
+ def getCPULoad(self):
98
+ '''Returns current CPU usage'''
99
+ if self.ptero_enabled:
100
+ return self.mc_server.getCPU(rounding=0)
101
+ else:
102
+ return self.bridge.getCPUStats()['load']
103
+
104
+ def getProcessorCount(self):
105
+ '''Returns the number of processors'''
106
+ return self.bridge.getCPUStats()['processors']
107
+
108
+ def getUptime(self):
109
+ '''Returns the uptime'''
110
+ if self.ptero_enabled:
111
+ return self.mc_server.getUptime()
112
+ else:
113
+ return self.bridge.getUptime()
114
+
115
+ def startServer(self):
116
+ '''Starts the server (ptero-only)'''
117
+ if self.ptero_enabled:
118
+ return self.mc_server.start()
119
+ elif self.bridge_start_handler is not None:
120
+ self.bridge_start_handler()
121
+ else:
122
+ raise UnsupportedOperationError('Bridge-only mode: starting the server is not supported unless a bridge start handler is provided.')
123
+
124
+ def restartServer(self):
125
+ '''Restarts the server (ptero-only)'''
126
+ if self.ptero_enabled:
127
+ return self.mc_server.restart()
128
+ elif self.bridge_restart_handler is not None:
129
+ self.bridge_restart_handler()
130
+ else:
131
+ raise UnsupportedOperationError('Bridge-only mode: restarting the server is not supported unless a bridge restart handler is provided.')
132
+
133
+ def stopServer(self):
134
+ '''Stops the server (ptero and bridge)'''
135
+ if self.ptero_enabled:
136
+ return self.mc_server.stop()
137
+ else:
138
+ self.bridge.stopServer()
139
+
140
+ def killServer(self):
141
+ '''Kills the server (ptero-only)'''
142
+ if self.ptero_enabled:
143
+ return self.mc_server.kill()
144
+ elif self.bridge_kill_handler is not None:
145
+ self.bridge_kill_handler()
146
+ else:
147
+ raise UnsupportedOperationError('Bridge-only mode: killing the server is not supported unless a bridge kill handler is provided.')