matrix-alertbot/matrix_alertbot/matcher.py

36 lines
1,000 B
Python
Raw Normal View History

2022-07-10 02:40:04 +02:00
import re
from typing import Any, Dict
2022-07-10 12:51:49 +02:00
class AlertMatcher:
def __init__(self, label: str, value: str) -> None:
2022-07-10 02:40:04 +02:00
self.label = label
self.value = value
def match(self, labels: Dict[str, str]) -> bool:
2022-07-10 12:51:49 +02:00
return self.label in labels and self.value == labels[self.label]
2022-07-10 02:40:04 +02:00
def __str__(self) -> str:
2022-07-10 12:51:49 +02:00
return f"{self.label}={self.value}"
2022-07-10 02:40:04 +02:00
2022-07-10 12:51:49 +02:00
def __repr__(self) -> str:
return f"AlertMatcher({self})"
2022-07-10 02:40:04 +02:00
2022-07-10 12:51:49 +02:00
def __eq__(self, matcher: Any) -> bool:
return str(self) == str(matcher)
2022-07-10 02:40:04 +02:00
2022-07-10 12:51:49 +02:00
class AlertRegexMatcher(AlertMatcher):
2022-07-10 02:40:04 +02:00
def __init__(self, label: str, regex: str) -> None:
2022-07-10 12:51:49 +02:00
super().__init__(label, regex)
2022-07-10 02:40:04 +02:00
self.regex = re.compile(regex)
2022-07-10 12:51:49 +02:00
def __str__(self) -> str:
return f"{self.label}=~{self.value}"
def __repr__(self) -> str:
return f"AlertRegexMatcher({self})"
2022-07-10 02:40:04 +02:00
def match(self, labels: Dict[str, str]) -> bool:
return self.label in labels and self.regex.match(labels[self.label]) is not None