serverwatcher 5.33.dev4__py3-none-any.whl → 6a2__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/__main__.py +71 -17
- serverwatcher/configclasses/config.py +14 -3
- serverwatcher/configclasses/messages.py +2 -2
- serverwatcher/configclasses/watcher.py +2 -2
- serverwatcher/defaultconfigs/config.yaml +6 -1
- serverwatcher/defaultconfigs/messages.yaml +21 -21
- serverwatcher/tests/test.py +77 -0
- serverwatcher/tests/test2.py +323 -0
- serverwatcher/validator.py +17 -3
- serverwatcher/watcher.py +102 -27
- serverwatcher/watchercli.py +144 -0
- serverwatcher-6a2.dist-info/METADATA +60 -0
- serverwatcher-6a2.dist-info/RECORD +19 -0
- {serverwatcher-5.33.dev4.dist-info → serverwatcher-6a2.dist-info}/WHEEL +1 -1
- serverwatcher-5.33.dev4.dist-info/METADATA +0 -47
- serverwatcher-5.33.dev4.dist-info/RECORD +0 -16
- {serverwatcher-5.33.dev4.dist-info → serverwatcher-6a2.dist-info}/licenses/LICENSE +0 -0
- {serverwatcher-5.33.dev4.dist-info → serverwatcher-6a2.dist-info}/top_level.txt +0 -0
serverwatcher/__main__.py
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import time
|
|
2
|
+
import asyncio
|
|
3
|
+
import threading
|
|
4
|
+
|
|
5
|
+
from mapres import rprint, setGlobalMaps, ascii_colors
|
|
6
|
+
|
|
3
7
|
from hungerlib.validator import (
|
|
4
8
|
ValidationError,
|
|
5
9
|
FatalError,
|
|
@@ -7,41 +11,91 @@ from hungerlib.validator import (
|
|
|
7
11
|
FallbackError,
|
|
8
12
|
RecommendedError,
|
|
9
13
|
)
|
|
10
|
-
|
|
14
|
+
|
|
15
|
+
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
|
+
|
|
11
46
|
|
|
12
47
|
def main():
|
|
13
48
|
try:
|
|
14
49
|
validate_all()
|
|
15
50
|
|
|
16
51
|
except FatalError as e:
|
|
17
|
-
|
|
18
|
-
|
|
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.')
|
|
19
56
|
return
|
|
20
57
|
|
|
21
58
|
except TypeMismatchError as e:
|
|
22
|
-
|
|
23
|
-
|
|
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.')
|
|
24
63
|
return
|
|
25
64
|
|
|
26
65
|
except FallbackError as e:
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
|
31
71
|
|
|
32
72
|
except RecommendedError as e:
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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...')
|
|
36
77
|
time.sleep(5)
|
|
37
78
|
|
|
38
79
|
except ValidationError as e:
|
|
39
|
-
|
|
40
|
-
|
|
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
|
+
|
|
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.')
|
|
41
91
|
return
|
|
42
92
|
|
|
93
|
+
# Start watcher thread
|
|
43
94
|
watcher = ServerWatcher()
|
|
44
|
-
watcher.run()
|
|
95
|
+
threading.Thread(target=watcher.run, daemon=True).start()
|
|
96
|
+
|
|
97
|
+
cli = WatcherCLI(watcher)
|
|
98
|
+
asyncio.run(cli.run())
|
|
45
99
|
|
|
46
100
|
if __name__ == '__main__':
|
|
47
101
|
main()
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
from mapres import datamap
|
|
1
|
+
from mapres import datamap
|
|
2
2
|
|
|
3
|
-
@datamap
|
|
3
|
+
@datamap.braces.config(recursive=True)
|
|
4
4
|
class GlobalConfig:
|
|
5
5
|
__user_config_path__ = 'config/config.yaml'
|
|
6
6
|
__default_config_path__ = 'defaultconfigs/config.yaml'
|
|
@@ -20,6 +20,10 @@ class GlobalConfig:
|
|
|
20
20
|
bridge_token: str = 'hungerbridge.token'
|
|
21
21
|
bridge_url: str = 'hungerbridge.url'
|
|
22
22
|
|
|
23
|
+
discord_enabled: bool = 'discord.enabled'
|
|
24
|
+
discord_token: str = 'discord.token'
|
|
25
|
+
discord_url: str = 'discord.url'
|
|
26
|
+
|
|
23
27
|
enable_logging: bool = 'logger.enabled'
|
|
24
28
|
logger_name: str = 'logger.name'
|
|
25
29
|
log_path: str = 'logger.log_path'
|
|
@@ -47,7 +51,11 @@ class fallbacks:
|
|
|
47
51
|
server_port = 25565
|
|
48
52
|
|
|
49
53
|
bridge_token = 'CHANGE_ME'
|
|
50
|
-
bridge_url = 'https://api.example.com
|
|
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'
|
|
51
59
|
|
|
52
60
|
enable_logging = True
|
|
53
61
|
logger_name = 'Server Watcher'
|
|
@@ -74,4 +82,7 @@ class rules:
|
|
|
74
82
|
server_port = 'recommended'
|
|
75
83
|
bridge_url = 'recommended'
|
|
76
84
|
|
|
85
|
+
discord_url = 'recommended'
|
|
86
|
+
discord_token = 'recommended'
|
|
87
|
+
|
|
77
88
|
# everything else defaults to optional
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
from mapres import datamap
|
|
1
|
+
from mapres import datamap
|
|
2
2
|
|
|
3
|
-
@datamap
|
|
3
|
+
@datamap.braces.config(recursive=True)
|
|
4
4
|
class MessagesConfig:
|
|
5
5
|
__user_config_path__ = 'config/messages.yaml'
|
|
6
6
|
__default_config_path__ = 'defaultconfigs/messages.yaml'
|
|
@@ -14,7 +14,12 @@ server:
|
|
|
14
14
|
|
|
15
15
|
hungerbridge:
|
|
16
16
|
token: 'CHANGE_ME'
|
|
17
|
-
url: 'https://api.example.com
|
|
17
|
+
url: 'https://api.example.com'
|
|
18
|
+
|
|
19
|
+
discord:
|
|
20
|
+
enabled: False
|
|
21
|
+
token: 'CHANGE_ME'
|
|
22
|
+
url: 'https://bot.example.com/webhook'
|
|
18
23
|
|
|
19
24
|
logger:
|
|
20
25
|
enabled: True
|
|
@@ -9,22 +9,22 @@
|
|
|
9
9
|
# <red> <green> <yellow> <reset>
|
|
10
10
|
#
|
|
11
11
|
# 2. GlobalConfig (config)
|
|
12
|
-
# Provides server-wide configuration values. Syntax: {field}
|
|
12
|
+
# Provides server-wide configuration values. Syntax: {{field}}
|
|
13
13
|
# Examples:
|
|
14
|
-
# {server_name}
|
|
15
|
-
# {panel_url}
|
|
14
|
+
# {{server_name}}
|
|
15
|
+
# {{panel_url}}
|
|
16
16
|
#
|
|
17
17
|
# 3. MessagesConfig (keys)
|
|
18
|
-
# Provides message templates. Syntax: {field}
|
|
18
|
+
# Provides message templates. Syntax: {{field}}
|
|
19
19
|
# Examples:
|
|
20
|
-
# {prefix}
|
|
21
|
-
# {broadcast_restart_at}
|
|
20
|
+
# {{prefix}}
|
|
21
|
+
# {{broadcast_restart_at}}
|
|
22
22
|
#
|
|
23
23
|
# 4. WatcherConfig (config)
|
|
24
|
-
# Provides thresholds, weights, and timing values. Syntax: {field}
|
|
24
|
+
# Provides thresholds, weights, and timing values. Syntax: {{field}}
|
|
25
25
|
# Examples:
|
|
26
|
-
# {threshold_ram}
|
|
27
|
-
# {low_gap_minutes}
|
|
26
|
+
# {{threshold_ram}}
|
|
27
|
+
# {{low_gap_minutes}}
|
|
28
28
|
#
|
|
29
29
|
# 5. TimeMap (dynamic)
|
|
30
30
|
# Provides live timestamps. Syntax: %field%
|
|
@@ -41,11 +41,11 @@
|
|
|
41
41
|
prefix: '<aqua>[Server Watcher]'
|
|
42
42
|
bullet: '-'
|
|
43
43
|
|
|
44
|
-
broadcast_restart_at: '{prefix} The server will restart at {time} CDT.'
|
|
44
|
+
broadcast_restart_at: '{{prefix}} The server will restart at {{time}} CDT.'
|
|
45
45
|
|
|
46
46
|
broadcast_templates:
|
|
47
|
-
minutes: '{prefix} Restart in {n} minute{s}!'
|
|
48
|
-
seconds: '{prefix} <red>Restarting in {n} second{s}!'
|
|
47
|
+
minutes: '{{prefix}} Restart in {{n}} minute{{s}}!'
|
|
48
|
+
seconds: '{{prefix}} <red>Restarting in {{n}} second{{s}}!'
|
|
49
49
|
|
|
50
50
|
broadcast_minutes: {}
|
|
51
51
|
broadcast_seconds: {}
|
|
@@ -55,25 +55,25 @@ logging:
|
|
|
55
55
|
status_check: 'Checking server status...'
|
|
56
56
|
validation_fail: 'Validation FAILED.'
|
|
57
57
|
validation_ok: 'All validation checks succeeded.'
|
|
58
|
-
sampling_start: 'Starting sampling process. This should take about {duration} seconds...'
|
|
58
|
+
sampling_start: 'Starting sampling process. This should take about {{duration}} seconds...'
|
|
59
59
|
shutdown: 'Shutting down ServerWatcher.'
|
|
60
60
|
immediate_restart: 'Restarting immediately.'
|
|
61
61
|
no_restart: 'The server does not need to restart.'
|
|
62
62
|
scheduled: 'Restart needed, but anti-restart factors outweigh it.'
|
|
63
|
-
gap_low: 'Gap {gap}. Scheduling restart in 2 hours.'
|
|
64
|
-
gap_high: 'Gap {gap}. Scheduling restart in 1 hour.'
|
|
63
|
+
gap_low: 'Gap {{gap}}. Scheduling restart in 2 hours.'
|
|
64
|
+
gap_high: 'Gap {{gap}}. Scheduling restart in 1 hour.'
|
|
65
65
|
|
|
66
66
|
reasons:
|
|
67
67
|
pro_splash: 'PRO-RESTART REASONS:'
|
|
68
68
|
anti_splash: 'ANTI-RESTART REASONS:'
|
|
69
69
|
|
|
70
70
|
restart_soon: 'The server is set to restart soon'
|
|
71
|
-
ram: 'RAM usage ({ram}) is higher than {threshold} GB'
|
|
72
|
-
cpu: 'CPU usage ({cpu}) is higher than {threshold}%'
|
|
73
|
-
uptime: 'Uptime {uptime} exceeds {threshold}h'
|
|
74
|
-
tps: 'TPS {tps} is lower than {threshold}'
|
|
75
|
-
low_uptime: 'Uptime {uptime} is shorter than 30m'
|
|
76
|
-
players: 'There {verb} {count} {plural} online' # produces: 'There are 2 players online' or 'There is 1 player online'
|
|
71
|
+
ram: 'RAM usage ({{ram}}) is higher than {{threshold}} GB'
|
|
72
|
+
cpu: 'CPU usage ({{cpu}}) is higher than {{threshold}}%'
|
|
73
|
+
uptime: 'Uptime {{uptime}} exceeds {{threshold}}h'
|
|
74
|
+
tps: 'TPS {{tps}} is lower than {{threshold}}'
|
|
75
|
+
low_uptime: 'Uptime {{uptime}} is shorter than 30m'
|
|
76
|
+
players: 'There {{verb}} {{count}} {{plural}} online' # produces: 'There are 2 players online' or 'There is 1 player online'
|
|
77
77
|
|
|
78
78
|
pro_restart_number: 'Pro-restart: '
|
|
79
79
|
anti_restart_number: 'Anti-restart:'
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
@command('stats') # removed requires_children=True, the DSL should interpret no logic as requiring children
|
|
2
|
+
def stats(self):
|
|
3
|
+
'''
|
|
4
|
+
Retrieve and print server statistics
|
|
5
|
+
'''
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@stats.child('get') # removed requires_arguments=False, the DSL should interpret logic for both as supporting both args and noargs. that and having arg=None. If it didn't support arguments it would just be self right? And if it required arguments it would have arg, not arg=None right?
|
|
9
|
+
def stats_get(self, arg=None):
|
|
10
|
+
'''
|
|
11
|
+
Retrieve and print all or specific server statistics
|
|
12
|
+
'''
|
|
13
|
+
# the below will render as not having indents correct? or not?
|
|
14
|
+
__args__ = '''
|
|
15
|
+
ram: [rounding] [--raw]
|
|
16
|
+
cpu: [rounding]
|
|
17
|
+
uptime: [rounding] [mode]
|
|
18
|
+
players
|
|
19
|
+
version
|
|
20
|
+
platform
|
|
21
|
+
'''
|
|
22
|
+
self.watcher.server.refresh()
|
|
23
|
+
|
|
24
|
+
if arg is None:
|
|
25
|
+
return # will add support later for showing all stats, but this acts as a placeholder for the DLS to know it supports optional arguments.
|
|
26
|
+
|
|
27
|
+
gb = not raw()
|
|
28
|
+
fmt = not raw()
|
|
29
|
+
|
|
30
|
+
unit = ''
|
|
31
|
+
match arg:
|
|
32
|
+
case 'ram':
|
|
33
|
+
value = self.watcher.server.getRAM(rounding=rounding(), gb=gb)
|
|
34
|
+
name = 'RAM'
|
|
35
|
+
unit = ' GB' if gb else ' MB'
|
|
36
|
+
case 'cpu':
|
|
37
|
+
value = self.watcher.server.getCPU(rounding=rounding())
|
|
38
|
+
name = 'CPU'
|
|
39
|
+
unit = '%'
|
|
40
|
+
case 'uptime':
|
|
41
|
+
value = self.watcher.server.getUptime(formatted=fmt)
|
|
42
|
+
name = 'Uptime'
|
|
43
|
+
unit = '' if fmt else 'ms'
|
|
44
|
+
case 'tps':
|
|
45
|
+
value = self.watcher.server.getTPS(rounding=rounding(), mode=mode())
|
|
46
|
+
name = 'TPS'
|
|
47
|
+
case 'players':
|
|
48
|
+
value = self.watcher.server.getPlayers()
|
|
49
|
+
name = 'Players'
|
|
50
|
+
case 'version':
|
|
51
|
+
value = self.watcher.server.version
|
|
52
|
+
name = 'Minecraft version'
|
|
53
|
+
case 'platform':
|
|
54
|
+
value = self.watcher.server.platform
|
|
55
|
+
name = 'Server platform'
|
|
56
|
+
case _:
|
|
57
|
+
return self.safePrint('Unknown stat')
|
|
58
|
+
|
|
59
|
+
self.bprint(f'{name}: {value}{unit}')
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@stats.get.param('rounding', type=int, default=2)
|
|
63
|
+
def rounding(value):
|
|
64
|
+
'''The decimal place to round to''' # yes, descriptions need to be supported for flags and params too.
|
|
65
|
+
return value
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@stats.get.param('mode', type=str, default='current')
|
|
69
|
+
def mode(value):
|
|
70
|
+
'''The mode for TPS. Accepted: current, 1m, 5m, tick_time'''
|
|
71
|
+
return value
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@stats.get.flag('raw')
|
|
75
|
+
def raw():
|
|
76
|
+
'''Return the raw value instead of the calculated or formatted string'''
|
|
77
|
+
return True
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import argparse
|
|
3
|
+
import cmd
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
import termios
|
|
7
|
+
import tty
|
|
8
|
+
|
|
9
|
+
from hungerlib import utils
|
|
10
|
+
from mapres import res, maps, setGlobalMaps
|
|
11
|
+
|
|
12
|
+
from .watcher import ServerWatcher
|
|
13
|
+
|
|
14
|
+
setGlobalMaps(maps.ascii_colors)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class BufferingStdout:
|
|
18
|
+
def __init__(self, buffer, real_stdout):
|
|
19
|
+
self.buffer = buffer
|
|
20
|
+
self.real_stdout = real_stdout
|
|
21
|
+
|
|
22
|
+
def write(self, text):
|
|
23
|
+
# capture only non-empty lines
|
|
24
|
+
if self.buffer.enabled and text.strip():
|
|
25
|
+
self.buffer.captured.append(text.rstrip("\n"))
|
|
26
|
+
self.real_stdout.write(text)
|
|
27
|
+
|
|
28
|
+
def flush(self):
|
|
29
|
+
self.real_stdout.flush()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# we keep this only for the positional stat name
|
|
33
|
+
stats_parser = argparse.ArgumentParser(add_help=False)
|
|
34
|
+
stats_parser.add_argument(
|
|
35
|
+
"stat",
|
|
36
|
+
choices=["cpu", "ram", "uptime", "tps", "players"],
|
|
37
|
+
help="Statistic to retrieve"
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
schedule_parser = argparse.ArgumentParser()
|
|
41
|
+
schedule_parser.add_argument(
|
|
42
|
+
"minutes",
|
|
43
|
+
type=int,
|
|
44
|
+
help="Minutes until restart"
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class WatcherCLI(cmd.Cmd):
|
|
49
|
+
prompt = ""
|
|
50
|
+
|
|
51
|
+
def __init__(self, watcher: ServerWatcher):
|
|
52
|
+
self.watcher = watcher
|
|
53
|
+
|
|
54
|
+
# buffer for CLI output
|
|
55
|
+
self.buffer = utils.Buffer(enabled=True)
|
|
56
|
+
|
|
57
|
+
# real stdout (terminal)
|
|
58
|
+
self.real_stdout = sys.stdout
|
|
59
|
+
|
|
60
|
+
# CLI stdout goes through BufferingStdout → captured in self.buffer
|
|
61
|
+
self.cli_stdout = BufferingStdout(self.buffer, self.real_stdout)
|
|
62
|
+
|
|
63
|
+
# permanently override cmd.Cmd stdout
|
|
64
|
+
super().__init__(stdout=self.cli_stdout)
|
|
65
|
+
|
|
66
|
+
# output mode: both | cli | silent
|
|
67
|
+
self.outputMode = "both"
|
|
68
|
+
|
|
69
|
+
# disable rawinput in order to control input manually
|
|
70
|
+
self.use_rawinput = False
|
|
71
|
+
|
|
72
|
+
def read_line_raw(self):
|
|
73
|
+
fd = sys.stdin.fileno()
|
|
74
|
+
old = termios.tcgetattr(fd)
|
|
75
|
+
|
|
76
|
+
try:
|
|
77
|
+
tty.setraw(fd)
|
|
78
|
+
chars = []
|
|
79
|
+
while True:
|
|
80
|
+
ch = sys.stdin.read(1)
|
|
81
|
+
if ch in ("\r", "\n"):
|
|
82
|
+
break
|
|
83
|
+
chars.append(ch)
|
|
84
|
+
|
|
85
|
+
return "".join(chars)
|
|
86
|
+
finally:
|
|
87
|
+
termios.tcsetattr(fd, termios.TCSADRAIN, old)
|
|
88
|
+
|
|
89
|
+
async def run(self):
|
|
90
|
+
while True:
|
|
91
|
+
# read input without echo (Pterodactyl will echo anyway)
|
|
92
|
+
line = await asyncio.to_thread(self.read_line_raw)
|
|
93
|
+
line = line.strip()
|
|
94
|
+
|
|
95
|
+
if not line:
|
|
96
|
+
continue
|
|
97
|
+
|
|
98
|
+
# capture command (Pterodactyl already printed it)
|
|
99
|
+
if self.buffer.enabled and not line.startswith("view"):
|
|
100
|
+
self.buffer.captured.append(line)
|
|
101
|
+
|
|
102
|
+
# run command (self.stdout is already overridden)
|
|
103
|
+
stop = await asyncio.to_thread(self.onecmd, line)
|
|
104
|
+
|
|
105
|
+
if stop:
|
|
106
|
+
break
|
|
107
|
+
|
|
108
|
+
def safePrint(self, msg="", end="\n"):
|
|
109
|
+
self.real_stdout.write(str(msg) + end)
|
|
110
|
+
self.real_stdout.flush()
|
|
111
|
+
|
|
112
|
+
def printHeader(self):
|
|
113
|
+
self.safePrint(res("<yellow>-----------------------------------"))
|
|
114
|
+
self.safePrint(res("<yellow>-------- <aqua>ServerWatcher CLI <yellow>--------"))
|
|
115
|
+
self.safePrint(res("<yellow>-----------------------------------"))
|
|
116
|
+
self.safePrint("\n")
|
|
117
|
+
|
|
118
|
+
# ---------------------------------------------------------
|
|
119
|
+
# VIEW COMMANDS
|
|
120
|
+
# ---------------------------------------------------------
|
|
121
|
+
def do_view(self, arg):
|
|
122
|
+
"""
|
|
123
|
+
view cli
|
|
124
|
+
view watcher
|
|
125
|
+
"""
|
|
126
|
+
if arg == "cli":
|
|
127
|
+
self._view_cli()
|
|
128
|
+
elif arg == "watcher":
|
|
129
|
+
self._view_watcher()
|
|
130
|
+
else:
|
|
131
|
+
self.safePrint("Usage: view <cli|watcher>")
|
|
132
|
+
|
|
133
|
+
def _view_cli(self):
|
|
134
|
+
self.watcher.router.disableOriginOutput()
|
|
135
|
+
self.outputMode = "cli"
|
|
136
|
+
|
|
137
|
+
# CLI capture always enabled
|
|
138
|
+
self.buffer.enabled = True
|
|
139
|
+
|
|
140
|
+
utils.clearTerminal()
|
|
141
|
+
self.safePrint("", end="")
|
|
142
|
+
|
|
143
|
+
# header is always printed fresh, not stored in buffer
|
|
144
|
+
self.printHeader()
|
|
145
|
+
|
|
146
|
+
# replay captured CLI output
|
|
147
|
+
for msg in self.buffer.captured:
|
|
148
|
+
self.safePrint(msg)
|
|
149
|
+
|
|
150
|
+
def _view_watcher(self):
|
|
151
|
+
self.watcher.router.enableOriginOutput()
|
|
152
|
+
self.outputMode = "both"
|
|
153
|
+
|
|
154
|
+
# do NOT touch self.buffer.enabled here
|
|
155
|
+
|
|
156
|
+
utils.clearTerminal()
|
|
157
|
+
self.safePrint("", end="")
|
|
158
|
+
|
|
159
|
+
# replay watcher output
|
|
160
|
+
for msg in self.watcher.router.buffer.captured:
|
|
161
|
+
self.safePrint(msg)
|
|
162
|
+
|
|
163
|
+
# ---------------------------------------------------------
|
|
164
|
+
# STATS COMMANDS
|
|
165
|
+
# ---------------------------------------------------------
|
|
166
|
+
def do_stats(self, arg):
|
|
167
|
+
"""
|
|
168
|
+
stats get <cpu|ram|uptime|tps|players> [gb:true|false] [rounding:<int>]
|
|
169
|
+
Example:
|
|
170
|
+
stats get ram
|
|
171
|
+
stats get ram gb:false
|
|
172
|
+
stats get ram gb:false rounding:1
|
|
173
|
+
"""
|
|
174
|
+
parts = arg.split()
|
|
175
|
+
if len(parts) == 0 or parts[0] != "get":
|
|
176
|
+
self.safePrint("Usage: stats get <cpu|ram|uptime|tps|players> [gb:true|false] [rounding:<int>]")
|
|
177
|
+
return
|
|
178
|
+
|
|
179
|
+
# strip the leading "get"
|
|
180
|
+
tokens = parts[1:]
|
|
181
|
+
if not tokens:
|
|
182
|
+
self.safePrint("Usage: stats get <cpu|ram|uptime|tps|players> [gb:true|false] [rounding:<int>]")
|
|
183
|
+
return
|
|
184
|
+
|
|
185
|
+
# first token is the stat name, validated by stats_parser
|
|
186
|
+
try:
|
|
187
|
+
args = stats_parser.parse_args([tokens[0]])
|
|
188
|
+
stat = args.stat
|
|
189
|
+
except SystemExit:
|
|
190
|
+
self.safePrint("Usage: stats get <cpu|ram|uptime|tps|players> [gb:<bool>] [rounding:<int>] [formatted:<bool>]")
|
|
191
|
+
return
|
|
192
|
+
|
|
193
|
+
# defaults
|
|
194
|
+
gb = True
|
|
195
|
+
rounding = 2
|
|
196
|
+
formatted = True
|
|
197
|
+
|
|
198
|
+
# parse optional key:value tokens
|
|
199
|
+
for token in tokens[1:]:
|
|
200
|
+
if ":" not in token:
|
|
201
|
+
continue
|
|
202
|
+
key, value = token.split(":", 1)
|
|
203
|
+
key = key.strip().lower()
|
|
204
|
+
value = value.strip().lower()
|
|
205
|
+
|
|
206
|
+
if key == "gb":
|
|
207
|
+
gb = value == "true"
|
|
208
|
+
elif key == "rounding":
|
|
209
|
+
try:
|
|
210
|
+
rounding = int(value)
|
|
211
|
+
except ValueError:
|
|
212
|
+
self.safePrint("rounding must be an integer")
|
|
213
|
+
return
|
|
214
|
+
elif key == 'formatted':
|
|
215
|
+
formatted = value == 'true'
|
|
216
|
+
|
|
217
|
+
self._stats_get(stat, gb=gb, rounding=rounding, formatted=formatted)
|
|
218
|
+
|
|
219
|
+
def _stats_get(self, stat: str, gb: bool=True, rounding: int=2, formatted: bool=True):
|
|
220
|
+
self.watcher.server.refresh()
|
|
221
|
+
|
|
222
|
+
if stat == "ram":
|
|
223
|
+
value = self.watcher.server.getRAM(rounding=rounding, gb=gb)
|
|
224
|
+
stat_name = 'RAM'
|
|
225
|
+
unit = ' GB' if gb else ' MB'
|
|
226
|
+
elif stat == "cpu":
|
|
227
|
+
value = self.watcher.server.getCPU(rounding=rounding)
|
|
228
|
+
stat_name = 'CPU'
|
|
229
|
+
unit = '%'
|
|
230
|
+
elif stat == "uptime":
|
|
231
|
+
value = self.watcher.server.getUptime(formatted=formatted)
|
|
232
|
+
stat_name = 'Uptime'
|
|
233
|
+
unit = '' if formatted else 'ms'
|
|
234
|
+
elif stat == "tps":
|
|
235
|
+
value = self.watcher.server.getTPS()
|
|
236
|
+
stat_name = 'TPS'
|
|
237
|
+
unit = ''
|
|
238
|
+
elif stat == "players":
|
|
239
|
+
value = self.watcher.server.getPlayers()
|
|
240
|
+
stat_name = 'Players'
|
|
241
|
+
unit = ''
|
|
242
|
+
else:
|
|
243
|
+
self.safePrint("Unknown stat")
|
|
244
|
+
return
|
|
245
|
+
|
|
246
|
+
self.bprint(f'{stat_name}: {value}{unit}')
|
|
247
|
+
|
|
248
|
+
# ---------------------------------------------------------
|
|
249
|
+
# CLEAR COMMAND
|
|
250
|
+
# ---------------------------------------------------------
|
|
251
|
+
def do_clear(self, arg):
|
|
252
|
+
"""
|
|
253
|
+
clear buffer:true
|
|
254
|
+
clear buffer:false
|
|
255
|
+
"""
|
|
256
|
+
parts = arg.split()
|
|
257
|
+
|
|
258
|
+
# default: buffer:false
|
|
259
|
+
clear_buffer = False
|
|
260
|
+
|
|
261
|
+
# parse key:value pairs
|
|
262
|
+
for token in parts:
|
|
263
|
+
if ":" not in token:
|
|
264
|
+
continue
|
|
265
|
+
key, value = token.split(":", 1)
|
|
266
|
+
key = key.strip().lower()
|
|
267
|
+
value = value.strip().lower()
|
|
268
|
+
|
|
269
|
+
if key == "buffer":
|
|
270
|
+
clear_buffer = (value == "true")
|
|
271
|
+
|
|
272
|
+
# clear CLI buffer only
|
|
273
|
+
if clear_buffer:
|
|
274
|
+
self.buffer.clear()
|
|
275
|
+
|
|
276
|
+
# clear terminal (but NOT watcher buffer)
|
|
277
|
+
utils.clearTerminal()
|
|
278
|
+
|
|
279
|
+
# print header (not captured)
|
|
280
|
+
self.printHeader()
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
# ---------------------------------------------------------
|
|
284
|
+
# WATCHER COMMANDS
|
|
285
|
+
# ---------------------------------------------------------
|
|
286
|
+
def do_watcher(self, arg):
|
|
287
|
+
"""
|
|
288
|
+
watcher restart
|
|
289
|
+
watcher schedule <minutes>
|
|
290
|
+
watcher shutdown
|
|
291
|
+
"""
|
|
292
|
+
parts = arg.split()
|
|
293
|
+
|
|
294
|
+
if len(parts) == 0:
|
|
295
|
+
self.safePrint("Usage: watcher <restart|schedule|shutdown>")
|
|
296
|
+
return
|
|
297
|
+
|
|
298
|
+
sub = parts[0]
|
|
299
|
+
|
|
300
|
+
if sub == "restart":
|
|
301
|
+
self.watcher.restart_and_wait()
|
|
302
|
+
|
|
303
|
+
elif sub == "schedule":
|
|
304
|
+
try:
|
|
305
|
+
args = schedule_parser.parse_args(parts[1:])
|
|
306
|
+
self.watcher.schedule_restart(args.minutes)
|
|
307
|
+
except SystemExit:
|
|
308
|
+
self.safePrint("Usage: watcher schedule <minutes>")
|
|
309
|
+
|
|
310
|
+
elif sub == "shutdown":
|
|
311
|
+
self.watcher.shutdown()
|
|
312
|
+
return True
|
|
313
|
+
|
|
314
|
+
else:
|
|
315
|
+
self.safePrint("Usage: watcher <restart|schedule|shutdown>")
|
|
316
|
+
|
|
317
|
+
# ---------------------------------------------------------
|
|
318
|
+
# BUFFER PRINT
|
|
319
|
+
# ---------------------------------------------------------
|
|
320
|
+
def bprint(self, text):
|
|
321
|
+
if self.buffer.enabled:
|
|
322
|
+
self.buffer.captured.append(str(text))
|
|
323
|
+
self.safePrint(str(text))
|
serverwatcher/validator.py
CHANGED
|
@@ -3,9 +3,9 @@ from dataclasses import fields
|
|
|
3
3
|
|
|
4
4
|
from hungerlib import utils, loadConfig, Validator
|
|
5
5
|
|
|
6
|
-
from
|
|
7
|
-
from
|
|
8
|
-
from
|
|
6
|
+
from .configclasses.config import GlobalConfig
|
|
7
|
+
from .configclasses.messages import MessagesConfig
|
|
8
|
+
from .configclasses.watcher import WatcherConfig
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
utils.clearTerminal()
|
|
@@ -18,6 +18,20 @@ def validate_global_config(c):
|
|
|
18
18
|
if not f.name.startswith('__'):
|
|
19
19
|
v.check_field(c, f.name)
|
|
20
20
|
|
|
21
|
+
# --- URL validation ---
|
|
22
|
+
if c.discord_enabled:
|
|
23
|
+
url = c.discord_url.strip()
|
|
24
|
+
|
|
25
|
+
if not url.startswith('https://'):
|
|
26
|
+
v.errors.append(f'discord_url: must start with https:// (got "{url}")')
|
|
27
|
+
|
|
28
|
+
# optional: detect example.com placeholder
|
|
29
|
+
if 'example.com' in url:
|
|
30
|
+
v.errors.append(f'discord_url: placeholder URL detected ("{url}")')
|
|
31
|
+
|
|
32
|
+
if c.discord_token == 'CHANGE_ME':
|
|
33
|
+
v.errors.append('discord_token: must be configured (got "CHANGE_ME")')
|
|
34
|
+
|
|
21
35
|
|
|
22
36
|
def validate_watcher_config(c):
|
|
23
37
|
for f in fields(WatcherConfig):
|
serverwatcher/watcher.py
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import os
|
|
2
1
|
import time
|
|
2
|
+
import traceback
|
|
3
3
|
from zoneinfo import ZoneInfo
|
|
4
4
|
|
|
5
|
-
from hungerlib import servers, MessageRouter, loadConfig, utils
|
|
5
|
+
from hungerlib import servers, MessageRouter, loadConfig, WebhookClient, utils
|
|
6
|
+
from hungerlib.configloader import deep_get
|
|
6
7
|
from mapres import MapResolver, maps
|
|
7
8
|
|
|
8
|
-
from
|
|
9
|
-
from
|
|
10
|
-
from
|
|
9
|
+
from .configclasses.config import GlobalConfig
|
|
10
|
+
from .configclasses.messages import MessagesConfig
|
|
11
|
+
from .configclasses.watcher import WatcherConfig
|
|
11
12
|
|
|
12
13
|
|
|
13
14
|
class ServerWatcher:
|
|
@@ -89,6 +90,9 @@ class ServerWatcher:
|
|
|
89
90
|
info_prefix=self.config.info_prefix,
|
|
90
91
|
warn_prefix=self.config.warn_prefix,
|
|
91
92
|
error_prefix=self.config.error_prefix,
|
|
93
|
+
|
|
94
|
+
buffer_enabled=True,
|
|
95
|
+
origin_output=True
|
|
92
96
|
)
|
|
93
97
|
|
|
94
98
|
self.router.registerLevel(
|
|
@@ -100,9 +104,23 @@ class ServerWatcher:
|
|
|
100
104
|
|
|
101
105
|
self.tz = ZoneInfo(self.config.timezone)
|
|
102
106
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
107
|
+
self.Webhook = WebhookClient(
|
|
108
|
+
url=self.config.discord_url,
|
|
109
|
+
token=self.config.discord_token
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
def webhookSend(self, event: str, **ctx):
|
|
113
|
+
if self.config.discord_enabled:
|
|
114
|
+
self.Webhook.send(event=event, **ctx)
|
|
115
|
+
|
|
116
|
+
def clearTerminal(self, conditional=True):
|
|
117
|
+
self.router.buffer.clear()
|
|
118
|
+
if conditional:
|
|
119
|
+
if self.config.clear_terminal and not self.router.buffer.enabled: # if clearing terminal is enabled and buffer is disabled
|
|
120
|
+
utils.clearTerminal()
|
|
121
|
+
else:
|
|
122
|
+
if not self.router.buffer.enabled: # if buffer disabled
|
|
123
|
+
utils.clearTerminal()
|
|
106
124
|
|
|
107
125
|
def shutdown(self):
|
|
108
126
|
self.router.info(self.messages.shutdown)
|
|
@@ -110,7 +128,10 @@ class ServerWatcher:
|
|
|
110
128
|
|
|
111
129
|
def restart_and_wait(self):
|
|
112
130
|
self.server.restart()
|
|
131
|
+
|
|
113
132
|
self.router.info(self.messages.restart_action_sent)
|
|
133
|
+
self.webhookSend(event='restart_action_sent', server=self.config.server_name)
|
|
134
|
+
|
|
114
135
|
time.sleep(self.watcherconfig.restart_wait_seconds)
|
|
115
136
|
|
|
116
137
|
self.router.warn(self.messages.status_check)
|
|
@@ -123,8 +144,10 @@ class ServerWatcher:
|
|
|
123
144
|
if alive:
|
|
124
145
|
self.router.info(self.messages.server_back_online)
|
|
125
146
|
self.router.destination(self.messages.server_back_online_log)
|
|
147
|
+
self.webhookSend(event='server_back_online', server=self.config.server_name)
|
|
126
148
|
else:
|
|
127
149
|
self.router.error(self.messages.server_failed_restart)
|
|
150
|
+
self.webhookSend(event='server_failed_restart', server=self.config.server_name)
|
|
128
151
|
|
|
129
152
|
def schedule_restart(self, minutes):
|
|
130
153
|
info = utils.snapSchedule(
|
|
@@ -137,6 +160,7 @@ class ServerWatcher:
|
|
|
137
160
|
time_str = local_time.strftime('%I:%M %p')
|
|
138
161
|
|
|
139
162
|
self.router.broadcast(self.messages.broadcast_restart_at, time=time_str)
|
|
163
|
+
self.webhookSend(event='restart_scheduled', server=self.config.server_name, time=time_str)
|
|
140
164
|
|
|
141
165
|
def plural(n):
|
|
142
166
|
return '' if n == 1 else 's'
|
|
@@ -176,8 +200,10 @@ class ServerWatcher:
|
|
|
176
200
|
)
|
|
177
201
|
|
|
178
202
|
def evaluate(self):
|
|
203
|
+
self.router.buffer.disable()
|
|
179
204
|
self.router.info('ServerWatcher is running!')
|
|
180
|
-
|
|
205
|
+
self.clearTerminal(conditional=False)
|
|
206
|
+
self.router.buffer.enable()
|
|
181
207
|
|
|
182
208
|
self.router.info(self.messages.startup)
|
|
183
209
|
|
|
@@ -185,9 +211,10 @@ class ServerWatcher:
|
|
|
185
211
|
for i in range(5):
|
|
186
212
|
if utils.validateAll(self.panel, self.server):
|
|
187
213
|
break
|
|
188
|
-
time.sleep(
|
|
214
|
+
time.sleep(5)
|
|
189
215
|
else:
|
|
190
216
|
self.router.error(self.messages.validation_fail)
|
|
217
|
+
self.webhookSend(event='validation_fail', server=self.config.server_name)
|
|
191
218
|
return
|
|
192
219
|
|
|
193
220
|
sample_duration_formatted = int(self.watcherconfig.sample_duration) if self.watcherconfig.sample_duration.is_integer() else self.watcherconfig.sample_duration
|
|
@@ -200,12 +227,19 @@ class ServerWatcher:
|
|
|
200
227
|
restart_reasons = []
|
|
201
228
|
no_restart_reasons = []
|
|
202
229
|
|
|
230
|
+
# NoneType error handling (for slower panels and apis)
|
|
231
|
+
resourcelist = [snap.ram, snap.cpu, snap.uptime, snap.tps, snap.players]
|
|
232
|
+
if any(item is None for item in resourcelist):
|
|
233
|
+
self.router.error(self.messages.sampling_fail)
|
|
234
|
+
self.webhookSend(event='sampling_fail', server=self.config.server_name)
|
|
235
|
+
return
|
|
236
|
+
|
|
203
237
|
if self.config.debug:
|
|
204
238
|
self.router.debug(f'RAM: {snap.ram}/{self.watcherconfig.threshold_ram}')
|
|
205
239
|
self.router.debug(f'CPU: {snap.cpu}/{self.watcherconfig.threshold_cpu}')
|
|
206
|
-
self.router.debug(f'Uptime: {snap.uptime // 3600}/{self.watcherconfig.threshold_uptime}')
|
|
240
|
+
self.router.debug(f'Uptime: {(snap.uptime // 1000) // 3600}/{self.watcherconfig.threshold_uptime}') # outputs raw ms, must convert to seconds first. this was changed in 6-dev.28
|
|
207
241
|
self.router.debug(f'TPS: {snap.tps}/{self.watcherconfig.threshold_tps}')
|
|
208
|
-
self.router.debug(f'Players: {snap.players}/{self.server.
|
|
242
|
+
self.router.debug(f'Players: {snap.players}/{self.server.getMaxPlayers()}')
|
|
209
243
|
|
|
210
244
|
if snap.ram >= self.watcherconfig.threshold_ram:
|
|
211
245
|
restart_reasons.append(self.res(self.messages.reason_ram, ram=snap.ram, threshold=self.watcherconfig.threshold_ram))
|
|
@@ -215,7 +249,7 @@ class ServerWatcher:
|
|
|
215
249
|
restart_reasons.append(self.res(self.messages.reason_cpu, cpu=snap.cpu, threshold=self.watcherconfig.threshold_cpu))
|
|
216
250
|
pro += self.watcherconfig.weight_cpu
|
|
217
251
|
|
|
218
|
-
if snap.uptime // 3600 >= self.watcherconfig.threshold_uptime:
|
|
252
|
+
if (snap.uptime // 1000) // 3600 >= self.watcherconfig.threshold_uptime: # outputs raw ms, must convert to seconds first. this was changed in 6-dev.28
|
|
219
253
|
restart_reasons.append(self.res(self.messages.reason_uptime, uptime=snap.uptime_formatted, threshold=self.watcherconfig.threshold_uptime))
|
|
220
254
|
pro += self.watcherconfig.weight_uptime
|
|
221
255
|
|
|
@@ -246,11 +280,10 @@ class ServerWatcher:
|
|
|
246
280
|
self.router.warn(f'{self.messages.pro_restart_number} {pro}')
|
|
247
281
|
self.router.warn(f'{self.messages.anti_restart_number} {anti}')
|
|
248
282
|
|
|
249
|
-
gap =
|
|
283
|
+
gap = pro - anti
|
|
250
284
|
|
|
251
285
|
if pro == 0:
|
|
252
286
|
self.router.info(self.messages.no_restart)
|
|
253
|
-
# will add something here later
|
|
254
287
|
return
|
|
255
288
|
|
|
256
289
|
if pro > anti and snap.players == 0:
|
|
@@ -270,20 +303,62 @@ class ServerWatcher:
|
|
|
270
303
|
self.restart_and_wait()
|
|
271
304
|
|
|
272
305
|
def run(self):
|
|
273
|
-
|
|
306
|
+
crash_times = [] # timestamps of recent crashes
|
|
307
|
+
|
|
308
|
+
while True:
|
|
274
309
|
try:
|
|
275
|
-
|
|
276
|
-
utils.clearTerminal()
|
|
277
|
-
self.evaluate()
|
|
278
|
-
if self.config.debug:
|
|
279
|
-
self.router.debug(f'Waiting {self.watcherconfig.watch_interval}s until next run...')
|
|
280
|
-
time.sleep(self.watcherconfig.watch_interval)
|
|
281
|
-
except KeyboardInterrupt:
|
|
282
|
-
self.shutdown()
|
|
283
|
-
else:
|
|
284
|
-
while True:
|
|
285
|
-
utils.clearTerminal()
|
|
310
|
+
self.clearTerminal()
|
|
286
311
|
self.evaluate()
|
|
312
|
+
|
|
287
313
|
if self.config.debug:
|
|
288
314
|
self.router.debug(f'Waiting {self.watcherconfig.watch_interval}s until next run...')
|
|
315
|
+
|
|
289
316
|
time.sleep(self.watcherconfig.watch_interval)
|
|
317
|
+
|
|
318
|
+
except KeyboardInterrupt:
|
|
319
|
+
if self.config.handle_keyboard_interrupt:
|
|
320
|
+
self.shutdown()
|
|
321
|
+
else:
|
|
322
|
+
raise
|
|
323
|
+
|
|
324
|
+
except Exception as e:
|
|
325
|
+
now = time.time()
|
|
326
|
+
crash_times.append(now)
|
|
327
|
+
|
|
328
|
+
# keep only crashes in last 60 seconds
|
|
329
|
+
crash_times = [t for t in crash_times if now - t <= 60]
|
|
330
|
+
|
|
331
|
+
# format traceback
|
|
332
|
+
tb = ''.join(traceback.format_exception(type(e), e, e.__traceback__))
|
|
333
|
+
|
|
334
|
+
# log locally
|
|
335
|
+
try:
|
|
336
|
+
with open('watcher_errors.log', 'a') as f:
|
|
337
|
+
f.write('\n\n=== Unexpected Error ===\n')
|
|
338
|
+
f.write(tb)
|
|
339
|
+
except Exception:
|
|
340
|
+
pass
|
|
341
|
+
|
|
342
|
+
# router log
|
|
343
|
+
self.router.error('Unexpected error in watcher loop:')
|
|
344
|
+
self.router.error(tb)
|
|
345
|
+
|
|
346
|
+
# webhook spam protection
|
|
347
|
+
if len(crash_times) <= 3:
|
|
348
|
+
try:
|
|
349
|
+
self.webhookSend(
|
|
350
|
+
event='unexpected_error',
|
|
351
|
+
server=self.config.server_name,
|
|
352
|
+
error=tb[:1800]
|
|
353
|
+
)
|
|
354
|
+
except Exception:
|
|
355
|
+
self.router.warn('Failed to send Discord webhook for unexpected error.')
|
|
356
|
+
else:
|
|
357
|
+
self.router.warn('Error rate high — suppressing webhook spam.')
|
|
358
|
+
|
|
359
|
+
# exponential backoff
|
|
360
|
+
backoff = min(2 ** len(crash_times), self.watcherconfig.watch_interval)
|
|
361
|
+
self.router.warn(f'Backing off for {backoff}s due to repeated errors.')
|
|
362
|
+
time.sleep(backoff)
|
|
363
|
+
|
|
364
|
+
continue
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
from hungerlib import utils
|
|
2
|
+
from mapres import res, ascii_colors, setGlobalMaps
|
|
3
|
+
from .watcher import ServerWatcher
|
|
4
|
+
from c2e import LiveCLI, command
|
|
5
|
+
|
|
6
|
+
setGlobalMaps(ascii_colors)
|
|
7
|
+
|
|
8
|
+
class BufferingStdout:
|
|
9
|
+
def __init__(self, buffer, real_stdout):
|
|
10
|
+
self.buffer = buffer
|
|
11
|
+
self.real_stdout = real_stdout
|
|
12
|
+
def write(self, text):
|
|
13
|
+
if self.buffer.enabled and text.strip():
|
|
14
|
+
self.buffer.captured.append(text.rstrip('\n'))
|
|
15
|
+
self.real_stdout.write(text)
|
|
16
|
+
def flush(self):
|
|
17
|
+
self.real_stdout.flush()
|
|
18
|
+
|
|
19
|
+
class WatcherCLI(LiveCLI):
|
|
20
|
+
def __init__(self, watcher: ServerWatcher):
|
|
21
|
+
super().__init__()
|
|
22
|
+
self.watcher = watcher
|
|
23
|
+
self.buffer = utils.Buffer(enabled=True)
|
|
24
|
+
self.outputMode = 'both'
|
|
25
|
+
def printHeader(self):
|
|
26
|
+
self.safePrint(res('<yellow>-----------------------------------'), write_buffer=False)
|
|
27
|
+
self.safePrint(res('<yellow>-------- <aqua>ServerWatcher CLI <yellow>--------'), write_buffer=False)
|
|
28
|
+
self.safePrint(res('<yellow>-----------------------------------'), write_buffer=False)
|
|
29
|
+
self.safePrint('', write_buffer=False)
|
|
30
|
+
|
|
31
|
+
@command('stats')
|
|
32
|
+
def stats(self, arg=None):
|
|
33
|
+
'''Retrieve and print all or specific server statistics'''
|
|
34
|
+
__args__ = '''
|
|
35
|
+
ram: rounding, --raw
|
|
36
|
+
cpu: rounding
|
|
37
|
+
uptime: rounding, mode
|
|
38
|
+
players
|
|
39
|
+
version
|
|
40
|
+
platform
|
|
41
|
+
'''
|
|
42
|
+
self.watcher.server.refresh()
|
|
43
|
+
if arg is None:
|
|
44
|
+
self.safePrint(
|
|
45
|
+
f'''
|
|
46
|
+
RAM: {self.watcher.server.getRAM(gb=True)} GiB
|
|
47
|
+
CPU: {self.watcher.server.getCPU()}%
|
|
48
|
+
Uptime: {self.watcher.server.getUptime(formatted=True)}
|
|
49
|
+
TPS: {self.watcher.server.getTPS()}
|
|
50
|
+
Players: {self.watcher.server.getPlayers()}
|
|
51
|
+
Version: {self.watcher.server.getVersion()}
|
|
52
|
+
Platform: {self.watcher.server.getPlatform()}
|
|
53
|
+
Bridge: {self.watcher.server.getBridgeVersion()}
|
|
54
|
+
'''
|
|
55
|
+
)
|
|
56
|
+
gb = not raw()
|
|
57
|
+
fmt = not raw()
|
|
58
|
+
unit = ''
|
|
59
|
+
match arg:
|
|
60
|
+
case 'ram':
|
|
61
|
+
value = self.watcher.server.getRAM(rounding=rounding(), gb=gb)
|
|
62
|
+
name = 'RAM'
|
|
63
|
+
unit = ' GiB' if gb else ' MiB'
|
|
64
|
+
case 'cpu':
|
|
65
|
+
value = self.watcher.server.getCPU(rounding=rounding())
|
|
66
|
+
name = 'CPU'
|
|
67
|
+
unit = '%'
|
|
68
|
+
case 'uptime':
|
|
69
|
+
value = self.watcher.server.getUptime(formatted=fmt)
|
|
70
|
+
name = 'Uptime'
|
|
71
|
+
unit = '' if fmt else 'ms'
|
|
72
|
+
case 'tps':
|
|
73
|
+
value = self.watcher.server.getTPS(rounding=rounding(), mode=mode())
|
|
74
|
+
name = 'TPS'
|
|
75
|
+
case 'players':
|
|
76
|
+
value = self.watcher.server.getPlayers()
|
|
77
|
+
name = 'Players'
|
|
78
|
+
case 'version':
|
|
79
|
+
value = self.watcher.server.getVersion()
|
|
80
|
+
name = 'Minecraft version'
|
|
81
|
+
case 'platform':
|
|
82
|
+
value = self.watcher.server.getPlatform()
|
|
83
|
+
name = 'Server platform'
|
|
84
|
+
case 'bridge':
|
|
85
|
+
value = self.watcher.server.getBridgeVersion()
|
|
86
|
+
name = 'Bridge version'
|
|
87
|
+
case _:
|
|
88
|
+
return self.safePrint('Unknown stat')
|
|
89
|
+
self.safePrint(f'{name}: {value}{unit}')
|
|
90
|
+
|
|
91
|
+
@stats.param('rounding', type=int, default=2)
|
|
92
|
+
def rounding(value):
|
|
93
|
+
'''The decimal place to round to'''
|
|
94
|
+
return value
|
|
95
|
+
|
|
96
|
+
@stats.param('mode', type=str, default='current')
|
|
97
|
+
def mode(value):
|
|
98
|
+
'''The mode for TPS. Accepted: current, 1m, 5m, tick_time'''
|
|
99
|
+
return value
|
|
100
|
+
|
|
101
|
+
@stats.flag('raw')
|
|
102
|
+
def raw():
|
|
103
|
+
'''Return the raw value instead of the formatted string'''
|
|
104
|
+
return True
|
|
105
|
+
|
|
106
|
+
@command('view', namespace=True)
|
|
107
|
+
def view(self):
|
|
108
|
+
'''Switch terminal view'''
|
|
109
|
+
pass
|
|
110
|
+
|
|
111
|
+
@view.child('cli')
|
|
112
|
+
def view_cli(self):
|
|
113
|
+
'''Switch to CLI view'''
|
|
114
|
+
self.watcher.router.disableOriginOutput()
|
|
115
|
+
self.outputMode = 'cli'
|
|
116
|
+
self.buffer.enabled = True
|
|
117
|
+
utils.clearTerminal()
|
|
118
|
+
self.safePrint('', end='')
|
|
119
|
+
self.printHeader()
|
|
120
|
+
for msg in self.buffer.captured:
|
|
121
|
+
self.safePrint(msg, write_buffer=False)
|
|
122
|
+
|
|
123
|
+
@view.child('watcher')
|
|
124
|
+
def view_watcher(self):
|
|
125
|
+
'''Switch to Watcher view'''
|
|
126
|
+
self.watcher.router.enableOriginOutput()
|
|
127
|
+
self.outputMode = 'both'
|
|
128
|
+
utils.clearTerminal()
|
|
129
|
+
self.safePrint('', end='')
|
|
130
|
+
for msg in self.watcher.router.buffer.captured:
|
|
131
|
+
self.safePrint(msg, write_buffer=False)
|
|
132
|
+
|
|
133
|
+
@command('clear')
|
|
134
|
+
def clear(self):
|
|
135
|
+
'''Clear the CLI terminal'''
|
|
136
|
+
if not no_buffer():
|
|
137
|
+
self.buffer.clear()
|
|
138
|
+
utils.clearTerminal()
|
|
139
|
+
self.printHeader()
|
|
140
|
+
|
|
141
|
+
@clear.flag('no-buffer')
|
|
142
|
+
def no_buffer():
|
|
143
|
+
'''Do not clear buffer'''
|
|
144
|
+
return True
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: serverwatcher
|
|
3
|
+
Version: 6a2
|
|
4
|
+
Summary: A HungerLib-powered Minecraft server automation engine.
|
|
5
|
+
Author: iFamished
|
|
6
|
+
License: GPL-3.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/iFamished/ServerWatcher
|
|
8
|
+
Project-URL: Documentation, https://github.com/iFamished/ServerWatcher
|
|
9
|
+
Project-URL: Source, https://github.com/iFamished/ServerWatcher
|
|
10
|
+
Project-URL: Issues, https://github.com/iFamished/ServerWatcher/issues
|
|
11
|
+
Keywords: pterodactyl,minecraft,automation,server-management,hungerlib,hungernet
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Development Status :: 4 - Beta
|
|
19
|
+
Classifier: Intended Audience :: Developers
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
21
|
+
Classifier: Topic :: System :: Systems Administration
|
|
22
|
+
Requires-Python: >=3.14
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: hungerlib>=3.1
|
|
26
|
+
Requires-Dist: mapres
|
|
27
|
+
Requires-Dist: C2E
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# ServerWatcher
|
|
31
|
+
A highly configurable Minecraft server monitoring and restart engine for HungerBridge / Pterodactyl-based Minecraft servers.
|
|
32
|
+
|
|
33
|
+
## System requirements
|
|
34
|
+
| | **Minimum** | **Recommended** |
|
|
35
|
+
| ----------- | ----------- | --------------- |
|
|
36
|
+
| **RAM** | 128 MB | 256 MB |
|
|
37
|
+
| **Storage** | 256 MB | 1 GB |
|
|
38
|
+
|
|
39
|
+
## Prerequisites
|
|
40
|
+
**Pterodactyl Panel / API credentials**
|
|
41
|
+
- You must have the server on a Pterodactyl Panel
|
|
42
|
+
- You need a valid client API token
|
|
43
|
+
**HungerBridge**
|
|
44
|
+
- Install [HungerBridge from Modrinth](https://modrinth.com/project/hungerbridge) on the Minecraft server you wish to monitor
|
|
45
|
+
- HungerBridge supports `Fabric`, `Quilt`, `Paper`, `Purpur`, and `Folia`
|
|
46
|
+
**A dedicated Python environment**
|
|
47
|
+
- ServerWatcher requires a Python 3.14+ environment to run
|
|
48
|
+
*Discord bot*
|
|
49
|
+
- Optional. The bot must have the correct endpoints set up.
|
|
50
|
+
*Logging directory*
|
|
51
|
+
- Optional. Only necessary if you want to use file logging.
|
|
52
|
+
|
|
53
|
+
## Installation
|
|
54
|
+
- Download the [**ServerWatcher Pterodactyl egg**](https://github.com/iFamished/ServerWatcher/blob/main/eggs/serverwatcher.json)
|
|
55
|
+
- Import it into your desired nest in your panel
|
|
56
|
+
- Create a server with the egg selected
|
|
57
|
+
- Start the server and wait for instalation and file generation to finish
|
|
58
|
+
- Configure the files in config/
|
|
59
|
+
- Start the server again
|
|
60
|
+
- You're done! Just let it do its thing.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
serverwatcher/__init__.py,sha256=Q_afN0XU29n48d6Gf0-LT2lLo3RiTWlHRT6rC_fYbjw,486
|
|
2
|
+
serverwatcher/__main__.py,sha256=5geaZQKgLSP1pxnpQPgFy9zAwyyPyTInlbcFxb9OiEw,3016
|
|
3
|
+
serverwatcher/validator.py,sha256=nWaMbicYifU25EA8apLnBtVX4aUWhWp-HZhMaBbz4ME,1739
|
|
4
|
+
serverwatcher/watcher.py,sha256=gzSX2nGpAGzHUsOtejLBzPLsMlKVLJzuN1KWpN8DB3o,13734
|
|
5
|
+
serverwatcher/watchercli.py,sha256=t5h5wOjr6PM0ZoxEXEJwcrinpWXQuh8wq3tP9c5BFZ0,4549
|
|
6
|
+
serverwatcher/configclasses/__init__.py,sha256=YS0KhxtAJGdMcaiFstqTRNxIPLnR7s9v3Tkt5h2uKE4,182
|
|
7
|
+
serverwatcher/configclasses/config.py,sha256=1Upor55QFE4UIOqL9ZYa4U5kbda48GG9HWdRXg8mb_Y,2418
|
|
8
|
+
serverwatcher/configclasses/messages.py,sha256=iOkCvwagngW4aeWD5I6hi6cqqDkzEsFJsLHSuqK-P1s,3467
|
|
9
|
+
serverwatcher/configclasses/watcher.py,sha256=OIAYQZF9hD9e5FbcaYV5N9CAdCZoLgXSqAMh_MOayaw,2727
|
|
10
|
+
serverwatcher/defaultconfigs/config.yaml,sha256=yrJ59Jx0F4TJzE1EdBF5IKPCDqs09XcbKHFfkYGJ1ys,721
|
|
11
|
+
serverwatcher/defaultconfigs/messages.yaml,sha256=jSVEl-RYqPHhe5U5KLl8zfJtUBymvyE74hmzH0RFC_Y,3177
|
|
12
|
+
serverwatcher/defaultconfigs/watcher.yaml,sha256=GlAEKCuzFUSF6wWOqQLFL1CeuPltb1ltfYxFe_FUClw,723
|
|
13
|
+
serverwatcher/tests/test.py,sha256=CqGBdfktVIyXz6wMoa6TBbEPlPvp_lA_VSzBuxwxrfs,2551
|
|
14
|
+
serverwatcher/tests/test2.py,sha256=DcvYiidXTe3SSOpiSPQ585YBN4PXrDMs0a3ZW_TbBsg,9564
|
|
15
|
+
serverwatcher-6a2.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
|
|
16
|
+
serverwatcher-6a2.dist-info/METADATA,sha256=Yb9FO5PLBtI7Y8_ib6GWkf9zfCH1sV0PcJg2x3dd0wQ,2584
|
|
17
|
+
serverwatcher-6a2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
18
|
+
serverwatcher-6a2.dist-info/top_level.txt,sha256=8DJAf8WmmglgtZHkp8aoTriRJ2YPcS4F3DfOIkytASo,14
|
|
19
|
+
serverwatcher-6a2.dist-info/RECORD,,
|
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: serverwatcher
|
|
3
|
-
Version: 5.33.dev4
|
|
4
|
-
Summary: A HungerLib-powered Minecraft server automation engine.
|
|
5
|
-
Author: iFamished
|
|
6
|
-
License: GPL-3.0
|
|
7
|
-
Project-URL: Homepage, https://github.com/iFamishedX/ServerWatcher
|
|
8
|
-
Project-URL: Documentation, https://github.com/iFamishedX/ServerWatcher
|
|
9
|
-
Project-URL: Source, https://github.com/iFamishedX/ServerWatcher
|
|
10
|
-
Project-URL: Issues, https://github.com/iFamishedX/ServerWatcher/issues
|
|
11
|
-
Keywords: pterodactyl,minecraft,automation,rcon,server-management,hungerlib,hungernet
|
|
12
|
-
Classifier: Programming Language :: Python :: 3
|
|
13
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
-
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
-
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
-
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
|
17
|
-
Classifier: Operating System :: OS Independent
|
|
18
|
-
Classifier: Development Status :: 4 - Beta
|
|
19
|
-
Classifier: Intended Audience :: Developers
|
|
20
|
-
Classifier: Topic :: Software Development :: Libraries
|
|
21
|
-
Classifier: Topic :: System :: Systems Administration
|
|
22
|
-
Requires-Python: >=3.14
|
|
23
|
-
Description-Content-Type: text/markdown
|
|
24
|
-
License-File: LICENSE
|
|
25
|
-
Requires-Dist: requests
|
|
26
|
-
Requires-Dist: mcrcon
|
|
27
|
-
Requires-Dist: hungerlib>=3.1
|
|
28
|
-
Requires-Dist: PyYaml
|
|
29
|
-
Requires-Dist: mapres
|
|
30
|
-
Dynamic: license-file
|
|
31
|
-
|
|
32
|
-
# ServerWatcher
|
|
33
|
-
|
|
34
|
-
A configurable server monitoring and restart engine for HungerLib / Pterodactyl-based Minecraft servers.
|
|
35
|
-
|
|
36
|
-
## Usage
|
|
37
|
-
```bash
|
|
38
|
-
pip install serverwatcher
|
|
39
|
-
```
|
|
40
|
-
```python
|
|
41
|
-
from serverwatcher.watcher import ServerWatcher
|
|
42
|
-
from serverwatcher.config import WatcherConfig
|
|
43
|
-
from serverwatcher.messages import WatcherMessages
|
|
44
|
-
|
|
45
|
-
watcher = ServerWatcher(server, origin, panel, logger, WatcherConfig(), WatcherMessages())
|
|
46
|
-
watcher.evaluate()
|
|
47
|
-
```
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
serverwatcher/__init__.py,sha256=Q_afN0XU29n48d6Gf0-LT2lLo3RiTWlHRT6rC_fYbjw,486
|
|
2
|
-
serverwatcher/__main__.py,sha256=XBz1dYfQSN5FRah7xfQaJ82b-dc0qoscVHYs5Snma_c,991
|
|
3
|
-
serverwatcher/validator.py,sha256=fgItW9NPYxFPseQIK_d_iNBdxwST2Gw8i4wOlBKls98,1258
|
|
4
|
-
serverwatcher/watcher.py,sha256=vW6YdT4srtQetqeLFEPuehUgOi4wzDLwhbL2ggimTjg,10628
|
|
5
|
-
serverwatcher/configclasses/__init__.py,sha256=YS0KhxtAJGdMcaiFstqTRNxIPLnR7s9v3Tkt5h2uKE4,182
|
|
6
|
-
serverwatcher/configclasses/config.py,sha256=2iQslC6z8_c7UBDe8EzbtFI_-w5tQRKlOuWyARWPyLw,2134
|
|
7
|
-
serverwatcher/configclasses/messages.py,sha256=8SqAhHrnByz0IxCfkbp2_Bd5ha9yUzKfNwD_R1SEYbs,3482
|
|
8
|
-
serverwatcher/configclasses/watcher.py,sha256=wBBAP3nQJ4FTqRxafIr1JRUEtzqAWUBLx1nVT8FGur4,2720
|
|
9
|
-
serverwatcher/defaultconfigs/config.yaml,sha256=tNywPeyqYh9xGpSkxdeYv_T9EBuyvSJKaQhmOSnNFy0,637
|
|
10
|
-
serverwatcher/defaultconfigs/messages.yaml,sha256=IX27K9qSIsGQkyL9aULRP_zq1xMwTQSNtO-Xoxg0IrU,3113
|
|
11
|
-
serverwatcher/defaultconfigs/watcher.yaml,sha256=GlAEKCuzFUSF6wWOqQLFL1CeuPltb1ltfYxFe_FUClw,723
|
|
12
|
-
serverwatcher-5.33.dev4.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
|
|
13
|
-
serverwatcher-5.33.dev4.dist-info/METADATA,sha256=E2h_6OscB5yM6oW5iO2dbzb-Bg24zwa9adMP2CpyvRQ,1714
|
|
14
|
-
serverwatcher-5.33.dev4.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
15
|
-
serverwatcher-5.33.dev4.dist-info/top_level.txt,sha256=8DJAf8WmmglgtZHkp8aoTriRJ2YPcS4F3DfOIkytASo,14
|
|
16
|
-
serverwatcher-5.33.dev4.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|