-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAPMonitor.py
More file actions
5928 lines (5060 loc) · 269 KB
/
Copy pathAPMonitor.py
File metadata and controls
5928 lines (5060 loc) · 269 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
#!/usr/bin/env python3
"""
APMonitor - On-Premises Network Resource Availability Monitor
https://github.com/CompSciFutures/APMonitor
“Commons Clause” License Condition v1.0
=======================================
The Software is provided to you by the Licensor under the License,
as defined below, subject to the following condition.
Without limiting other conditions in the License, the grant of rights
under the License will not include, and the License does not grant to
you, the right to Sell the Software.
For purposes of the foregoing, “Sell” means practicing any or all of
the rights granted to you under the License to provide to third
parties, for a fee or other consideration (including without
limitation fees for hosting or consulting/ support services related
to the Software), a product or service whose value derives, entirely
or substantially, from the functionality of the Software. Any license
notice or attribution required by the License must also include this
Commons Clause License Condition notice.
Software: APMonitor
License: GNU General Public License version 3
Licensor: Andrew (AP) Prendergast, ap@andrewprendergast.com -- FSF Member
GNU General Public License version 3
------------------------------------
(C) COPYRIGHT 2000-2025 Andrew Prendergast
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
__version__ = "1.4.1"
__app_name__ = "APMonitor"
import argparse
import json
import re
from urllib.parse import urlparse
import OpenSSL.crypto
from pathlib import Path
import yaml # can push into load_config() if this is a dependency problem for you
import requests
import time
import platform
import subprocess
import concurrent.futures
import sys
import threading
import os
from datetime import datetime
import ssl
import hashlib
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import traceback
from typing import Any, Dict, List, Optional, Tuple, Union
import rrdtool
import tempfile
import difflib
# NB: check_quic_url() already has aioquic defined as a function local import so you don't have to lug it around if you don't need it
# Hush insecure SSL warnings
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Configuration constants
MAX_RETRIES: int = 3
MAX_TRY_SECS: int = 20
VERBOSE: int = 0
IGNORE_SSL_ERRORS: bool = True
MAX_THREADS: int = 1
STATEFILE: str = "statefile.json"
STATE: Dict[str, Any] = {}
STATE_LOCK: threading.Lock = threading.Lock()
DEFAULT_CHECK_EVERY_N_SECS: int = 60
DEFAULT_NOTIFY_EVERY_N_SECS: int = 600
DEFAULT_AFTER_EVERY_N_NOTIFICATIONS: int = 1
RRD_ENABLED: bool = False
RRD_ELAPSED_MS: int = 0
RRD_ELAPSED_LOCK: threading.Lock = threading.Lock()
# Global thread-local storage
thread_local: threading.local = threading.local()
thread_local.prefix = None
def to_natural_language_boolean(value: Any) -> bool:
"""Convert various representations to boolean.
False values: false, no, fail, 0, bad, negative, off, n, f (case-insensitive)
True values: true, yes, ok, 1, good, positive, on, y, t (case-insensitive)
Args:
value: Can be bool, int, str, or None
Returns:
bool: The boolean interpretation
Raises:
ValueError: If string value is not a recognized boolean representation
"""
if value is None:
return False
if isinstance(value, bool):
return value
if isinstance(value, int):
return bool(value)
if isinstance(value, str):
normalized = value.lower().strip()
# False values
if normalized in ['false', 'no', 'fail', '0', 'bad', 'negative', 'off', 'n', 'f']:
return False
# True values
if normalized in ['true', 'yes', 'ok', '1', 'good', 'positive', 'on', 'y', 't']:
return True
raise ValueError(f"Unrecognized boolean value: '{value}'")
# For any other type, use Python's truthiness
return bool(value)
# Loads YAML or JSON config file
#
# Example Config
# --------------
#
# site: "HomeLab"
# emails:
# - "ap@andrewprendergast.com"
# - sfgdfgdfg@sendmonitoringalert.com
#
# monitors:
#
# - type: ping
# name: home-fw
# address: "192.168.1.1"
# heartbeat_url: "http://google.com/"
#
# - type: ping
# name: "Inception t4000"
# address: "192.168.1.22"
# heartbeat_url: "http://excite.com/"
#
# - type: http
# name: in3245622
# address: "http://192.168.1.21/Login?oldUrl=Index"
# expect: "System Name: <b>HomeLab</b>"
# heartbeat_url: "http://google.com/"
#
def load_config(config_path: str) -> Dict[str, Any]:
"""Load configuration from JSON or YAML file."""
path = Path(config_path)
if not path.exists():
print(f"Error: Config file '{config_path}' not found", file=sys.stderr)
sys.exit(1)
with open(path, 'r') as f:
if path.suffix in ['.json']:
return json.load(f)
elif path.suffix in ['.yaml', '.yml']:
return yaml.safe_load(f)
else:
print(f"Error: Unsupported file format '{path.suffix}'", file=sys.stderr)
sys.exit(1)
def load_state(statefile_path: str) -> Dict[str, Any]:
"""Load state from JSON file."""
path = Path(statefile_path)
if not path.exists():
return {}
try:
with open(path, 'r') as f:
return json.load(f)
except Exception as e:
if VERBOSE:
print(f"Warning: Could not load state from '{statefile_path}': {e}")
return {}
def update_state(updates: Dict[str, Any]) -> None:
"""Thread-safely update state and write to .new file."""
global STATE
with STATE_LOCK:
STATE.update(updates)
new_path = Path(STATEFILE + '.new')
try:
with open(new_path, 'w') as f:
json.dump(STATE, f, indent=2)
except Exception as e:
print(f"Error: Could not write state to '{new_path}': {e}", file=sys.stderr)
# keep console logging atomic as well
sys.stdout.flush()
def save_state(state: Dict[str, Any]) -> None:
"""Rotate state files: current -> .old, .new -> current."""
global STATE
STATE = state
update_state(state)
path = Path(STATEFILE)
new_path = Path(STATEFILE + '.new')
old_path = Path(STATEFILE + '.old')
try:
# Rotate files: current -> .old, .new -> current
if path.exists():
os.replace(path, old_path)
if new_path.exists():
os.replace(new_path, path)
except Exception as e:
print(f"Error: Could not rotate state files: {e}", file=sys.stderr)
def format_time_ago(timestamp_or_secs: Union[str, int, float, None]) -> str:
"""Format time difference in human-readable form."""
if not timestamp_or_secs:
return "never"
try:
# If it's an integer, treat as seconds directly
if isinstance(timestamp_or_secs, int) or isinstance(timestamp_or_secs, float):
total_seconds = int(timestamp_or_secs)
else:
# Otherwise parse as ISO timestamp
last_time = datetime.fromisoformat(timestamp_or_secs)
delta = datetime.now() - last_time
total_seconds = int(delta.total_seconds())
if total_seconds < 60:
return f"{total_seconds} secs"
elif total_seconds < 3600:
minutes = total_seconds // 60
seconds = total_seconds % 60
return f"{minutes} mins {seconds} secs"
elif total_seconds < 86400:
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
return f"{hours} hrs {minutes} mins"
else:
days = total_seconds // 86400
hours = (total_seconds % 86400) // 3600
return f"{days} days {hours} hrs"
except:
return "unknown"
class ConfigError(Exception):
"""Configuration validation error."""
pass
def print_and_exit_on_bad_config(config: Dict[str, Any]) -> None:
"""Validate configuration structure and required fields."""
try:
# Check site is present and is a dict
if 'site' not in config:
raise ConfigError("Missing required field: 'site'")
if not isinstance(config['site'], dict):
raise ConfigError("Field 'site' must be a dictionary")
site = config['site']
# Check site name is present and is a string
if 'name' not in site:
raise ConfigError("Missing required field: 'site.name'")
if not isinstance(site['name'], str):
raise ConfigError("Field 'site.name' must be a string")
# Validate optional site.email_server
if 'email_server' in site:
if not isinstance(site['email_server'], dict):
raise ConfigError("Field 'site.email_server' must be a dictionary")
email_server = site['email_server']
if 'smtp_host' not in email_server:
raise ConfigError("Field 'site.email_server': missing required field 'smtp_host'")
if not isinstance(email_server['smtp_host'], str):
raise ConfigError("Field 'site.email_server.smtp_host' must be a string")
if 'smtp_port' not in email_server:
raise ConfigError("Field 'site.email_server': missing required field 'smtp_port'")
if not isinstance(email_server['smtp_port'], int) or email_server['smtp_port'] < 1 or email_server['smtp_port'] > 65535:
raise ConfigError("Field 'site.email_server.smtp_port' must be an integer between 1 and 65535")
if 'smtp_username' in email_server:
if not isinstance(email_server['smtp_username'], str):
raise ConfigError("Field 'site.email_server.smtp_username' must be a string")
if 'smtp_password' in email_server:
if not isinstance(email_server['smtp_password'], str):
raise ConfigError("Field 'site.email_server.smtp_password' must be a string")
if 'from_address' not in email_server:
raise ConfigError("Field 'site.email_server': missing required field 'from_address'")
if not isinstance(email_server['from_address'], str):
raise ConfigError("Field 'site.email_server.from_address' must be a string")
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(email_pattern, email_server['from_address']):
raise ConfigError(f"Field 'site.email_server.from_address': '{email_server['from_address']}' is not a valid email address")
if 'use_tls' in email_server:
if not isinstance(email_server['use_tls'], bool):
raise ConfigError("Field 'site.email_server.use_tls' must be a boolean")
# Validate optional site.outage_emails
if 'outage_emails' in site:
if 'email_server' not in site:
raise ConfigError("Field 'site.outage_emails' can only be specified if 'site.email_server' is configured")
if not isinstance(site['outage_emails'], list):
raise ConfigError("Field 'site.outage_emails' must be a list")
for i, email_entry in enumerate(site['outage_emails']):
if not isinstance(email_entry, dict):
raise ConfigError(f"Field 'site.outage_emails[{i}]' must be a dictionary")
if 'email' not in email_entry:
raise ConfigError(f"Field 'site.outage_emails[{i}]': missing required field 'email'")
if not isinstance(email_entry['email'], str):
raise ConfigError(f"Field 'site.outage_emails[{i}].email' must be a string")
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
if not re.match(email_pattern, email_entry['email']):
raise ConfigError(f"Field 'site.outage_emails[{i}].email': '{email_entry['email']}' is not a valid email address")
if 'email_outages' in email_entry:
try:
to_natural_language_boolean(email_entry['email_outages'])
except ValueError as e:
raise ConfigError(f"Field 'site.outage_emails[{i}].email_outages': {e}")
if 'email_recoveries' in email_entry:
try:
to_natural_language_boolean(email_entry['email_recoveries'])
except ValueError as e:
raise ConfigError(f"Field 'site.outage_emails[{i}].email_recoveries': {e}")
if 'email_reminders' in email_entry:
try:
to_natural_language_boolean(email_entry['email_reminders'])
except ValueError as e:
raise ConfigError(f"Field 'site.outage_emails[{i}].email_reminders': {e}")
# Validate optional site.outage_webhooks
if 'outage_webhooks' in site:
if not isinstance(site['outage_webhooks'], list):
raise ConfigError("Field 'site.outage_webhooks' must be a list")
for i, webhook in enumerate(site['outage_webhooks']):
if not isinstance(webhook, dict):
raise ConfigError(f"Field 'site.outage_webhooks[{i}]' must be a dictionary")
if 'endpoint_url' not in webhook:
raise ConfigError(f"Missing required field: 'site.outage_webhooks[{i}].endpoint_url'")
if not isinstance(webhook['endpoint_url'], str):
raise ConfigError(f"Field 'site.outage_webhooks[{i}].endpoint_url' must be a string")
parsed_webhook = urlparse(webhook['endpoint_url'])
if not parsed_webhook.scheme or not parsed_webhook.netloc:
raise ConfigError(f"Field 'site.outage_webhooks[{i}].endpoint_url' must be a valid URL with scheme and host, got '{webhook['endpoint_url']}'")
if 'request_method' not in webhook:
raise ConfigError(f"Missing required field: 'site.outage_webhooks[{i}].request_method'")
if webhook['request_method'] not in ['GET', 'POST']:
raise ConfigError(f"Field 'site.outage_webhooks[{i}].request_method' must be 'GET' or 'POST', got '{webhook['request_method']}'")
if 'request_encoding' not in webhook:
raise ConfigError(f"Missing required field: 'site.outage_webhooks[{i}].request_encoding'")
if webhook['request_encoding'] not in ['URL', 'HTML', 'JSON', 'CSVQUOTED']:
raise ConfigError(f"Field 'site.outage_webhooks[{i}].request_encoding' must be one of 'URL', 'HTML', 'JSON', 'CSVQUOTED', got '{webhook['request_encoding']}'")
if 'request_prefix' in webhook:
if not isinstance(webhook['request_prefix'], str):
raise ConfigError(f"Field 'site.outage_webhooks[{i}].request_prefix' must be a string")
if 'request_suffix' in webhook:
if not isinstance(webhook['request_suffix'], str):
raise ConfigError(f"Field 'site.outage_webhooks[{i}].request_suffix' must be a string")
# Validate optional site.max_threads
if 'max_threads' in site:
if not isinstance(site['max_threads'], int) or site['max_threads'] < 1:
raise ConfigError("Field 'site.max_threads' must be a positive integer")
if 'max_retries' in site:
if not isinstance(site['max_retries'], int) or site['max_retries'] < 1:
raise ConfigError("Field 'site.max_retries' must be a positive integer")
if 'max_try_secs' in site:
if not isinstance(site['max_try_secs'], int) or site['max_try_secs'] < 1:
raise ConfigError("Field 'site.max_try_secs' must be a positive integer")
if 'check_every_n_secs' in site:
if not isinstance(site['check_every_n_secs'], int) or site['check_every_n_secs'] < 1:
raise ConfigError("Field 'site.check_every_n_secs' must be a positive integer")
if 'notify_every_n_secs' in site:
if not isinstance(site['notify_every_n_secs'], int) or site['notify_every_n_secs'] < 1:
raise ConfigError("Field 'site.notify_every_n_secs' must be a positive integer")
if 'after_every_n_notifications' in site:
if not isinstance(site['after_every_n_notifications'], int) or site['after_every_n_notifications'] < 1:
raise ConfigError("Field 'site.after_every_n_notifications' must be a positive integer")
if 'alarms' in site:
try:
to_natural_language_boolean(site['alarms'])
except ValueError as e:
raise ConfigError(f"Field 'site.alarms': {e}")
valid_site_params = {
'name', 'email_server', 'outage_emails', 'outage_webhooks', 'max_threads', 'max_retries',
'max_try_secs', 'check_every_n_secs', 'notify_every_n_secs', 'after_every_n_notifications',
'alarms'
}
unrecognized_site = set(site.keys()) - valid_site_params
if unrecognized_site:
raise ConfigError(f"Unrecognized site-level parameters: {', '.join(sorted(unrecognized_site))}")
if 'monitors' not in config:
raise ConfigError("Missing required field: 'monitors'")
if not isinstance(config['monitors'], list):
raise ConfigError("Field 'monitors' must be a list")
if len(config['monitors']) == 0:
raise ConfigError("Field 'monitors' must contain at least one monitor")
monitor_names = set()
for i, monitor in enumerate(config['monitors']):
if not isinstance(monitor, dict):
raise ConfigError(f"Monitor {i}: must be a dictionary")
required_fields = ['type', 'name', 'address']
for field in required_fields:
if field not in monitor:
raise ConfigError(
f"Monitor {i} (name: {monitor.get('name', 'unknown')}): missing required field '{field}'")
valid_monitor_params = {
'type', 'name', 'address', 'check_every_n_secs', 'notify_every_n_secs',
'notify_on_down_every_n_secs', 'after_every_n_notifications', 'heartbeat_url',
'heartbeat_every_n_secs', 'expect', 'ssl_fingerprint', 'ignore_ssl_expiry', 'email',
'send', 'content_type', 'community', 'percentile', 'port', 'mac', 'always_up',
'display', 'alarms'
}
unrecognized_monitor = set(monitor.keys()) - valid_monitor_params
if unrecognized_monitor:
raise ConfigError(f"Monitor {i} (name: {monitor.get('name', 'unknown')}): unrecognized parameters: {', '.join(sorted(unrecognized_monitor))}")
if not isinstance(monitor['name'], str):
raise ConfigError(f"Monitor {i} (name: {monitor.get('name', 'unknown')}): 'name' must be a string")
name = monitor['name']
if name in monitor_names:
raise ConfigError(f"Monitor {i} (name: {name}): duplicate monitor name '{name}'")
monitor_names.add(name)
# 'snmp' removed — direct users to 'ports'
valid_types = ['ping', 'http', 'quic', 'tcp', 'udp', 'ports', 'port', 'host', 'switch']
if monitor['type'] == 'snmp':
raise ConfigError(f"Monitor {i} (name: {name}): type 'snmp' is not valid. Did you mean type: ports?")
if monitor['type'] not in valid_types:
raise ConfigError(f"Monitor {i} (name: {monitor.get('name', 'unknown')}): invalid type '{monitor['type']}', must be one of {valid_types}")
if not isinstance(monitor['address'], str):
raise ConfigError(f"Monitor {i} (name: {monitor.get('name', 'unknown')}): 'address' must be a string")
if 'check_every_n_secs' in monitor:
if not isinstance(monitor['check_every_n_secs'], int) or monitor['check_every_n_secs'] < 1:
raise ConfigError(f"Monitor {i} (name: {name}): 'check_every_n_secs' must be a positive integer")
if 'notify_on_down_every_n_secs' in monitor:
if not isinstance(monitor['notify_on_down_every_n_secs'], int) or monitor['notify_on_down_every_n_secs'] < 1:
raise ConfigError(f"Monitor {i} (name: {name}): 'notify_on_down_every_n_secs' must be a positive integer")
if 'check_every_n_secs' in monitor:
if monitor['notify_on_down_every_n_secs'] < monitor['check_every_n_secs']:
raise ConfigError(f"Monitor {i} (name: {name}): 'notify_on_down_every_n_secs' must be >= 'check_every_n_secs'")
if 'after_every_n_notifications' in monitor:
if 'notify_every_n_secs' not in monitor:
raise ConfigError(f"Monitor {i} (name: {name}): 'after_every_n_notifications' can only be specified if 'notify_every_n_secs' is present")
if not isinstance(monitor['after_every_n_notifications'], int) or monitor['after_every_n_notifications'] < 1:
raise ConfigError(f"Monitor {i} (name: {name}): 'after_every_n_notifications' must be a positive integer")
if 'email' in monitor:
try:
to_natural_language_boolean(monitor['email'])
except ValueError as e:
raise ConfigError(f"Monitor {i} (name: {name}): 'email' field: {e}")
if 'display' in monitor:
try:
to_natural_language_boolean(monitor['display'])
except ValueError as e:
raise ConfigError(f"Monitor {i} (name: {name}): 'display' field: {e}")
if 'alarms' in monitor:
try:
to_natural_language_boolean(monitor['alarms'])
except ValueError as e:
raise ConfigError(f"Monitor {i} (name: {name}): 'alarms' field: {e}")
monitor_type = monitor['type']
address = monitor['address']
if monitor_type == 'ping':
ipv4_pattern = r'^(\d{1,3}\.){3}\d{1,3}$'
ipv6_pattern = r'^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$'
hostname_pattern = r'^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$'
if not (re.match(ipv4_pattern, address) or re.match(ipv6_pattern, address) or re.match(hostname_pattern, address)):
raise ConfigError(f"Monitor {i} (name: {name}): 'address' must be a valid hostname, IPv4 or IPv6 address, got '{address}'")
for forbidden in ('expect', 'ssl_fingerprint', 'percentile'):
if forbidden in monitor:
raise ConfigError(f"Monitor {i} (name: {name}): '{forbidden}' field is not valid for ping monitors")
elif monitor_type in ['http', 'quic']:
parsed = urlparse(address)
if not parsed.scheme or not parsed.netloc:
raise ConfigError(f"Monitor {i} (name: {name}): 'address' must be a valid URL with scheme and host, got '{address}'")
if 'expect' in monitor:
if not isinstance(monitor['expect'], str):
raise ConfigError(f"Monitor {i} (name: {name}): 'expect' must be a string")
if len(monitor['expect']) == 0:
raise ConfigError(f"Monitor {i} (name: {name}): 'expect' must not be empty")
if 'ssl_fingerprint' in monitor:
if not isinstance(monitor['ssl_fingerprint'], str):
raise ConfigError(f"Monitor {i} (name: {name}): 'ssl_fingerprint' must be a string")
fingerprint_clean = monitor['ssl_fingerprint'].replace(':', '')
if not re.match(r'^[0-9a-fA-F]+$', fingerprint_clean):
raise ConfigError(f"Monitor {i} (name: {name}): 'ssl_fingerprint' must be a valid hex string")
fp_len = len(fingerprint_clean)
if fp_len == 0 or (fp_len & (fp_len - 1)) != 0:
raise ConfigError(f"Monitor {i} (name: {name}): 'ssl_fingerprint' length must be a power of two (got {fp_len} hex characters)")
if 'percentile' in monitor:
raise ConfigError(f"Monitor {i} (name: {name}): 'percentile' field is only valid for 'ports' monitors")
elif monitor_type in ['tcp', 'udp']:
parsed = urlparse(address)
if monitor_type == 'tcp' and parsed.scheme != 'tcp':
raise ConfigError(f"Monitor {i} (name: {name}): TCP monitor must use 'tcp://' scheme, got '{address}'")
if monitor_type == 'udp' and parsed.scheme != 'udp':
raise ConfigError(f"Monitor {i} (name: {name}): UDP monitor must use 'udp://' scheme, got '{address}'")
if not parsed.netloc:
raise ConfigError(f"Monitor {i} (name: {name}): 'address' must include hostname/IP and port, got '{address}'")
if 'send' in monitor:
if not isinstance(monitor['send'], str):
raise ConfigError(f"Monitor {i} (name: {name}): 'send' must be a string")
if 'content_type' in monitor:
if 'send' not in monitor:
raise ConfigError(f"Monitor {i} (name: {name}): 'content_type' can only be specified if 'send' is present")
valid_content_types = ['text', 'hex', 'base64']
if monitor['content_type'] not in valid_content_types:
raise ConfigError(f"Monitor {i} (name: {name}): 'content_type' must be one of {valid_content_types}, got '{monitor['content_type']}'")
if 'expect' in monitor:
if not isinstance(monitor['expect'], str):
raise ConfigError(f"Monitor {i} (name: {name}): 'expect' must be a string")
if len(monitor['expect']) == 0:
raise ConfigError(f"Monitor {i} (name: {name}): 'expect' must not be empty")
for forbidden in ('ssl_fingerprint', 'percentile'):
if forbidden in monitor:
raise ConfigError(f"Monitor {i} (name: {name}): '{forbidden}' field is not valid for {monitor_type} monitors")
elif monitor_type in ('ports', 'switch'):
# ports: merged snmp metrics + port state/MAC monitoring
parsed = urlparse(address)
if parsed.scheme != 'snmp':
raise ConfigError(f"Monitor {i} (name: {name}): ports monitor must use 'snmp://' scheme, got '{address}'")
if not parsed.netloc:
raise ConfigError(f"Monitor {i} (name: {name}): 'address' must include hostname/IP, got '{address}'")
hostname = parsed.hostname
if hostname:
ipv4_pattern = r'^(\d{1,3}\.){3}\d{1,3}$'
ipv6_pattern = r'^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$'
hostname_pattern = r'^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$'
if not (re.match(ipv4_pattern, hostname) or re.match(ipv6_pattern, hostname) or re.match(hostname_pattern, hostname)):
raise ConfigError(f"Monitor {i} (name: {name}): 'address' hostname must be valid hostname, IPv4 or IPv6 address, got '{hostname}'")
if 'community' in monitor:
if not isinstance(monitor['community'], str):
raise ConfigError(f"Monitor {i} (name: {name}): 'community' must be a string")
if len(monitor['community']) == 0:
raise ConfigError(f"Monitor {i} (name: {name}): 'community' must not be empty")
if 'percentile' in monitor:
if not isinstance(monitor['percentile'], int) or not (1 <= monitor['percentile'] <= 99):
raise ConfigError(f"Monitor {i} (name: {name}): 'percentile' must be an integer between 1 and 99")
for forbidden in ('expect', 'ssl_fingerprint', 'ignore_ssl_expiry', 'send', 'content_type'):
if forbidden in monitor:
raise ConfigError(f"Monitor {i} (name: {name}): '{forbidden}' field not valid for ports monitors")
elif monitor_type == 'host':
parsed = urlparse(address)
if parsed.scheme != 'snmp':
raise ConfigError(f"Monitor {i} (name: {name}): host monitor must use 'snmp://' scheme, got '{address}'")
if not parsed.netloc:
raise ConfigError(f"Monitor {i} (name: {name}): 'address' must include hostname/IP, got '{address}'")
hostname = parsed.hostname
if hostname:
ipv4_pattern = r'^(\d{1,3}\.){3}\d{1,3}$'
ipv6_pattern = r'^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$'
hostname_pattern = r'^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$'
if not (re.match(ipv4_pattern, hostname) or re.match(ipv6_pattern, hostname) or re.match(hostname_pattern, hostname)):
raise ConfigError(f"Monitor {i} (name: {name}): 'address' hostname must be valid hostname, IPv4 or IPv6 address, got '{hostname}'")
if 'community' in monitor:
if not isinstance(monitor['community'], str):
raise ConfigError(f"Monitor {i} (name: {name}): 'community' must be a string")
if len(monitor['community']) == 0:
raise ConfigError(f"Monitor {i} (name: {name}): 'community' must not be empty")
for forbidden in ('expect', 'ssl_fingerprint', 'ignore_ssl_expiry', 'send', 'content_type', 'percentile'):
if forbidden in monitor:
raise ConfigError(f"Monitor {i} (name: {name}): '{forbidden}' field not valid for host monitors")
elif monitor_type == 'port':
parsed = urlparse(address)
if parsed.scheme != 'snmp':
raise ConfigError(f"Monitor {i} (name: {name}): port monitor must use 'snmp://' scheme, got '{address}'")
if not parsed.netloc:
raise ConfigError(f"Monitor {i} (name: {name}): 'address' must include hostname/IP, got '{address}'")
hostname = parsed.hostname
if hostname:
ipv4_pattern = r'^(\d{1,3}\.){3}\d{1,3}$'
ipv6_pattern = r'^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$'
hostname_pattern = r'^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$'
if not (re.match(ipv4_pattern, hostname) or re.match(ipv6_pattern, hostname) or re.match(hostname_pattern, hostname)):
raise ConfigError(f"Monitor {i} (name: {name}): 'address' hostname must be valid hostname, IPv4 or IPv6 address, got '{hostname}'")
if 'port' not in monitor:
raise ConfigError(f"Monitor {i} (name: {name}): 'port' (ifIndex) is required for port monitors")
if not isinstance(monitor['port'], int) or monitor['port'] < 0:
raise ConfigError(f"Monitor {i} (name: {name}): 'port' must be a non-negative integer (ifIndex)")
if 'mac' not in monitor:
raise ConfigError(f"Monitor {i} (name: {name}): 'mac' (pinned MAC address) is required for port monitors")
if not isinstance(monitor['mac'], str):
raise ConfigError(f"Monitor {i} (name: {name}): 'mac' must be a string")
if not re.match(r'^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$', monitor['mac']):
raise ConfigError(f"Monitor {i} (name: {name}): 'mac' must be a valid MAC address (XX:XX:XX:XX:XX:XX), got '{monitor['mac']}'")
if 'always_up' in monitor:
try:
to_natural_language_boolean(monitor['always_up'])
except ValueError as e:
raise ConfigError(f"Monitor {i} (name: {name}): 'always_up' field: {e}")
if 'community' in monitor:
if not isinstance(monitor['community'], str):
raise ConfigError(f"Monitor {i} (name: {name}): 'community' must be a string")
if len(monitor['community']) == 0:
raise ConfigError(f"Monitor {i} (name: {name}): 'community' must not be empty")
for forbidden in ('expect', 'ssl_fingerprint', 'ignore_ssl_expiry', 'send', 'content_type', 'percentile'):
if forbidden in monitor:
raise ConfigError(f"Monitor {i} (name: {name}): '{forbidden}' field not valid for port monitors")
if 'heartbeat_url' in monitor:
if not isinstance(monitor['heartbeat_url'], str):
raise ConfigError(f"Monitor {i} (name: {name}): 'heartbeat_url' must be a string")
parsed_heartbeat = urlparse(monitor['heartbeat_url'])
if not parsed_heartbeat.scheme or not parsed_heartbeat.netloc:
raise ConfigError(f"Monitor {i} (name: {name}): 'heartbeat_url' must be a valid URL with scheme and host, got '{monitor['heartbeat_url']}'")
if 'heartbeat_every_n_secs' in monitor:
if 'heartbeat_url' not in monitor:
raise ConfigError(f"Monitor {i} (name: {name}): 'heartbeat_every_n_secs' can only be specified if 'heartbeat_url' is present")
if not isinstance(monitor['heartbeat_every_n_secs'], int) or monitor['heartbeat_every_n_secs'] < 1:
raise ConfigError(f"Monitor {i} (name: {name}): 'heartbeat_every_n_secs' must be a positive integer")
if 'ignore_ssl_expiry' in monitor:
if monitor_type not in ['http', 'quic']:
raise ConfigError(f"Monitor {i} (name: {name}): 'ignore_ssl_expiry' field is only valid for 'http' and 'quic' monitors")
try:
to_natural_language_boolean(monitor['ignore_ssl_expiry'])
except ValueError as e:
raise ConfigError(f"Monitor {i} (name: {name}): 'ignore_ssl_expiry' field: {e}")
except ConfigError as e:
print(str(e), file=sys.stderr)
sys.exit(1)
def check_http_url_resource(
url: str,
name: str,
ssl_fingerprint: Optional[str],
ignore_ssl_expiry: bool,
send_data: Optional[str] = None,
content_type: Optional[str] = None) \
-> Tuple[Optional[str], Optional[int], Any, Optional[str]]:
"""Perform HTTP/S request and return None if OK, error message if failed."""
prefix = getattr(thread_local, 'prefix', '')
error_msg = None
# parse the url and don't proceed if it's not pure HTTP/S
parsed = urlparse(url)
if parsed.scheme not in ('http', 'https'):
error_msg = f"{parsed.scheme.upper()} protocol not supported for HTTP, use http or https"
print(f"{prefix}HTTP/S check FAILED for '{name}' at '{url}': {error_msg}", file=sys.stderr)
return error_msg, None, None, None
# calculate is_ssl
is_ssl = parsed.scheme == 'https'
# Determine if we need to verify SSL
if is_ssl and (ssl_fingerprint or not ignore_ssl_expiry):
hostname = parsed.hostname
port = parsed.port or 443
try:
# Get server certificate
cert_pem = ssl.get_server_certificate((hostname, port))
cert_der = ssl.PEM_cert_to_DER_cert(cert_pem)
# Check fingerprint if provided
if ssl_fingerprint:
server_fingerprint = hashlib.sha256(cert_der).hexdigest()
expected_fingerprint = ssl_fingerprint.replace(':', '').lower()
if server_fingerprint != expected_fingerprint:
error_msg = f"SSL fingerprint mismatch"
if VERBOSE:
print(f"{prefix}SSL fingerprint check FAILED for '{name}': expected {expected_fingerprint}, got {server_fingerprint}")
print(f"{prefix}HTTP/S check FAILED for '{name}' at '{url}': {error_msg}", file=sys.stderr)
return error_msg, None, None, None
if VERBOSE:
print(f"{prefix}SSL fingerprint check PASSED for '{name}'")
# Check certificate expiry unless ignored
if not ignore_ssl_expiry:
try:
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_pem)
not_after_asn1 = x509.get_notAfter()
if VERBOSE > 1:
print(f"{prefix}DEBUG: notAfter raw (ASN1) = {not_after_asn1}")
if not not_after_asn1:
error_msg = "Certificate has no expiry date"
print(f"{prefix}HTTP/S check FAILED for '{name}' at '{url}': {error_msg}", file=sys.stderr)
return error_msg, None, None, None
not_after_str = not_after_asn1.decode('ascii')
not_after = datetime.strptime(not_after_str, '%Y%m%d%H%M%SZ')
if datetime.now() > not_after:
error_msg = f"SSL certificate expired on {not_after}"
if VERBOSE:
print(f"{prefix}SSL certificate expiry check FAILED for '{name}': expired on {not_after}")
print(f"{prefix}HTTP/S check FAILED for '{name}' at '{url}': SSL certificate expired", file=sys.stderr)
return error_msg, None, None, None
if VERBOSE:
print(f"{prefix}SSL certificate expiry check PASSED for '{name}': valid until {not_after}")
except Exception as e:
error_msg = f"Certificate parsing error: {e}"
print(f"{prefix}HTTP/S check FAILED for '{name}' at '{url}': {error_msg}", file=sys.stderr)
return error_msg, None, None, None
elif VERBOSE:
print(f"{prefix}SSL certificate expiry check SKIPPED for '{name}' (ignore_ssl_expiry=True)")
except Exception as e:
error_msg = f"{type(e).__name__}: {e}"
print(f"{prefix}HTTP/S check FAILED for '{name}' at '{url}': {error_msg}", file=sys.stderr)
return error_msg, None, None, None
# Certificate checks passed, proceed with verification disabled (we already validated)
verify_ssl = False
elif is_ssl:
# HTTPS but no certificate checks requested, use standard verification
verify_ssl = not IGNORE_SSL_ERRORS
else:
# HTTP - no SSL verification
verify_ssl = False
try:
# Determine request method and prepare data
if send_data:
# POST request with data
# Send data as UTF-8 encoded bytes
data_to_send = send_data.encode('utf-8')
# Use provided content_type or default to text/plain
headers = {'Content-Type': content_type if content_type else 'text/plain; charset=utf-8'}
if VERBOSE:
print(f"{prefix}HTTP/S POST sending {len(data_to_send)} bytes to '{name}' at '{url}' (Content-Type: {headers['Content-Type']})")
response = requests.post(url, data=data_to_send, headers=headers, timeout=MAX_TRY_SECS, verify=verify_ssl)
else:
# GET request (original behavior)
response = requests.get(url, timeout=MAX_TRY_SECS, verify=verify_ssl)
# Return response details for expect checking
return None, response.status_code, response.headers, response.text
except requests.exceptions.RequestException as e:
# Extract the root cause from nested exceptions (check both __cause__ and __context__)
root_cause = e
while True:
next_cause = getattr(root_cause, '__cause__', None) or getattr(root_cause, '__context__', None)
if next_cause is None or next_cause == root_cause:
break
root_cause = next_cause
error_msg = f"{type(root_cause).__name__}: {root_cause}"
print(f"{prefix}HTTP/S check FAILED for '{name}' at '{url}': {error_msg}", file=sys.stderr)
return error_msg, None, None, None
def check_quic_url_resource(
url: str,
name: str,
ssl_fingerprint: Optional[str],
ignore_ssl_expiry: bool,
send_data: Optional[str] = None,
content_type: Optional[str] = None) \
-> Tuple[Optional[str], Optional[int], Any, Optional[str]]:
"""Perform QUIC/HTTP3 request and return None if OK, error message if failed."""
import asyncio
prefix = getattr(thread_local, 'prefix', '')
async def _check_quic_url_async():
"""Async implementation of QUIC/HTTP3 check."""
from aioquic.asyncio.client import connect
from aioquic.asyncio.protocol import QuicConnectionProtocol
from aioquic.h3.connection import H3_ALPN
from aioquic.h3.events import HeadersReceived, DataReceived, H3Event
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.events import QuicEvent
import OpenSSL.crypto
error_msg = None
# Parse the URL and check scheme
parsed = urlparse(url)
if parsed.scheme not in ('https', 'quic'):
error_msg = f"{parsed.scheme.upper()} protocol not supported for QUIC, use https or quic"
print(f"{prefix}QUIC check FAILED for '{name}' at '{url}': {error_msg}", file=sys.stderr)
return error_msg, None, None, None
hostname = parsed.hostname
port = parsed.port or 443
path = parsed.path or '/'
if parsed.query:
path = f"{path}?{parsed.query}"
# Configure QUIC connection with timeout
configuration = QuicConfiguration(
alpn_protocols=H3_ALPN,
is_client=True,
verify_mode=ssl.CERT_NONE if (ssl_fingerprint or ignore_ssl_expiry) else ssl.CERT_REQUIRED,
idle_timeout=MAX_TRY_SECS
)
# Storage for response
response_headers = None
response_data = b""
response_complete = asyncio.Event()
# Custom protocol to handle HTTP/3 events
class HttpClientProtocol(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
from aioquic.h3.connection import H3Connection
self._http = H3Connection(self._quic)
def quic_event_received(self, event: QuicEvent):
nonlocal response_headers, response_data
# Pass QUIC event to HTTP/3 layer
for h3_event in self._http.handle_event(event):
if isinstance(h3_event, HeadersReceived):
response_headers = h3_event.headers
if VERBOSE > 2:
print(f"{prefix}DEBUG: Received headers: {response_headers}")
elif isinstance(h3_event, DataReceived):
response_data += h3_event.data
if VERBOSE > 2:
print(f"{prefix}DEBUG: Received {len(h3_event.data)} bytes, stream_ended={h3_event.stream_ended}, total={len(response_data)}")
if h3_event.stream_ended:
response_complete.set()
try:
# Establish QUIC connection with custom protocol and timeout
async with asyncio.timeout(MAX_TRY_SECS):
async with connect(
hostname,
port,
configuration=configuration,
create_protocol=HttpClientProtocol,
) as protocol:
# Get the peer certificate
quic = protocol._quic
tls = quic.tls
# Extract certificate from TLS connection
if tls and hasattr(tls, 'peer_certificate'):
peer_cert_der = tls.peer_certificate
if peer_cert_der:
# Check fingerprint if provided
if ssl_fingerprint:
server_fingerprint = hashlib.sha256(peer_cert_der).hexdigest()
expected_fingerprint = ssl_fingerprint.replace(':', '').lower()
if server_fingerprint != expected_fingerprint:
error_msg = f"SSL fingerprint mismatch"
if VERBOSE:
print(f"{prefix}SSL fingerprint check FAILED for '{name}': expected {expected_fingerprint}, got {server_fingerprint}")
print(f"{prefix}QUIC check FAILED for '{name}' at '{url}': {error_msg}", file=sys.stderr)
return error_msg, None, None, None
if VERBOSE:
print(f"{prefix}SSL fingerprint check PASSED for '{name}'")
# Check certificate expiry unless ignored
if not ignore_ssl_expiry:
try:
# Convert DER to PEM for OpenSSL
cert_pem = ssl.DER_cert_to_PEM_cert(peer_cert_der)
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_pem)
not_after_asn1 = x509.get_notAfter()
if VERBOSE > 1:
print(f"{prefix}DEBUG: notAfter raw (ASN1) = {not_after_asn1}")
if not not_after_asn1:
error_msg = "Certificate has no expiry date"
print(f"{prefix}QUIC check FAILED for '{name}' at '{url}': {error_msg}", file=sys.stderr)
return error_msg, None, None, None
not_after_str = not_after_asn1.decode('ascii')
not_after = datetime.strptime(not_after_str, '%Y%m%d%H%M%SZ')
if datetime.now() > not_after:
error_msg = f"SSL certificate expired on {not_after}"
if VERBOSE:
print(f"{prefix}SSL certificate expiry check FAILED for '{name}': expired on {not_after}")
print(f"{prefix}QUIC check FAILED for '{name}' at '{url}': SSL certificate expired", file=sys.stderr)
return error_msg, None, None, None
if VERBOSE:
print(f"{prefix}SSL certificate expiry check PASSED for '{name}': valid until {not_after}")
except Exception as e:
error_msg = f"Certificate parsing error: {e}"
print(f"{prefix}QUIC check FAILED for '{name}' at '{url}': {error_msg}", file=sys.stderr)
return error_msg, None, None, None
elif VERBOSE:
print(f"{prefix}SSL certificate expiry check SKIPPED for '{name}' (ignore_ssl_expiry=True)")
# Access HTTP/3 connection from protocol
http = protocol._http
# Get next available stream ID
stream_id = quic.get_next_available_stream_id()
# Determine method and prepare data