forked from Checkmk/checkmk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3631 lines (3199 loc) · 149 KB
/
Copy pathmain.py
File metadata and controls
3631 lines (3199 loc) · 149 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
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.
# TODO: Refactor/document locking. It is not clear when and how to apply
# locks or when they are held by which component.
# TODO: Refactor events to be handled as objects, e.g. in case when
# creating objects. Or at least update the documentation. It is not clear
# which fields are mandatory for the events.
from __future__ import annotations
import abc
import ast
import contextlib
import errno
import ipaddress
import itertools
import json
import logging
import os
import pprint
import select
import signal
import socket
import sys
import threading
import time
import traceback
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from logging import DEBUG, getLogger, Logger
from pathlib import Path
from types import FrameType
from typing import Any, assert_never, ClassVar, IO, Literal, TypedDict
from setproctitle import setthreadtitle
import cmk.ccc.daemon
import cmk.ccc.profile
from cmk.ccc.crash_reporting import ABCCrashReport, CrashReportStore, make_crash_report_base_path
from cmk.ccc.exceptions import MKException
from cmk.ccc.hostaddress import HostAddress, HostName
from cmk.ccc.site import omd_site, SiteId
from cmk.ccc.translations import translate
from cmk.ccc.version import get_general_version_infos
from cmk.livestatus_client import LocalConnection
from .actions import do_event_action, do_event_actions, do_notify, event_has_opened
from .config import (
Config,
ConfigFromWATO,
Count,
ECRulePack,
Expect,
ExpectInterval,
MatchGroups,
Rule,
)
from .core_queries import Connection, HostInfo, query_hosts_scheduled_downtime_depth
from .event import create_events_from_syslog_messages, Event, scrub_string
from .helpers import ECLock, parse_bytes_into_syslog_messages
from .history import ActiveHistoryPeriod, get_logfile, History, HistoryWhat, quote_tab, TimedHistory
from .history_file import FileHistory
from .history_mongo import MongoDBHistory
from .history_sqlite import SQLiteHistory, SQLiteSettings
from .host_config import HostConfig
from .log_level import VERBOSE, verbosity_to_log_level
from .perfcounters import Perfcounters
from .query import (
Columns,
filter_operator_in,
MKClientError,
Query,
QueryCOMMAND,
QueryGET,
QueryREPLICATE,
StatusTable,
)
from .rule_matcher import compile_rule, match, MatchFailure, MatchResult, MatchSuccess, RuleMatcher
from .rule_packs import load_active_config
from .settings import create_settings, FileDescriptor, PortNumber, Settings
from .snmp import SNMPTrapParser
from .syslog import SyslogFacility, SyslogPriority
from .timeperiod import TimePeriods
def open_log(log_file_path: Path) -> None:
try:
logfile: IO[str] = log_file_path.open("a", encoding="utf-8")
except Exception as e:
getLogger("cmk.mkeventd").exception("Cannot open log file '%s': %s", log_file_path, e)
logfile = sys.stderr
setup_logging_handler(logfile)
def setup_logging_handler(stream: IO[str]) -> None:
"""This method enables all log messages to be written to the given
stream file object. The messages are formatted in Check_MK standard
logging format.
"""
handler = logging.StreamHandler(stream=stream)
handler.setFormatter(logging.Formatter("%(asctime)s [%(levelno)s] [%(name)s] %(message)s"))
logger = logging.getLogger("cmk")
del logger.handlers[:] # Remove all previously existing handlers
logger.addHandler(handler)
class PackedEventStatus(TypedDict):
next_event_id: int
events: list[Event]
rule_stats: dict[str, int]
interval_starts: dict[str, int]
class SlaveStatus(TypedDict):
last_master_down: float | None
last_sync: float
mode: Literal["master", "sync", "takeover"]
success: bool
FileDescr = int # mypy calls this FileDescriptor, but this clashes with our definition
Response = Iterable[Sequence[object]] | Mapping[str, object] | None
LimitKind = Literal["overall", "by_rule", "by_host"]
# .
# .--Helper functions----------------------------------------------------.
# | _ _ _ |
# | | | | | ___| |_ __ ___ _ __ ___ |
# | | |_| |/ _ \ | '_ \ / _ \ '__/ __| |
# | | _ | __/ | |_) | __/ | \__ \ |
# | |_| |_|\___|_| .__/ \___|_| |___/ |
# | |_| |
# +----------------------------------------------------------------------+
# | Various helper functions |
# '----------------------------------------------------------------------'
class ECServerThread(threading.Thread):
@abc.abstractmethod
def serve(self) -> None:
raise NotImplementedError
def __init__(
self,
name: str,
logger: Logger,
settings: Settings,
config: Config,
slave_status: SlaveStatus,
profiling_enabled: bool,
profile_file: Path,
) -> None:
super().__init__(name=name)
self.settings = settings
self._config = config
self._slave_status = slave_status
self._profiling_enabled = profiling_enabled
self._profile_file = profile_file
self._terminate_event = threading.Event()
self._logger = logger
def run(self) -> None:
self._logger.info("Starting up")
setthreadtitle(self.name)
while not self._terminate_event.is_set():
try:
with cmk.ccc.profile.Profile(
enabled=self._profiling_enabled, profile_file=str(self._profile_file)
):
self.serve()
except Exception:
self._logger.exception("Exception in %s server", self.name)
if self.settings.options.debug:
raise
time.sleep(1)
self._logger.info("Terminated")
def terminate(self) -> None:
self._terminate_event.set()
def create_history_raw(
settings: Settings,
config: Config,
logger: Logger,
event_columns: Columns,
history_columns: Columns,
) -> History:
"""Factory for History objects based on the current configuration."""
match config["archive_mode"]:
case "file":
return FileHistory(settings, config, logger, event_columns, history_columns)
case "mongodb":
return MongoDBHistory(settings, config, logger, event_columns, history_columns)
case "sqlite":
return SQLiteHistory(
SQLiteSettings.from_settings(
settings=settings,
database=Path(settings.paths.history_dir.value / "history.sqlite"),
),
config,
logger,
event_columns,
history_columns,
)
case _ as default:
assert_never(default)
def create_history(
settings: Settings,
config: Config,
logger: Logger,
event_columns: Columns,
history_columns: Columns,
) -> History:
"""Factory for History objects based on the current configuration, optionally augmented with timing information."""
history_logger = logger.getChild("EventStatus")
history = create_history_raw(settings, config, history_logger, event_columns, history_columns)
return TimedHistory(history, history_logger) if history_logger.isEnabledFor(DEBUG) else history
def allowed_ip(
ip: ipaddress.IPv6Address | ipaddress.IPv4Address,
access_list: Iterable[ipaddress.IPv6Network | ipaddress.IPv4Network],
) -> bool:
"""
Checks if ip is in the access_list.
Takes care of mapped ipv6->ipv4 and ipv4->mapped_ipv6.
This is needed because the access_list could contain ipv4/ipv6/ipv6mapped.
"""
if any(ip in entry for entry in access_list):
return True
if not str(ip).startswith("::ffff:"):
if any(ipaddress.ip_address(f"::ffff:{str(ip)}") in entry for entry in access_list):
return True
if isinstance(ip, ipaddress.IPv6Address):
return any(ip.ipv4_mapped in entry for entry in access_list)
return False
def unmap_ipv4_address(ip_address: str) -> str:
"""
Accepts addresses with ipv4_mapped hosts and
returns unmapped ipv4.
>>> unmap_ipv4_address('::FFFF:192.0.2.128')
'192.0.2.128'
"""
with contextlib.suppress(ValueError): # in case address[0] is a hostname
host = ipaddress.ip_address(ip_address)
if host.version == 6 and host.ipv4_mapped:
return str(host.ipv4_mapped)
return ip_address
def parse_address(what: str, address: object) -> tuple[str, int]:
# We always have an AF_INET or AF_INET6 socket, so the remote address we're dealing with is a
# pair (host: str, port: int), where host can be the domain name or an IPv4/IPv6 address.
if not (
isinstance(address, tuple) and isinstance(address[0], str) and isinstance(address[1], int)
):
raise ValueError(f"Invalid remote address '{address!r}' for {what}")
return unmap_ipv4_address(address[0]), address[1]
def terminate(
terminate_main_event: threading.Event,
event_server: EventServer,
status_server: StatusServer,
) -> None:
terminate_main_event.set()
status_server.terminate()
event_server.terminate()
def bail_out(logger: Logger, reason: str) -> None:
logger.error("FATAL ERROR: %s", reason)
sys.exit(1)
def process_exists(pid: int) -> bool:
try:
os.kill(pid, 0)
return True
except Exception:
return False
def drain_pipe(pipe: FileDescr) -> None:
while True:
try:
readable: list[FileDescr] = select.select([pipe], [], [], 0.1)[0]
except OSError as e:
if e.args[0] != errno.EINTR:
raise
continue
if pipe in readable:
try:
if not os.read(pipe, 4096): # EOF
break
except Exception:
break # Error while reading
else:
break # No data available
def replace_groups(text: str, origtext: str, match_groups: MatchGroups) -> str:
# replace \0 with text itself. This allows to add information
# in front or and the end of a message
text = text.replace("\\0", origtext)
# Generic replacement with \1, \2, ...
match_groups_message = match_groups.get("match_groups_message", False)
if match_groups_message is not False:
for nr, g in enumerate(match_groups_message):
text = text.replace(f"\\{nr + 1}", g)
# Replacement with keyword
# Right now we have
# $MATCH_GROUPS_MESSAGE_x$
# $MATCH_GROUPS_SYSLOG_APPLICATION_x$
for key_prefix, values in match_groups.items():
if not isinstance(values, tuple):
continue
for idx, match_value in enumerate(values):
text = text.replace(f"${key_prefix.upper()}_{idx + 1}$", match_value)
return text
class MKSignalException(MKException):
def __init__(self, signum: int) -> None:
MKException.__init__(self, f"Got signal {signum}")
self.signum = signum
# .
# .--EventServer---------------------------------------------------------.
# | _____ _ ____ |
# | | ____|_ _____ _ __ | |_/ ___| ___ _ ____ _____ _ __ |
# | | _| \ \ / / _ \ '_ \| __\___ \ / _ \ '__\ \ / / _ \ '__| |
# | | |___ \ V / __/ | | | |_ ___) | __/ | \ V / __/ | |
# | |_____| \_/ \___|_| |_|\__|____/ \___|_| \_/ \___|_| |
# | |
# +----------------------------------------------------------------------+
# | Verarbeitung und Klassifizierung von eingehenden Events. |
# '----------------------------------------------------------------------'
class EventServer(ECServerThread):
"""Processing and classification of incoming events."""
def __init__(
self,
logger: Logger,
settings: Settings,
config: Config,
slave_status: SlaveStatus,
perfcounters: Perfcounters,
lock_configuration: ECLock,
history: History,
event_status: EventStatus,
event_columns: Columns,
connection: Connection,
omd_site: SiteId,
*,
create_pipes_and_sockets: bool = True,
) -> None:
super().__init__(
name="EventServer",
logger=logger,
settings=settings,
config=config,
slave_status=slave_status,
profiling_enabled=settings.options.profile_event,
profile_file=settings.paths.event_server_profile.value,
)
self._syslog_udp: socket.socket | None = None
self._syslog_tcp: socket.socket | None = None
self._snmp_trap_socket: socket.socket | None = None
self._rules: list[Rule] = []
self._rule_by_id: dict[str | None, Rule] = {}
self._rule_hash: dict[int, dict[int, Any]] = {}
self._hash_stats: list[list[int]] = [] # facility/priority
for _unused_facility in range(32):
self._hash_stats.append([0] * 8)
self._connection = connection
self._omd_site = omd_site
self.host_config = HostConfig(self._logger, self._connection)
self._perfcounters = perfcounters
self._lock_configuration = lock_configuration
self._history = history
self._event_status = event_status
self._event_columns = event_columns
self._message_period = ActiveHistoryPeriod()
self._time_period = TimePeriods(self._logger, self._connection)
self._rule_matcher = RuleMatcher(
logger=self._logger if config["debug_rules"] else None,
omd_site_id=self._omd_site,
is_active_time_period=self._time_period.active,
)
# HACK for testing: The real fix would involve breaking up these huge
# class monsters.
if not create_pipes_and_sockets:
return
self.create_pipe()
self.open_eventsocket()
self.open_syslog_udp()
self.open_syslog_tcp()
self.open_snmptrap()
self._snmp_trap_parser = SNMPTrapParser(
self.settings, self._config, self._logger.getChild("snmp")
).parse
@classmethod
def status_columns(cls) -> Columns:
return list(
itertools.chain(
cls._general_columns(),
Perfcounters.status_columns(),
cls._replication_columns(),
cls._event_limit_columns(),
)
)
@classmethod
def _general_columns(cls) -> Columns:
return [
("status_config_load_time", 0),
("status_num_open_events", 0),
("status_virtual_memory_size", 0),
]
@classmethod
def _replication_columns(cls) -> Columns:
return [
("status_replication_slavemode", ""),
("status_replication_last_sync", 0.0),
("status_replication_success", False),
]
@classmethod
def _event_limit_columns(cls) -> Columns:
return [
("status_event_limit_host", 0),
("status_event_limit_rule", 0),
("status_event_limit_overall", 0),
("status_event_limit_active_hosts", []),
("status_event_limit_active_rules", []),
("status_event_limit_active_overall", False),
]
def get_status(self) -> Iterable[Sequence[object]]:
return [
[
*self._add_general_status(),
*self._perfcounters.get_status(),
*self._add_replication_status(),
*self._add_event_limit_status(),
]
]
def _add_general_status(self) -> Sequence[object]:
return [
self._config["last_reload"],
self._event_status.num_existing_events,
self._virtual_memory_size(),
]
def _virtual_memory_size(self) -> int:
parts = Path("/proc/self/stat").read_text().split()
return int(parts[22]) # in Bytes
def _add_replication_status(self) -> list[object]:
if is_replication_slave(self._config):
return [
self._slave_status["mode"],
self._slave_status["last_sync"],
self._slave_status["success"],
]
return ["master", 0.0, False]
def _add_event_limit_status(self) -> list[object]:
return [
self._config["event_limit"]["by_host"]["limit"],
self._config["event_limit"]["by_rule"]["limit"],
self._config["event_limit"]["overall"]["limit"],
self.get_hosts_with_active_event_limit(),
self.get_rules_with_active_event_limit(),
self.is_overall_event_limit_active(),
]
def create_pipe(self) -> None:
path = self.settings.paths.event_pipe.value
with contextlib.suppress(Exception):
if not path.is_fifo():
path.unlink()
if not path.exists():
os.mkfifo(str(path))
# We want to be able to receive events from all users on the local system
path.chmod(0o662)
self._logger.info("Created FIFO '%s' for receiving events", path)
def open_syslog_udp(self) -> None:
endpoint = self.settings.options.syslog_udp
try:
if isinstance(endpoint, FileDescriptor):
try:
self._logger.info("Trying to use ipv6 for syslog-udp from file descriptor")
self._syslog_udp = socket.fromfd(
endpoint.value, socket.AF_INET6, socket.SOCK_DGRAM
)
except OSError:
self._logger.info("Binding ipv6 failed. Falling back to ipv4 for syslog-udp")
self._syslog_udp = socket.fromfd(
endpoint.value, socket.AF_INET, socket.SOCK_DGRAM
)
os.close(endpoint.value)
self._logger.info(
"Opened builtin syslog server on inherited filedescriptor %d", endpoint.value
)
if isinstance(endpoint, PortNumber):
try:
self._logger.info("Trying to use ipv6 for syslog-udp")
self._syslog_udp = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
self._syslog_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self._logger.info("Trying to enable ipv6 dualstack for syslog-udp...")
self._syslog_udp.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
except (AttributeError, OSError):
self._logger.info(
"ipv6 dualstack failed. Continuing in ipv6-only mode for syslog-udp"
)
self._syslog_udp.bind(("::", endpoint.value))
except OSError:
self._logger.info("Binding ipv6 failed. Falling back to ipv4 for syslog-udp")
self._syslog_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._syslog_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._syslog_udp.bind(("0.0.0.0", endpoint.value)) # nosec B104 # BNS:3d8f2a
self._logger.info("Opened builtin syslog server on UDP port %d", endpoint.value)
except Exception as e:
raise Exception("Cannot start builtin syslog server") from e
def open_syslog_tcp(self) -> None:
endpoint = self.settings.options.syslog_tcp
try:
if isinstance(endpoint, FileDescriptor):
try:
self._logger.info("Trying to use ipv6 for syslog-tcp from file descriptor")
self._syslog_tcp = socket.fromfd(
endpoint.value, socket.AF_INET6, socket.SOCK_STREAM
)
except OSError:
self._logger.exception("Binding ipv6 failed. Falling back to ipv4")
self._syslog_tcp = socket.fromfd(
endpoint.value, socket.AF_INET, socket.SOCK_STREAM
)
self._syslog_tcp.listen(20)
os.close(endpoint.value)
self._logger.info(
"Opened builtin syslog-tcp server on inherited filedescriptor %d",
endpoint.value,
)
if isinstance(endpoint, PortNumber):
try:
self._logger.info("Trying to use ipv6 for syslog-tcp")
self._syslog_tcp = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
self._syslog_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self._logger.info("Trying to enable ipv6 dualstack for syslog-tcp...")
self._syslog_tcp.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
except (AttributeError, OSError):
self._logger.info(
"ipv6 dualstack failed. Continuing in ipv6-only mode for syslog-tcp"
)
self._syslog_tcp.bind(("::", endpoint.value))
except OSError:
self._logger.info("Binding ipv6 failed. Falling back to ipv4 for syslog-tcp")
self._syslog_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._syslog_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._syslog_tcp.bind(("0.0.0.0", endpoint.value)) # nosec B104 # BNS:3d8f2a
self._syslog_tcp.listen(20)
self._logger.info("Opened builtin syslog-tcp server on TCP port %d", endpoint.value)
except Exception as e:
raise Exception("Cannot start builtin syslog-tcp server") from e
def open_snmptrap(self) -> None:
endpoint = self.settings.options.snmptrap_udp
try:
if isinstance(endpoint, FileDescriptor):
try:
self._logger.info("Trying to use ipv6 for snmptrap from file descriptor")
self._snmp_trap_socket = socket.fromfd(
endpoint.value, socket.AF_INET6, socket.SOCK_DGRAM
)
except OSError:
self._logger.info("Binding ipv6 failed. Falling back to ipv4 for snmptrap")
self._snmp_trap_socket = socket.fromfd(
endpoint.value, socket.AF_INET, socket.SOCK_DGRAM
)
os.close(endpoint.value)
self._logger.info(
"Opened builtin snmptrap server on inherited filedescriptor %d", endpoint.value
)
if isinstance(endpoint, PortNumber):
try:
self._logger.info("Trying to use ipv6 for snmptrap")
self._snmp_trap_socket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
self._snmp_trap_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self._logger.info("Trying to enable ipv6 dualstack for snmptrap...")
self._snmp_trap_socket.setsockopt(
socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0
)
except (AttributeError, OSError):
self._logger.info(
"ipv6 dualstack failed. Continuing in ipv6-only mode for snmptrap"
)
self._snmp_trap_socket.bind(("::", endpoint.value))
except OSError:
self._logger.info("Binding ipv6 failed. Falling back to ipv4 for snmptrap")
self._snmp_trap_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._snmp_trap_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._snmp_trap_socket.bind(("0.0.0.0", endpoint.value)) # nosec B104 # BNS:3d8f2a
self._logger.info("Opened builtin snmptrap server on UDP port %d", endpoint.value)
except Exception as e:
raise Exception("Cannot start builtin snmptrap server") from e
def open_eventsocket(self) -> None:
path = self.settings.paths.event_socket.value
if path.exists():
path.unlink()
path.parent.mkdir(parents=True, exist_ok=True)
self._eventsocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self._eventsocket.bind(str(path))
path.chmod(0o660)
self._eventsocket.listen(self._config["eventsocket_queue_len"])
self._logger.info("Opened UNIX socket '%s' for receiving events", path)
def open_pipe(self) -> FileDescr:
# Beware: we must open the pipe also for writing. Otherwise
# we will see EOF forever after one writer has finished and
# select() will trigger even if there is no data. A good article
# about this is here:
# http://www.outflux.net/blog/archives/2008/03/09/using-select-on-a-fifo/
return os.open(str(self.settings.paths.event_pipe.value), os.O_RDWR | os.O_NONBLOCK)
def serve(self) -> None:
pipe = self.open_pipe()
# We just read()/recvfrom() these, so we create no new FDs via them.
pipe_and_datagram_sockets = [
f for f in (pipe, self._syslog_udp, self._snmp_trap_socket) if f is not None
]
# We use accept() on these FDs, so we must be careful to avoid creating too many additional
# FDs. We use an arbitrary limit below (less than the usual 1024 FD_SETSIZE limit), so we
# don't accept() any more connections when there are already many of them. Connections get
# queued in the OS queue then, and when that is full, a client will get an error, which is
# the right thing here.
stream_sockets = [f for f in (self._syslog_tcp, self._eventsocket) if f is not None]
client_sockets: dict[FileDescr, tuple[socket.socket, tuple[str, int] | None, bytes]] = {}
select_timeout = 1
unprocessed_pipe_data = b""
while not self._terminate_event.is_set():
try:
readable: list[FileDescr | socket.socket] = select.select(
pipe_and_datagram_sockets
+ (stream_sockets if len(client_sockets) < 900 else [])
+ list(client_sockets.keys()),
[],
[],
select_timeout,
)[0]
except OSError as e:
if e.args[0] != errno.EINTR:
raise
continue
address: tuple[str, int] | None # host/port
# Accept new connection on event unix socket
if self._eventsocket in readable:
client_socket, remote_address = self._eventsocket.accept()
# We have a AF_UNIX socket, so the remote address is a str, which is always ''.
if not (isinstance(remote_address, str) and remote_address == ""):
raise ValueError(
f"Invalid remote address '{remote_address!r}' for event socket"
)
client_sockets[client_socket.fileno()] = (client_socket, None, b"")
# Same for the TCP syslog socket
if self._syslog_tcp is not None and self._syslog_tcp in readable:
client_socket, address = self._syslog_tcp.accept()
client_sockets[client_socket.fileno()] = (
client_socket,
parse_address("syslog socket (TCP)", address),
b"",
)
# Read data from existing event unix socket connections
# NOTE: We modify client_socket in the loop, so we need to copy below!
for fd, (cs, address, previous_data) in list(client_sockets.items()):
if fd in readable:
try:
new_data = cs.recv(4096)
except Exception:
new_data = b""
self._logger.exception("Exception during syslog socket_tcp recv")
if new_data:
messages, unprocessed = parse_bytes_into_syslog_messages(
previous_data + new_data
)
self.process_syslog_messages(messages, address)
client_sockets[fd] = (cs, address, unprocessed)
else: # the other side is gone, no more data will ever come
del client_sockets[fd] # discarding previous_data is OK, it's incomplete
cs.close() # do this *after* the bookkeeping above, close() can throw
# Read data from pipe
if pipe in readable:
try:
unprocessed_pipe_data += os.read(pipe, 4096)
except Exception:
self._logger.exception("General exception during pipe os.read")
messages, unprocessed_pipe_data = parse_bytes_into_syslog_messages(
unprocessed_pipe_data
)
self.process_syslog_messages(messages, None)
# Read events from builtin syslog server
if self._syslog_udp is not None and self._syslog_udp in readable:
message, address = self._syslog_udp.recvfrom(4096)
self.process_syslog_messages(
[message], parse_address("syslog socket (UDP)", address)
)
# Read events from builtin snmptrap server
if self._snmp_trap_socket is not None and self._snmp_trap_socket in readable:
message, address = self._snmp_trap_socket.recvfrom(65535)
self.process_potential_event_instrumented(
self.create_events_from_trap(message, parse_address("SNMP trap", address))
)
if spool_files := sorted(
self.settings.paths.spool_dir.value.glob("[!.]*"), key=lambda x: x.stat().st_mtime
):
self.process_syslog_messages(spool_files[0].read_bytes().splitlines(), None)
spool_files[0].unlink()
select_timeout = 0 # enable fast processing to process further files
else:
select_timeout = 1 # restore default select timeout
def create_events_from_trap(self, data: bytes, address: tuple[str, int]) -> Iterator[Event]:
try:
if varbinds_and_ipaddress := self._snmp_trap_parser(data, address):
yield create_event_from_trap(varbinds_and_ipaddress[0], varbinds_and_ipaddress[1])
except Exception as e:
# NOTE: SNMPTrapParser._handle_unauthenticated_snmptrap() logs more details about what
# went wrong on "verbose" logging level, anyway. We do not log on "info" here to avoid
# possible log spam from a misconfigured/buggy device.
self._logger.debug("skipping unparsable SNMP trap, reason: %s", e)
def process_potential_event_instrumented(self, events: Iterable[Event]) -> None:
"""
Processes incoming data, just a wrapper between the real data and the
handler function to record some statistics etc.
"""
for event in events:
self._perfcounters.count("messages")
before = time.time()
# In replication slave mode (when not took over), ignore all events
if not is_replication_slave(self._config) or self._slave_status["mode"] != "sync":
self.process_potential_event(event)
elif self.settings.options.debug:
self._logger.info("Replication: we are in slave mode, ignoring event")
elapsed = time.time() - before
self._perfcounters.count_time("processing", elapsed)
def process_syslog_messages(
self, messages: Iterable[bytes], address: tuple[str, int] | None
) -> None:
self.process_potential_event_instrumented(
create_events_from_syslog_messages(
messages, address, self._logger if self._config["debug_rules"] else None
)
)
def do_housekeeping(self) -> None:
with self._event_status.lock, self._lock_configuration:
self.hk_handle_event_timeouts()
self.hk_check_expected_messages()
self.hk_cleanup_downtime_events()
self._history.housekeeping()
def hk_cleanup_downtime_events(self) -> None:
"""
For all events that have been created in a host downtime check the host
whether or not it is still in downtime. In case the downtime has ended
archive the events that have been created in a downtime.
"""
host_downtimes: dict[str, bool] = {}
for event in self._event_status.events():
if not event["host_in_downtime"]:
continue # only care about events created in downtime
host_name = HostName("") if event["core_host"] is None else event["core_host"]
try:
in_downtime = host_downtimes[host_name]
except KeyError:
in_downtime = self._is_host_in_downtime(host_name)
host_downtimes[host_name] = in_downtime
if in_downtime:
continue # (still) in downtime, don't delete any event
self._logger.log(
VERBOSE, "Remove event %d (created in downtime, host left downtime)", event["id"]
)
self._event_status.remove_event(event, "AUTODELETE")
def hk_handle_event_timeouts(self) -> None:
"""
1. Automatically delete all events that are in state "counting"
and have not reached the required number of hits and whose
time is elapsed.
2. Automatically delete all events that are in state "open"
and whose lifetime is elapsed.
"""
events_to_delete: list[tuple[Event, HistoryWhat]] = []
events = self._event_status.events()
now = time.time()
for event in events:
rule = self._rule_by_id.get(event["rule_id"])
if event["phase"] == "counting":
# Event belongs to a rule that does not longer exist? It
# will never reach its count. Better delete it.
if not rule:
self._logger.info(
"Deleting orphaned event %d created by obsolete rule %s",
event["id"],
event["rule_id"],
)
event["phase"] = "closed"
events_to_delete.append((event, "ORPHANED"))
elif "count" not in rule and not rule.get("expect"):
self._logger.info(
"Count-based event %d belonging to rule %s: rule does not "
"count/expect anymore. Deleting event.",
event["id"],
event["rule_id"],
)
event["phase"] = "closed"
events_to_delete.append((event, "NOCOUNT"))
# handle counting
elif "count" in rule:
count = rule["count"]
if count.get("algorithm") in {"tokenbucket", "dynabucket"}:
last_token = event.get("last_token", event["first"])
secs_per_token = count["period"] / float(count["count"])
if count["algorithm"] == "dynabucket": # get fewer tokens if count is lower
if event["count"] <= 1:
secs_per_token = count["period"]
else:
secs_per_token *= float(count["count"]) / float(event["count"])
elapsed_secs = now - last_token
new_tokens = int(elapsed_secs / secs_per_token)
if new_tokens:
if self.settings.options.debug:
self._logger.info(
"Rule %s/%s, event %d: got %d new tokens",
rule["pack"],
rule["id"],
event["id"],
new_tokens,
)
event["count"] = max(0, event["count"] - new_tokens)
event["last_token"] = (
last_token + new_tokens * secs_per_token
) # not now! would be unfair
if event["count"] == 0:
self._logger.info(
"Rule %s/%s, event %d: again without allowed rate, dropping event",
rule["pack"],
rule["id"],
event["id"],
)
event["phase"] = "closed"
events_to_delete.append((event, "COUNTFAILED"))
elif event["first"] + count["period"] <= now: # End of period reached
self._logger.info(
"Rule %s/%s: reached only %d out of %d events within %d seconds. "
"Resetting to zero.",
rule["pack"],
rule["id"],
event["count"],
count["count"],
count["period"],
)
event["phase"] = "closed"
events_to_delete.append((event, "COUNTFAILED"))
# Handle delayed actions
elif event["phase"] == "delayed":
delay_until = event.get("delay_until", 0) # should always be present
if now >= delay_until:
self._logger.info(
"Delayed event %d of rule %s is now activated.",
event["id"],
event["rule_id"],
)
event["phase"] = "open"
self._history.add(event, "DELAYOVER")
if rule:
event_has_opened(
self._history,
self.settings,
self._config,
self._logger,
self._connection,
self.host_config,
self._event_columns,
rule,
event,
)
if rule.get("autodelete"):
event["phase"] = "closed"
events_to_delete.append((event, "AUTODELETE"))
else:
self._logger.info(
"Cannot do rule action: rule %s not present anymore.", event["rule_id"]
)
# Handle events with a limited lifetime
elif "live_until" in event and now >= event["live_until"]:
allowed_phases = event.get("live_until_phases", ["open"])
if event["phase"] in allowed_phases:
event["phase"] = "closed"
events_to_delete.append((event, "EXPIRED"))
self._logger.info(
"Lifetime of event %d (rule %s) exceeded. Deleting event.",
event["id"],
event["rule_id"],
)
for event, reason in events_to_delete:
self._event_status.remove_event(event, reason)
def hk_check_expected_messages(self) -> None:
"""
"Expecting"-rules are rules that require one or several
occurrences of a message within a defined time period.
Whenever one period of time has elapsed, we need to check
how many messages have been seen for that rule. If these
are too few, we open an event.
We need to handle to cases:
1. An event for such a rule already exists and is
in the state "counting" -> this can only be the case if
more than one occurrence is required.
2. No event at all exists.
in that case.
"""
now = time.time()
for rule in self._rules:
if expect := rule.get("expect"):
if isinstance(
self._rule_matcher.event_rule_matches_site(rule, event=Event()), MatchFailure
):
continue
interval = expect["interval"]
interval_start = self._event_status.interval_start(rule["id"], interval)
if interval_start >= now:
continue
next_interval_start = self._event_status.clamp_timestamp_to_interval(
interval, interval_start, interval_count=1
)
if next_interval_start > now:
continue
# Interval has been elapsed. Now comes the truth: do we have enough