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.
serverwatcher/watcher.py CHANGED
@@ -1,364 +1,150 @@
1
1
  import time
2
- import traceback
3
- from zoneinfo import ZoneInfo
2
+ from hungerlib import WebhookClient, utils
4
3
 
5
- from hungerlib import servers, MessageRouter, loadConfig, WebhookClient, utils
6
- from hungerlib.configloader import deep_get
7
- from mapres import MapResolver, maps
8
-
9
- from .configclasses.config import GlobalConfig
10
- from .configclasses.messages import MessagesConfig
11
- from .configclasses.watcher import WatcherConfig
4
+ from .configmanager import config_manager
5
+ from .targetserver import TargetServer
6
+ from .router import Router
7
+ from .metricfetcher import MetricFetcher
8
+ from .evaluator import Evaluator
9
+ from .actionperformer import ActionPerformer
12
10
 
13
11
 
14
12
  class ServerWatcher:
15
- def __init__(self):
16
- self.config = loadConfig(GlobalConfig)
17
- self.messages = loadConfig(MessagesConfig)
18
- self.watcherconfig = loadConfig(WatcherConfig)
19
-
20
- # resolver for internal mapping
21
- self.resolver = MapResolver()
22
- self.res = self.resolver.res
23
-
24
- # panel + server
25
- self.panel = servers.Panel(
26
- name=self.config.panel_name,
27
- url=self.config.panel_url,
28
- api_key=self.config.panel_api_key,
29
- )
30
-
31
- self.server = servers.Minecraft(
32
- name=self.config.server_name,
33
- panel=self.panel,
34
- server_id=self.config.server_id,
35
- server_domain=self.config.server_domain,
36
- server_port=self.config.server_port,
37
- bridge_url=self.config.bridge_url,
38
- bridge_token=self.config.bridge_token,
13
+ def __init__(self, bridge_start_handler=None, bridge_restart_handler=None, bridge_kill_handler=None):
14
+ self.config_manager = config_manager
15
+ self.config = self.config_manager.config
16
+ self.discordcfg = self.config_manager.discordcfg
17
+ self.env = self.config_manager.env
18
+ self.watchercfg = self.config_manager.watchercfg
19
+ self.evaluatorcfg = self.config_manager.evaluatorcfg
20
+
21
+ self.target = TargetServer(
22
+ bridge_start_handler=bridge_start_handler,
23
+ bridge_restart_handler=bridge_restart_handler,
24
+ bridge_kill_handler=bridge_kill_handler
39
25
  )
40
26
 
41
- # logger name
42
- logger_name = self.res(
43
- self.config.logger_name,
44
- server_name=self.config.server_name
45
- )
46
-
47
- # router using mapres
48
- self.router = MessageRouter(
49
- name=logger_name,
50
- Servers=[self.server],
51
- log_path=self.config.log_path,
52
-
53
- origin_maps=[
54
- maps.ascii_colors,
55
- maps.time(self.config.timezone),
56
- self.config,
57
- self.messages,
58
- self.watcherconfig,
59
- ],
60
-
61
- destination_maps=[
62
- maps.ascii_colors,
63
- maps.time(self.config.timezone),
64
- self.config,
65
- self.messages,
66
- self.watcherconfig,
67
- ],
27
+ self.r = Router(self.target)
68
28
 
69
- broadcast_maps=[
70
- maps.mc_colors,
71
- maps.time(self.config.timezone),
72
- self.config,
73
- self.messages,
74
- self.watcherconfig,
75
- ],
76
-
77
- file_maps=[
78
- maps.strip_colors,
79
- maps.time(self.config.timezone),
80
- self.config,
81
- self.messages,
82
- self.watcherconfig,
83
- ],
84
-
85
- prefix_maps=[
86
- maps.ascii_colors,
87
- maps.time(self.config.timezone),
88
- ],
89
-
90
- info_prefix=self.config.info_prefix,
91
- warn_prefix=self.config.warn_prefix,
92
- error_prefix=self.config.error_prefix,
93
-
94
- buffer_enabled=True,
95
- origin_output=True
29
+ self.webhook = WebhookClient(
30
+ url=self.discordcfg.discord_url,
31
+ token=self.discordcfg.discord_token
96
32
  )
97
33
 
98
- self.router.registerLevel(
99
- name='debug',
100
- prefix=self.config.debug_prefix,
101
- file_method='debug',
102
- routes=['origin']
34
+ self.fetcher = MetricFetcher(self.target)
35
+ self.evaluator = Evaluator(self.evaluatorcfg)
36
+ self.action = ActionPerformer(
37
+ server=self.target,
38
+ router=self.r,
39
+ webhook=self.webhook,
40
+ config=self.watchercfg
103
41
  )
104
-
105
- self.tz = ZoneInfo(self.config.timezone)
106
-
107
- self.Webhook = WebhookClient(
108
- url=self.config.discord_url,
109
- token=self.config.discord_token
110
- )
111
-
42
+
112
43
  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()
44
+ if self.discordcfg.discord_enabled:
45
+ self.webhook.send(event=event, **ctx)
124
46
 
125
47
  def shutdown(self):
126
- self.router.info(self.messages.shutdown)
48
+ self.r.info('Shutting down ServerWatcher.')
127
49
  raise SystemExit
128
50
 
129
- def restart_and_wait(self):
130
- self.server.restart()
131
-
132
- self.router.info(self.messages.restart_action_sent)
133
- self.webhookSend(event='restart_action_sent', server=self.config.server_name)
134
-
135
- time.sleep(self.watcherconfig.restart_wait_seconds)
136
-
137
- self.router.warn(self.messages.status_check)
138
- alive = utils.waitForOnline(
139
- self.server,
140
- timeout=self.watcherconfig.restart_timeout,
141
- interval=self.watcherconfig.restart_online_interval,
142
- )
143
-
144
- if alive:
145
- self.router.info(self.messages.server_back_online)
146
- self.router.destination(self.messages.server_back_online_log)
147
- self.webhookSend(event='server_back_online', server=self.config.server_name)
148
- else:
149
- self.router.error(self.messages.server_failed_restart)
150
- self.webhookSend(event='server_failed_restart', server=self.config.server_name)
151
-
152
- def schedule_restart(self, minutes):
153
- info = utils.snapSchedule(
154
- minimumMinutes=minutes,
155
- snapMinutes=tuple(sorted(self.watcherconfig.snap_minutes))
156
- )
157
- scheduled = info['scheduled']
158
-
159
- local_time = scheduled.astimezone(self.tz)
160
- time_str = local_time.strftime('%I:%M %p')
161
-
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)
164
-
165
- def plural(n):
166
- return '' if n == 1 else 's'
167
-
168
- # minute message generator
169
- def minute_msg(n):
170
- raw = self.messages.minute_template
171
- return self.res(raw, n=n, s=plural(n), prefix=self.messages.prefix)
172
-
173
- # second message generator
174
- def second_msg(n):
175
- raw = self.messages.second_template
176
- return self.res(raw, n=n, s=plural(n), prefix=self.messages.prefix)
177
-
178
- # minute callbacks using template
179
- minute_callbacks = {
180
- n: (lambda n=n: (
181
- self.router.broadcast(minute_msg(n + 1)),
182
- self.router.origin(minute_msg(n + 1))
183
- ))
184
- for n in self.watcherconfig.snap_minutes
185
- }
186
-
187
- # second callbacks using template
188
- second_callbacks = {
189
- n: (lambda n=n: (
190
- self.router.broadcast(second_msg(n)),
191
- self.router.origin(second_msg(n))
192
- ))
193
- for n in range(1, 11)
194
- }
195
-
196
- utils.runCountdownEvents(
197
- target_time=scheduled,
198
- minute_callbacks=minute_callbacks,
199
- second_callbacks=second_callbacks
200
- )
201
-
202
- def evaluate(self):
203
- self.router.buffer.disable()
204
- self.router.info('ServerWatcher is running!')
205
- self.clearTerminal(conditional=False)
206
- self.router.buffer.enable()
207
-
208
- self.router.info(self.messages.startup)
209
-
210
- # retry validation 5 times
51
+ def startupMessages(self):
52
+ if self.env.ptero_enabled:
53
+ self.r.info('ServerWatcher is running!')
54
+ utils.clearTerminal()
55
+ self.r.info('ServerWatcher is starting...')
56
+ self.r.debug(f"Environment: {'Pterodactyl' if self.env.ptero_enabled else 'Standalone'}")
57
+
58
+ def configExistenceCheck(self):
59
+ self.r.debug('Checking existence of configuration files...')
60
+ if not self.config_manager.checkAllExistence():
61
+ self.r.error('Some configuration files are missing. Generating default configs...')
62
+ self.config_manager.generateAllConfigs(overwrite=False)
63
+ self.r.info('Default configuration files have been generated.')
64
+ self.r.warn('Please review and edit the configuration files as needed, then restart the application.')
65
+ self.shutdown()
66
+ self.r.debug('Configs exist!')
67
+
68
+ def configValidation(self):
69
+ self.r.debug('Validating configuration files...')
70
+ self.config_manager.validateAll()
71
+
72
+ def checkReachability(self):
73
+ if self.env.ptero_enabled:
74
+ self.r.info('Checking Pterodactyl reachability...')
75
+ for i in range(5):
76
+ if self.target.checkPtero():
77
+ self.r.info('Pterodactyl reachable!')
78
+ break
79
+ time.sleep(5)
80
+ else:
81
+ self.r.fatal('Pterodactyl is not reachable or the API key is invalid!')
82
+ self.webhookSend(event='validation_fail', server=self.config.server_name)
83
+ return
84
+
85
+ self.r.info('Checking HungerBridge reachability...')
211
86
  for i in range(5):
212
- if utils.validateAll(self.panel, self.server):
87
+ if self.target.checkBridge():
88
+ self.r.info('HungerBridge reachable!')
213
89
  break
214
90
  time.sleep(5)
215
91
  else:
216
- self.router.error(self.messages.validation_fail)
217
- self.webhookSend(event='validation_fail', server=self.config.server_name)
218
- return
219
-
220
- sample_duration_formatted = int(self.watcherconfig.sample_duration) if self.watcherconfig.sample_duration.is_integer() else self.watcherconfig.sample_duration
221
- self.router.info(self.messages.sampling_start, duration=sample_duration_formatted)
222
- self.server.refresh()
223
- snap = utils.Snapshot(self.server, duration=self.watcherconfig.sample_duration, interval=self.watcherconfig.sample_interval, drop_outliers=self.watcherconfig.sample_outlier_drop, gb=True)
224
-
225
- pro = 0
226
- anti = 0
227
- restart_reasons = []
228
- no_restart_reasons = []
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
-
237
- if self.config.debug:
238
- self.router.debug(f'RAM: {snap.ram}/{self.watcherconfig.threshold_ram}')
239
- self.router.debug(f'CPU: {snap.cpu}/{self.watcherconfig.threshold_cpu}')
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
241
- self.router.debug(f'TPS: {snap.tps}/{self.watcherconfig.threshold_tps}')
242
- self.router.debug(f'Players: {snap.players}/{self.server.max_players}')
243
-
244
- if snap.ram >= self.watcherconfig.threshold_ram:
245
- restart_reasons.append(self.res(self.messages.reason_ram, ram=snap.ram, threshold=self.watcherconfig.threshold_ram))
246
- pro += int(round(snap.ram, 0) - (self.watcherconfig.threshold_ram - 1))
247
-
248
- if snap.cpu >= self.watcherconfig.threshold_cpu:
249
- restart_reasons.append(self.res(self.messages.reason_cpu, cpu=snap.cpu, threshold=self.watcherconfig.threshold_cpu))
250
- pro += self.watcherconfig.weight_cpu
251
-
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
253
- restart_reasons.append(self.res(self.messages.reason_uptime, uptime=snap.uptime_formatted, threshold=self.watcherconfig.threshold_uptime))
254
- pro += self.watcherconfig.weight_uptime
255
-
256
- if (snap.tps if snap.tps is not None else 20) <= self.watcherconfig.threshold_tps:
257
- restart_reasons.append(self.res(self.messages.reason_tps, tps=snap.tps, threshold=self.watcherconfig.threshold_tps))
258
- pro += self.watcherconfig.weight_tps
259
-
260
- if snap.uptime // 60 < self.watcherconfig.threshold_min_uptime:
261
- no_restart_reasons.append(self.res(self.messages.reason_low_uptime, uptime=snap.uptime_formatted))
262
- anti += self.watcherconfig.weight_low_uptime
263
-
264
- if snap.players > 0:
265
- verb = 'are' if snap.players != 1 else 'is'
266
- plural = 'players' if snap.players != 1 else 'player'
267
- no_restart_reasons.append(self.res(self.messages.reason_players, verb=verb, count=snap.players, plural=plural))
268
- anti += snap.players * self.watcherconfig.weight_per_player
269
-
270
- if restart_reasons:
271
- self.router.warn(self.messages.pro_restart_splash)
272
- for r in restart_reasons:
273
- self.router.warn(f'{self.messages.bullet} {r}')
274
-
275
- if no_restart_reasons:
276
- self.router.warn(self.messages.anti_restart_splash)
277
- for r in no_restart_reasons:
278
- self.router.warn(f'{self.messages.bullet} {r}')
279
-
280
- self.router.warn(f'{self.messages.pro_restart_number} {pro}')
281
- self.router.warn(f'{self.messages.anti_restart_number} {anti}')
282
-
283
- gap = pro - anti
284
-
285
- if pro == 0:
286
- self.router.info(self.messages.no_restart)
287
- return
288
-
289
- if pro > anti and snap.players == 0:
290
- self.router.info(self.messages.immediate_restart)
291
- self.restart_and_wait()
292
- return
293
-
294
- self.router.info(self.messages.scheduled)
295
-
296
- if gap <= self.watcherconfig.threshold_low_gap:
297
- self.router.warn(self.messages.gap_low, gap=gap)
298
- self.schedule_restart(self.watcherconfig.low_gap_minutes)
299
- else:
300
- self.router.warn(self.messages.gap_high, gap=gap)
301
- self.schedule_restart(self.watcherconfig.high_gap_minutes)
92
+ self.r.fatal('HungerBridge is not reachable or the token secret/id is invalid!')
93
+
94
+ def decideAction(self, result, metrics):
95
+ score = result['score']
96
+ uptime = metrics['uptime']
97
+ players = metrics['players']
98
+
99
+ if score == 0:
100
+ return 'none', None
101
+
102
+ if uptime < self.evaluatorcfg.threshold_min_uptime:
103
+ return 'none', None
104
+
105
+ if players == 0:
106
+ return 'restart_now', None
107
+
108
+ gap = score
109
+ minutes = (
110
+ self.watchercfg.low_gap_minutes
111
+ if gap <= self.watchercfg.threshold_low_gap
112
+ else self.watchercfg.high_gap_minutes
113
+ )
302
114
 
303
- self.restart_and_wait()
115
+ return 'schedule_restart', minutes
304
116
 
305
117
  def run(self):
306
- crash_times = [] # timestamps of recent crashes
118
+ self.startupMessages()
119
+ self.configExistenceCheck()
120
+ self.configValidation()
121
+ self.checkReachability()
307
122
 
308
123
  while True:
309
- try:
310
- self.clearTerminal()
311
- self.evaluate()
312
-
313
- if self.config.debug:
314
- self.router.debug(f'Waiting {self.watcherconfig.watch_interval}s until next run...')
315
-
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
124
+ metrics = self.fetcher.snapshot(
125
+ duration=self.evaluatorcfg.sample_duration,
126
+ interval=self.evaluatorcfg.sample_interval,
127
+ drop_outliers=self.evaluatorcfg.sample_outlier_drop
128
+ )
129
+
130
+ # handle sampling failures
131
+ if any(metrics[k] is None for k in ('ram', 'cpu', 'uptime', 'tps', 'players')):
132
+ self.r.error('Sampling failed — core metrics missing.')
133
+ self.webhookSend(event='sampling_fail', server=self.config.server_name)
134
+ time.sleep(5)
135
+ continue
341
136
 
342
- # router log
343
- self.router.error('Unexpected error in watcher loop:')
344
- self.router.error(tb)
137
+ result = self.evaluator.evaluate(metrics)
345
138
 
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.')
139
+ # log reasons (minimal)
140
+ if result['flags']:
141
+ self.r.warn('Evaluation flags:')
142
+ for reason in result['reasons']:
143
+ self.r.warn(f"- {reason}")
358
144
 
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)
145
+ action, minutes = self.decideAction(result, metrics)
146
+ self.action.perform(action, minutes=minutes)
363
147
 
364
- continue
148
+ # watcher interval (fallback if not defined)
149
+ interval = getattr(self.watchercfg, 'watch_interval', 300)
150
+ time.sleep(interval)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: serverwatcher
3
- Version: 6.dev60
3
+ Version: 7.dev1
4
4
  Summary: A HungerLib-powered Minecraft server automation engine.
5
5
  Author: iFamished
6
6
  License: GPL-3.0
@@ -0,0 +1,27 @@
1
+ serverwatcher/__init__.py,sha256=cxkJh_cCZQJi17JdsSUBQuwBnkvg_lBWAqhol4zvPRw,463
2
+ serverwatcher/actionperformer.py,sha256=vAGzskqe5RRGFwHZdED6PCu8OhSM7eBbHZ1WumS3w7w,4259
3
+ serverwatcher/configmanager.py,sha256=r-CqKz2llu8vJ5glaTnvh5Q0Jo6yZ3Vt5WZZP8BhKMc,5136
4
+ serverwatcher/evaluator.py,sha256=PgweOnp9aZ3oxWO-404FQFCwgJ-RLhTEyt2ZVTy95A0,2443
5
+ serverwatcher/exceptions.py,sha256=Iz5d4vUZzIjo3Z56A1rHT8T57YSq7pJjELaOoyqNYx0,161
6
+ serverwatcher/metricfetcher.py,sha256=T3QOYj3mwvZFVORXP7SgYWyiiMMBPHBZa63h9h8qVfc,2632
7
+ serverwatcher/router.py,sha256=4iAtQZdMpbSvoVnNlW_V31dpudtlHSTw4-rFF2az2QM,2994
8
+ serverwatcher/targetserver.py,sha256=3eUW1BgAuxjM5AEgXVKmUYh9T4UpGHgoZF6EK3doU9w,5325
9
+ serverwatcher/watcher.py,sha256=kvcfuoEx9OMtnuwNV2Dprdv_RqQJpXY-J13ZkxBDUXE,5498
10
+ serverwatcher/configclasses/__init__.py,sha256=nAGf1ojW__EMd2q4NwvFdocjinzsQaHJPOp2Fmcqpbo,321
11
+ serverwatcher/configclasses/config.py,sha256=QKT-_qbtjPP6LU0yxUWT4m80E5AAmPN0HBAFsEMPktE,1510
12
+ serverwatcher/configclasses/discord.py,sha256=A1_Hu6560sUAsubOc3xL9_U0FKVOFVGjuxYiBeVL_-c,612
13
+ serverwatcher/configclasses/environment.py,sha256=OX3BKUzvK-CQK3K_X1muZo4o88EFCvOeUItsZx0wf7o,1103
14
+ serverwatcher/configclasses/evaluation.py,sha256=rnNsfvm9AM8aFOhaKOpEblp9w1c9hKKArlO3Xg9SNYg,2925
15
+ serverwatcher/configclasses/messages.py,sha256=iOkCvwagngW4aeWD5I6hi6cqqDkzEsFJsLHSuqK-P1s,3467
16
+ serverwatcher/configclasses/watcher.py,sha256=8BakRRuFjUzPu1Ms0ZW0sDRHIKNVkEs8Pp7LpguGTpM,1214
17
+ serverwatcher/defaultconfigs/config.yaml,sha256=DKSlKCMVFB8XqXd_-4awvVVENWMGLLqbS1hfH3ncP2M,509
18
+ serverwatcher/defaultconfigs/discord.yaml,sha256=DH-QIF06H8cdJw2h3Y_HFGf1o6BayRiLDGiKeC77G1g,88
19
+ serverwatcher/defaultconfigs/environment.yaml,sha256=5llzkQ4ifjs7KjDVKJKf7OXOQVPex8Mm176wwVYo1eg,213
20
+ serverwatcher/defaultconfigs/evaluation.yaml,sha256=pmV3b8Ln7ZGUCtaECdypcjVr0RefYy7yWf3d9eBFYZw,733
21
+ serverwatcher/defaultconfigs/messages.yaml,sha256=jSVEl-RYqPHhe5U5KLl8zfJtUBymvyE74hmzH0RFC_Y,3177
22
+ serverwatcher/defaultconfigs/watcher.yaml,sha256=iev4whdLrGBWE9zcmuMrUNnZc89iaxujKjUWqdWKGv0,189
23
+ serverwatcher-7.dev1.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
24
+ serverwatcher-7.dev1.dist-info/METADATA,sha256=42XSde7kRao7RDBZIhJVFL5cd2nFguYso-T0bbRmLsQ,2587
25
+ serverwatcher-7.dev1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
26
+ serverwatcher-7.dev1.dist-info/top_level.txt,sha256=8DJAf8WmmglgtZHkp8aoTriRJ2YPcS4F3DfOIkytASo,14
27
+ serverwatcher-7.dev1.dist-info/RECORD,,
serverwatcher/__main__.py DELETED
@@ -1,101 +0,0 @@
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
- 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
-
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
-
93
- # Start watcher thread
94
- watcher = ServerWatcher()
95
- threading.Thread(target=watcher.run, daemon=True).start()
96
-
97
- cli = WatcherCLI(watcher)
98
- asyncio.run(cli.run())
99
-
100
- if __name__ == '__main__':
101
- main()