-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpingpanel.py
More file actions
2819 lines (2441 loc) · 114 KB
/
pingpanel.py
File metadata and controls
2819 lines (2441 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import datetime
import json
import os
import platform
import subprocess
import sys
import tempfile
import time
from typing import Dict, List, Tuple
import requests
import yaml
from textual import log, work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Container
from textual.screen import Screen
from textual.widget import Widget
from textual.widgets import (Button, Checkbox, Footer, Header, Input, Label,
RichLog, Sparkline, Static, Tree, SelectionList)
from textual.worker import Worker
class ConfigManager:
CONFIG_FILE = "pingpanel_config.json"
@staticmethod
def save_config(
inventory_path: str,
check_interval: int = 60,
max_latency: int = 1000,
ping_count: int = 3,
max_threads: int = 10,
tailscale_api_key: str = "",
key_expiry_days: int = 90,
tailnet_org: str = "",
auto_ping_delay: int = 0,
important_tailscale_tags: list = None
) -> None:
key_expiry_date = None
if tailscale_api_key:
key_expiry_date = (datetime.datetime.now() +
datetime.timedelta(days=key_expiry_days)).isoformat()
with open(ConfigManager.CONFIG_FILE, "w") as f:
json.dump({
"inventory_path": inventory_path,
"check_interval": check_interval,
"max_latency": max_latency,
"ping_count": ping_count,
"max_threads": max_threads,
"tailscale_api_key": tailscale_api_key,
"key_expiry_date": key_expiry_date,
"key_expiry_days": key_expiry_days,
"tailnet_org": tailnet_org,
"auto_ping_delay": auto_ping_delay,
"important_tailscale_tags": important_tailscale_tags or ["server", "important"]
}, f)
@staticmethod
def load_config() -> dict:
if os.path.exists(ConfigManager.CONFIG_FILE):
with open(ConfigManager.CONFIG_FILE, "r") as f:
config = json.load(f)
return {
"inventory_path": config.get("inventory_path", ""),
"check_interval": config.get("check_interval", 60),
"max_latency": config.get("max_latency", 1000),
"ping_count": config.get("ping_count", 3),
"max_threads": config.get("max_threads", 10),
"tailscale_api_key": config.get("tailscale_api_key", ""),
"key_expiry_date": config.get("key_expiry_date", None),
"key_expiry_days": config.get("key_expiry_days", 90),
"tailnet_org": config.get("tailnet_org", ""),
"auto_ping_delay": config.get("auto_ping_delay", 0),
"important_tailscale_tags": config.get("important_tailscale_tags", ["server", "important"])
}
return {
"inventory_path": "",
"check_interval": 60,
"max_latency": 1000,
"ping_count": 3,
"max_threads": 10,
"tailscale_api_key": "",
"key_expiry_date": None,
"key_expiry_days": 90,
"tailnet_org": "",
"auto_ping_delay": 0,
"important_tailscale_tags": ["server", "important"]
}
@staticmethod
def days_until_key_expiry() -> int:
config = ConfigManager.load_config()
expiry_date = config.get("key_expiry_date")
if not expiry_date:
return None
try:
expiry = datetime.datetime.fromisoformat(expiry_date)
now = datetime.datetime.now()
days_left = (expiry - now).days
return max(0, days_left)
except (ValueError, TypeError):
return None
class LogManager:
CURRENT_LOG_FILE = "pingpanel_current_logs.json"
AGGREGATED_LOG_FILE = "pingpanel_aggregated_logs.json"
@staticmethod
def save_log_entry(host: str, group: str, latency: float, timestamp: str, success: bool) -> None:
log_entry = {
"host": host,
"group": group,
"latency": latency,
"timestamp": timestamp,
"success": success
}
existing_logs = []
if os.path.exists(LogManager.CURRENT_LOG_FILE):
try:
with open(LogManager.CURRENT_LOG_FILE, 'r') as f:
existing_logs = json.load(f)
except json.JSONDecodeError:
existing_logs = []
# Keep only entries from the last 24 hours - we want to keep more history
# for sparklines while still managing file size
current_time = datetime.datetime.fromisoformat(timestamp)
day_ago = current_time - datetime.timedelta(hours=24)
# First filter by recency - only keep logs from last 24 hours
recent_logs = [
log for log in existing_logs
if datetime.datetime.fromisoformat(log["timestamp"]) > day_ago
]
# Add the new entry
recent_logs.append(log_entry)
# If we have too many logs, limit by count per host
if len(recent_logs) > 1000: # arbitrary limit to prevent file growth
# Group by host and keep more entries per host (up to 100)
logs_by_host = {}
for log in recent_logs:
log_host = log["host"]
if log_host not in logs_by_host:
logs_by_host[log_host] = []
logs_by_host[log_host].append(log)
# Keep more entries per host
logs_to_keep = []
for host_logs in logs_by_host.values():
# Sort by timestamp (newest first)
sorted_logs = sorted(
host_logs,
key=lambda x: datetime.datetime.fromisoformat(x["timestamp"]),
reverse=True
)
# Keep up to 100 entries per host instead of just 5
logs_to_keep.extend(sorted_logs[:100])
else:
logs_to_keep = recent_logs
with open(LogManager.CURRENT_LOG_FILE, 'w') as f:
json.dump(logs_to_keep, f, indent=2)
LogManager.update_aggregated_logs(host, group, latency, timestamp, success)
@staticmethod
def update_aggregated_logs(host: str, group: str, latency: float, timestamp: str, success: bool) -> None:
aggregated_logs = {}
if os.path.exists(LogManager.AGGREGATED_LOG_FILE):
try:
with open(LogManager.AGGREGATED_LOG_FILE, 'r') as f:
aggregated_logs = {entry["host"]: entry for entry in json.load(f)}
except json.JSONDecodeError:
aggregated_logs = {}
if host in aggregated_logs:
entry = aggregated_logs[host]
total_checks = entry["total_checks"] + 1
if success:
old_total = entry["avg_latency"] * entry["total_checks"]
new_avg = (old_total + latency) / total_checks
entry["avg_latency"] = new_avg
entry["last_successful"] = timestamp
successful_checks = (entry["uptime_percentage"] / 100 * entry["total_checks"])
if success:
successful_checks += 1
entry["uptime_percentage"] = (successful_checks / total_checks) * 100
entry["total_checks"] = total_checks
entry["last_check"] = timestamp
else:
aggregated_logs[host] = {
"host": host,
"group": group,
"avg_latency": latency if success else 0,
"uptime_percentage": 100 if success else 0,
"total_checks": 1,
"last_check": timestamp,
"last_successful": timestamp if success else None
}
with open(LogManager.AGGREGATED_LOG_FILE, 'w') as f:
json.dump(list(aggregated_logs.values()), f, indent=2)
@staticmethod
def calculate_uptime(host: str, hours: int = 24) -> float:
current_time = datetime.datetime.now()
threshold_time = current_time - datetime.timedelta(hours=hours)
current_logs = []
if os.path.exists(LogManager.CURRENT_LOG_FILE):
try:
with open(LogManager.CURRENT_LOG_FILE, 'r') as f:
current_logs = json.load(f)
except json.JSONDecodeError:
current_logs = []
aggregated_logs = []
if os.path.exists(LogManager.AGGREGATED_LOG_FILE):
try:
with open(LogManager.AGGREGATED_LOG_FILE, 'r') as f:
aggregated_logs = json.load(f)
except json.JSONDecodeError:
aggregated_logs = []
recent_logs = [
log for log in current_logs
if log['host'] == host and
datetime.datetime.fromisoformat(log['timestamp']) > threshold_time
]
host_aggregate = next(
(log for log in aggregated_logs if log['host'] == host and
datetime.datetime.fromisoformat(log['last_check']) > threshold_time),
None
)
if not recent_logs and not host_aggregate:
return 0.0
total_checks = len(recent_logs)
total_successes = sum(1 for log in recent_logs if log['success'])
if host_aggregate:
total_checks += host_aggregate['total_checks']
total_successes += (host_aggregate['total_checks'] * host_aggregate['uptime_percentage'] / 100)
return (total_successes / total_checks) * 100 if total_checks > 0 else 0.0
@staticmethod
def get_last_online(host: str) -> str:
if os.path.exists(LogManager.AGGREGATED_LOG_FILE):
try:
with open(LogManager.AGGREGATED_LOG_FILE, 'r') as f:
logs = json.load(f)
for log in logs:
if log['host'] == host and log.get('last_successful'):
return datetime.datetime.fromisoformat(log['last_successful']).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
pass
if os.path.exists(LogManager.CURRENT_LOG_FILE):
try:
with open(LogManager.CURRENT_LOG_FILE, 'r') as f:
logs = json.load(f)
successful_logs = [log for log in logs if log['host'] == host and log['success']]
if successful_logs:
latest = max(successful_logs, key=lambda x: x['timestamp'])
return datetime.datetime.fromisoformat(latest['timestamp']).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
pass
return "Never"
@staticmethod
def get_latency_history(host: str, hours: int = 24, points: int = 360) -> list:
"""
Fetch latency history for a specific host from aggregated logs
Returns a list of latency values suitable for sparkline
"""
try:
all_logs = []
current_time = datetime.datetime.now()
threshold_time = current_time - datetime.timedelta(hours=hours)
# Check current logs first
if os.path.exists(LogManager.CURRENT_LOG_FILE):
try:
with open(LogManager.CURRENT_LOG_FILE, 'r') as f:
current_logs = json.load(f)
# Get all matching logs within the time range
matching_logs = [
log for log in current_logs
if log['host'] == host and
log['success'] and
datetime.datetime.fromisoformat(log['timestamp']) >= threshold_time
]
all_logs.extend(matching_logs)
log.debug(f"Found {len(matching_logs)} log entries for {host} in current logs")
except json.JSONDecodeError:
log.error(f"Failed to decode current log file: {LogManager.CURRENT_LOG_FILE}")
pass
# Sort by timestamp and extract latencies
all_logs.sort(key=lambda x: x['timestamp'])
latencies = [log['latency'] for log in all_logs if log['success']]
# Only use aggregated logs as fallback if we have very few data points
if len(latencies) < 5 and os.path.exists(LogManager.AGGREGATED_LOG_FILE):
try:
log.debug(f"Not enough data points ({len(latencies)}), checking aggregated logs")
with open(LogManager.AGGREGATED_LOG_FILE, 'r') as f:
aggregated = json.load(f)
host_entry = next(
(entry for entry in aggregated if entry['host'] == host),
None
)
if host_entry:
avg_latency = host_entry.get('avg_latency', 0)
if avg_latency > 0:
# Use the average to pad sparse data
log.debug(f"Using average latency {avg_latency} from aggregated logs")
if len(latencies) == 0:
return [avg_latency] * min(5, points)
# If we have some data but not enough, add the average as padding
while len(latencies) < 5:
latencies.append(avg_latency)
except json.JSONDecodeError:
log.error(f"Failed to decode aggregated log file: {LogManager.AGGREGATED_LOG_FILE}")
pass
log.debug(f"Total latency data points for {host}: {len(latencies)}")
# If we have more points than our limit, sample them
if len(latencies) > points:
log.debug(f"Sampling {points} points from {len(latencies)} total points")
step = len(latencies) // points
return latencies[::step][:points]
# If we don't have enough data, pad with the last value or zeros
if len(latencies) < 2:
log.debug(f"Not enough data points, returning: {latencies or [0]}")
return latencies or [0]
log.debug(f"Returning {len(latencies)} data points for sparkline")
return latencies
except Exception as e:
log.error(f"Error getting latency history: {str(e)}", exc_info=True)
return [0]
class PingMonitor:
@staticmethod
async def ping(host: str, count: int = 3) -> Tuple[bool, float]:
param = "-n" if platform.system().lower() == "windows" else "-c"
try:
start_time = time.time()
process = await asyncio.create_subprocess_exec(
"ping", param, str(count), host,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, _ = await asyncio.wait_for(process.communicate(), timeout=count * 2)
end_time = time.time()
output = stdout.decode()
if platform.system().lower() == "windows":
if "Average" in output:
avg_line = [line for line in output.split("\n") if "Average" in line][0]
latency = float(avg_line.split("=")[-1].strip("ms"))
else:
latency = 0.0
else:
if "rtt" in output:
avg_line = output.split("\n")[-2]
latency = float(avg_line.split("/")[4])
else:
latency = 0.0
return process.returncode == 0, latency
except (asyncio.TimeoutError, Exception) as e:
log.error(f"Ping error for {host}: {str(e)}")
return False, 0.0
class InventoryParser:
@staticmethod
def parse_inventory(file_path: str) -> Dict[str, List[Tuple[str, str]]]:
with open(file_path, 'r') as f:
inventory = yaml.safe_load(f)
groups = {}
def extract_hosts(data, parent=None):
if isinstance(data, dict):
if 'hosts' in data:
group_name = parent if parent else 'ungrouped'
if group_name not in groups:
groups[group_name] = []
for hostname, host_data in data['hosts'].items():
if 'ansible_host' in host_data:
groups[group_name].append((hostname, host_data['ansible_host']))
for key, value in data.items():
if isinstance(value, dict):
extract_hosts(value, key)
extract_hosts(inventory)
return groups
class TableScreen(Screen):
def __init__(self, groups: Dict[str, List[Tuple[str, str]]]):
super().__init__()
self.groups = groups
self.host_nodes = {}
self.host_states = {}
self.auto_check = False
self.check_task = None
self.last_state_change = None
self.total_up = 0
self.total_down = 0
config = ConfigManager.load_config()
self.ping_semaphore = asyncio.Semaphore(config["max_threads"])
self._counter_lock = asyncio.Lock()
self.selected_host = None
self.selected_hostname = None
def compose(self) -> ComposeResult:
yield Header()
yield Container(
Static("Status: Ready", id="status"),
Container(
Static("[green]Up: 0[/]", id="total_up"),
Static("[red]Down: 0[/]", id="total_down"),
id="totals"
),
Container(
Container(
Tree("Hosts", id="host_tree"),
id="tree-container"
),
Container(
RichLog(
highlight=True,
markup=True,
max_lines=1000,
wrap=True,
auto_scroll=True,
id="ping-log"
),
id="log-container"
),
id="split-container"
),
Container(
Button("Check Now", id="check"),
Button("Auto Check", id="auto_check", variant="default"),
Button("Back", id="back"),
id="buttons",
),
)
yield Footer()
def on_mount(self) -> None:
tree = self.query_one("#host_tree")
log_widget = self.query_one("#ping-log", RichLog)
log_widget.clear()
log_widget.write("[bold green]Host Status Monitor Log[/]", expand=True)
log_widget.write("Status changes and ping results will be recorded here", expand=True)
log_widget.write("─" * 50, expand=True)
self.log_message("[blue]Log ready for ping events[/]")
self.total_up = 0
self.total_down = 0
for group, hosts in self.groups.items():
group_node = tree.root.add(group)
for hostname, ip in hosts:
label = f"{hostname} ({ip}) ⟳"
host_node = group_node.add(label)
self.host_nodes[(group, hostname)] = host_node
self.host_states[(group, hostname)] = None
def log_message(self, message: str) -> None:
try:
log_widget = self.query_one("#ping-log", RichLog)
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
log_widget.write(
f"[dim]{timestamp}[/] {message}",
expand=True,
scroll_end=True,
animate=True
)
except Exception as e:
log.error(f"Error writing to RichLog: {str(e)}")
async def check_single_host(self, group: str, hostname: str, ip: str) -> None:
async with self.ping_semaphore:
host_node = self.host_nodes[(group, hostname)]
status = self.query_one("#status")
try:
config = ConfigManager.load_config()
status.update(f"Status: Checking {hostname}...")
self.log_message(f"Checking [bold]{hostname}[/] ({ip})...")
is_alive, latency = await PingMonitor.ping(ip, config["ping_count"])
timestamp = datetime.datetime.now().isoformat()
is_acceptable = is_alive and latency <= config["max_latency"]
LogManager.save_log_entry(
host=hostname,
group=group,
latency=latency,
timestamp=timestamp,
success=is_acceptable
)
uptime = LogManager.calculate_uptime(hostname)
status_text = f"{latency:.1f}ms" if is_alive else "timeout"
prev_state = self.host_states.get((group, hostname))
async with self._counter_lock:
if prev_state is None:
if is_acceptable:
self.total_up += 1
else:
self.total_down += 1
elif prev_state != is_acceptable:
if is_acceptable and self.total_down > 0:
self.total_up += 1
self.total_down -= 1
elif not is_acceptable and self.total_up > 0:
self.total_down += 1
self.total_up -= 1
change_text = f"{hostname} is now {'ONLINE' if is_acceptable else 'OFFLINE'}"
self.last_state_change = change_text
status.update(f"Status: {change_text}")
# Log state change to RichLog
if is_acceptable:
self.log_message(f"Host '[bold]{hostname}[/]' [green]came online[/] ({status_text})")
else:
self.log_message(f"Host '[bold]{hostname}[/]' [red]went offline[/] (Last up: {LogManager.get_last_online(hostname)})")
else:
status.update(f"Status: Checking {hostname}...")
if is_acceptable:
status_icon = "✓"
icon_markup = f"[green]{status_icon}[/]"
elif is_alive:
status_icon = "!"
icon_markup = f"[yellow]{status_icon}[/]"
else:
status_icon = "✗"
icon_markup = f"[red]{status_icon}[/]"
self.host_states[(group, hostname)] = is_acceptable
last_seen = f" (Last up: {LogManager.get_last_online(hostname)})" if not is_acceptable else ""
host_node.label = f"{hostname} ({ip}) {icon_markup} [{status_text}] [blue]{uptime:.1f}%[/]{last_seen}"
self.query_one("#total_up").update(f"[green]Up: {self.total_up}[/]")
self.query_one("#total_down").update(f"[red]Down: {self.total_down}[/]")
# Log ping result in compact form
if is_acceptable:
self.log_message(f"[green]✓[/] {hostname.ljust(20)} {ip.ljust(15)} [green]{latency:.1f}ms[/]")
elif is_alive:
self.log_message(f"[yellow]![/] {hostname.ljust(20)} {ip.ljust(15)} [yellow]{latency:.1f}ms[/] (exceeds threshold)")
else:
self.log_message(f"[red]✗[/] {hostname.ljust(20)} {ip.ljust(15)} [red]timeout[/]")
except Exception as e:
error_msg = f"Error during check: {str(e)}"
print(error_msg)
status.update(f"Status: {error_msg}")
self.log_message(f"[red]Error checking {hostname}: {str(e)}[/]")
async def check_hosts(self) -> None:
status = self.query_one("#status")
status.update("Status: Starting host checks...")
self.log_message("[blue]━━━━━━━━━━━━━━━ Starting Host Checks ━━━━━━━━━━━━━━━[/]")
try:
tasks = []
for group, data in self.groups.items():
for hostname, ip in data:
task = asyncio.create_task(self.check_single_host(group, hostname, ip))
tasks.append(task)
await asyncio.gather(*tasks)
if self.last_state_change:
status.update(f"Status: {self.last_state_change}")
else:
status.update("Status: All checks complete")
self.log_message("[blue]━━━━━━━━━━━━━━━ All Checks Complete ━━━━━━━━━━━━━━━[/]")
summary = f"[green]✓ {self.total_up} online[/] • [red]✗ {self.total_down} offline[/] • [blue]{self.total_up + self.total_down} total[/]"
self.log_message(summary)
except Exception as e:
error_msg = f"Error during check: {str(e)}"
print(error_msg)
status.update(f"Status: {error_msg}")
self.log_message(f"[red]Error during check: {str(e)}[/]")
async def auto_check_hosts(self) -> None:
config = ConfigManager.load_config()
interval = config["check_interval"]
while self.auto_check:
await self.check_hosts()
await asyncio.sleep(interval)
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "back":
self.auto_check = False
if self.check_task:
self.check_task.cancel()
self.app.pop_screen()
elif event.button.id == "check":
self.run_worker(self.check_hosts())
elif event.button.id == "auto_check":
self.auto_check = not self.auto_check
if self.auto_check:
event.button.variant = "success"
event.button.label = "Auto Check (On)"
self.check_task = self.run_worker(self.auto_check_hosts())
else:
event.button.variant = "default"
event.button.label = "Auto Check"
if self.check_task:
self.check_task.cancel()
def on_tree_node_selected(self, event: Tree.NodeSelected) -> None:
try:
node = event.node
# Skip if this is a group node
if node.parent == self.query_one("#host_tree").root:
self.selected_hostname = None
return
# Extract the hostname from the node label
label = node.label
if " (" in label:
hostname = label.split(" (")[0]
self.selected_hostname = hostname
self.log_message(f"Selected host: [bold]{hostname}[/]")
except Exception as e:
log.error(f"Error in node selection: {str(e)}")
self.selected_hostname = None
class KeyExpiryWarningScreen(Screen):
def __init__(self, days_left: int):
super().__init__()
self.days_left = days_left
def compose(self) -> ComposeResult:
yield Header(show_clock=True)
yield Container(
Static("⚠️ Tailscale API Key Expiration Warning ⚠️", id="warning-title"),
Static(f"Your Tailscale API key will expire in {self.days_left} days.", id="warning-message"),
Static("Please update your API key in the Settings menu before it expires.", id="warning-advice"),
Button("Continue", id="continue", variant="primary"),
id="warning-container"
)
yield Footer()
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "continue":
self.app.pop_screen()
class SettingsScreen(Screen):
def compose(self) -> ComposeResult:
config = ConfigManager.load_config()
yield Header()
yield Container(
Static("Settings", classes="settings-title"),
Container(
# Left column
Container(
Static("Connection Settings", classes="settings-section-title"),
Static("Inventory File Path:", id="inventory_label"),
Button(config["inventory_path"] or "Not Set", id="inventory_path"),
Static("Max Threads:", id="threads_label"),
Button(str(config["max_threads"]), id="max_threads"),
Static("Auto-Ping Delay (seconds):", id="auto_ping_delay_label"),
Button(str(config["auto_ping_delay"]), id="auto_ping_delay"),
id="left-settings"
),
# Middle column
Container(
Static("Ping Configuration", classes="settings-section-title"),
Static("Check Interval (seconds):", id="interval_label"),
Button(str(config["check_interval"]), id="interval"),
Static("Max Acceptable Latency (ms):", id="latency_label"),
Button(str(config["max_latency"]), id="max_latency"),
Static("Ping Packet Count:", id="count_label"),
Button(str(config["ping_count"]), id="ping_count"),
id="middle-settings"
),
# Right column
Container(
Static("Tailscale Integration", classes="settings-section-title"),
Static("Tailscale API Key:", id="tailscale_api_label"),
Button("*****" if config["tailscale_api_key"] else "Not Set", id="tailscale_api_key"),
Static("Tailnet Organization:", id="tailnet_org_label"),
Button(config["tailnet_org"] or "Not Set", id="tailnet_org"),
Static("API Key Expiry (days):", id="key_expiry_label"),
Button(str(config["key_expiry_days"]), id="key_expiry_days"),
id="right-settings"
),
id="settings-grid"
),
Container(
Button("Save", id="save"),
Button("Back", id="back"),
id="settings-buttons",
),
id="settings-container"
)
yield Footer()
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "back":
self.app.pop_screen()
elif event.button.id in ["interval", "max_latency", "ping_count", "inventory_path",
"max_threads", "tailscale_api_key", "key_expiry_days",
"tailnet_org", "auto_ping_delay"]:
prompts = {
"interval": "Enter check interval in seconds:",
"max_latency": "Enter maximum acceptable latency in milliseconds:",
"ping_count": "Enter number of ping packets to send:",
"inventory_path": "Enter path to Ansible inventory file:",
"max_threads": "Enter maximum number of concurrent pings:",
"tailscale_api_key": "Enter your Tailscale API key:",
"key_expiry_days": "Enter days until API key expires (default 90):",
"tailnet_org": "Enter your Tailnet organization (e.g. example.com or example):",
"auto_ping_delay": "Enter delay before auto-ping (seconds, 0 for immediate):"
}
if event.button.id == "tailscale_api_key":
current_value = ConfigManager.load_config()["tailscale_api_key"]
else:
current_value = str(self.query_one(f"#{event.button.id}").label)
if current_value == "Not Set":
current_value = ""
self.app.push_screen(
TextPrompt(
prompts[event.button.id],
current_value,
event.button.id
)
)
elif event.button.id == "save":
try:
interval = int(str(self.query_one("#interval").label))
max_latency = int(str(self.query_one("#max_latency").label))
ping_count = int(str(self.query_one("#ping_count").label))
max_threads = int(str(self.query_one("#max_threads").label))
key_expiry_days = int(str(self.query_one("#key_expiry_days").label))
auto_ping_delay = int(str(self.query_one("#auto_ping_delay").label))
inventory_path = str(self.query_one("#inventory_path").label)
tailnet_org_btn = self.query_one("#tailnet_org")
tailnet_org = str(tailnet_org_btn.label)
if tailnet_org == "Not Set":
tailnet_org = ""
button_text = str(self.query_one("#tailscale_api_key").label)
if button_text == "*****":
tailscale_api_key = ConfigManager.load_config()["tailscale_api_key"]
else:
tailscale_api_key = button_text
if interval < 1 or max_latency < 1 or ping_count < 1 or max_threads < 1 or key_expiry_days < 1:
raise ValueError("All values must be positive")
if auto_ping_delay < 0:
raise ValueError("Auto ping delay cannot be negative")
if inventory_path != "Not Set" and inventory_path.strip() and not os.path.exists(inventory_path):
self.notify(f"Warning: Inventory file '{inventory_path}' does not exist")
ConfigManager.save_config(
inventory_path,
interval,
max_latency,
ping_count,
max_threads,
tailscale_api_key,
key_expiry_days,
tailnet_org,
auto_ping_delay
)
self.app.pop_screen()
except ValueError as e:
self.notify(str(e))
class TextPrompt(Screen):
def __init__(self, question: str, default_value: str, setting_id: str, callback=None):
super().__init__()
self.question = question
self.default_value = default_value
self.setting_id = setting_id
self.callback = callback
def compose(self) -> ComposeResult:
yield Static(self.question)
yield Input(
value=self.default_value,
id="input"
)
yield Button("OK", id="ok")
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "ok":
value = self.query_one("#input").value
# If we have a callback, use it
if self.callback:
self.app.pop_screen()
self.callback(value)
return
# Otherwise use the default behavior
settings_screen = self.app.screen_stack[-2]
if self.setting_id == "tailscale_api_key":
settings_screen.query_one(f"#{self.setting_id}").label = value if value else "Not Set"
else:
settings_screen.query_one(f"#{self.setting_id}").label = value
self.app.pop_screen()
class MainMenu(Screen):
def compose(self) -> ComposeResult:
yield Header()
yield Container(
Container(
Static(
"""[bold blue]██████╗[bold green]██╗[bold yellow]███╗ ██╗[bold red] ██████╗ [bold magenta]██████╗ [bold cyan]█████╗ [bold white]███╗ ██╗[bold blue]███████╗[bold green]██╗
[bold blue]██╔══██╗[bold green]██║[bold yellow]████╗ ██║[bold red]██╔════╝ [bold magenta]██╔══██╗[bold cyan]██╔══██╗[bold white]████╗ ██║[bold blue]██╔════╝[bold green]██║
[bold blue]██████╔╝[bold green]██║[bold yellow]██╔██╗ ██║[bold red]██║ ███╗[bold magenta]██████╔╝[bold cyan]███████║[bold white]██╔██╗ ██║[bold blue]█████╗ [bold green]██║
[bold blue]██╔═══╝ [bold green]██║[bold yellow]██║╚██╗██║[bold red]██║ ██║[bold magenta]██╔═══╝ [bold cyan]██╔══██║[bold white]██║╚██╗██║[bold blue]██╔══╝ [bold green]██║
[bold blue] ██║ [bold green]██║[bold yellow]██║ ╚████║[bold red]╚██████╔╝[bold magenta]██║ [bold cyan]██║ ██║[bold white]██║ ╚████║[bold blue]███████╗[bold green]███████╗
[bold blue] ╚═╝ [bold green]╚═╝[bold yellow]╚═╝ ╚═══╝[bold red] ╚═════╝ [bold magenta]╚═╝ [bold cyan]╚═╝ ╚═╝[bold white]╚═╝ ╚═══╝[bold blue]╚══════╝[bold green]╚══════╝[/]""", id="title-message"),
Static("Courtesy of CrabManStan", id="courtesy-message"),
Static("", classes="spacer"),
Container(
Button("Start Monitoring", id="start_monitoring", classes="btn-sunset"),
Button("Settings", id="settings", classes="btn-lime"),
Button("Exit", id="exit", classes="btn-coral"),
classes="button-row"
),
id="menu-container"
),
id="main-container"
)
yield Footer()
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "exit":
self.app.exit()
elif event.button.id == "settings":
self.app.push_screen(SettingsScreen())
elif event.button.id == "start_monitoring":
self.app.push_screen(MonitoringTypeScreen())
class MonitoringTypeScreen(Screen):
"""Screen to select between Standard Ping or Tailscale monitoring."""
def compose(self) -> ComposeResult:
yield Header()
yield Container(
Container(
Static("Select Monitoring Type", id="type-selection-title"),
Static("", classes="spacer"),
Container(
Button("Standard Ping", id="standard_ping", variant="primary", classes="btn-violet"),
Button("Tailscale", id="tailscale", variant="warning", classes="btn-ocean"),
Button("Back", id="back", classes="btn-coral"),
classes="button-row"
),
id="type-selection-container"
),
id="main-container"
)
yield Footer()
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "back":
self.app.pop_screen()
elif event.button.id == "standard_ping":
try:
print("Loading config...")
config = ConfigManager.load_config()
inventory_path = config["inventory_path"]
if not inventory_path or not os.path.exists(inventory_path):
self.notify(
"No inventory file set or file doesn't exist.\n"
"Please configure an inventory file in Settings first.",
title="Missing Inventory",
severity="error"
)
return
print("Parsing inventory...")
groups = InventoryParser.parse_inventory(inventory_path)
print(f"Found {len(groups)} groups")
self.app.push_screen(TableScreen(groups))
except Exception as e:
print(f"Error starting monitoring: {e}")
elif event.button.id == "tailscale":
self.app.push_screen(TailscaleIntegrationScreen())
class PingPanel(App):
BINDINGS = [
Binding("d", "toggle_dark", "Toggle dark mode"),
]
ENABLE_CONSOLE = True
CSS = """
Screen {
border: none;
}
Tree {
height: 1fr;
min-height: 10;
margin: 1 0;
}
Container {
height: auto;
overflow-x: auto;
}
#buttons {
width: 100%;
height: 3;
dock: bottom;
layout: horizontal;
align: center middle;
background: $surface;
border-top: solid $primary;
}
Button {
margin: 0 1;
min-width: 16;
}
/* Jazzy Button Colors */
.btn-sunset {
background: #FF5E62;
color: $text;
border: tall $background;
}
.btn-sunset:hover {
background: #FF9966;
}
.btn-ocean {
background: #2C3E50;
color: $text;
border: tall $background;
}
.btn-ocean:hover {
background: #4CA1AF;
}
.btn-violet {
background: #8E2DE2;
color: $text;
border: tall $background;
}
.btn-violet:hover {
background: #9F44D3;
}