Allow rejecting labels and areas

This commit is contained in:
Adam Goldsmith 2024-12-30 10:26:45 -05:00
parent 9035396156
commit a451d63149

View File

@ -9,7 +9,7 @@ import logging
import re import re
import sys import sys
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any, Literal
from urllib.parse import urljoin from urllib.parse import urljoin
import nagiosplugin import nagiosplugin
@ -148,6 +148,16 @@ class Entities(nagiosplugin.Resource):
max=self.max, max=self.max,
) )
@staticmethod
def _parse_negatable(filter: str) -> tuple[Literal["select", "reject"], str]:
if filter.startswith("!"):
filter = filter[1:]
op = "reject"
else:
op = "select"
return op, filter
def probe(self): def probe(self):
template_filter = "states" template_filter = "states"
if self.domain: if self.domain:
@ -163,12 +173,14 @@ class Entities(nagiosplugin.Resource):
) )
if self.area: if self.area:
op, area = self._parse_negatable(self.area)
template_filter += ( template_filter += (
f"|selectattr('entity_id', 'in', area_entities('{ self.area }'))" f"|{op}attr('entity_id', 'in', area_entities('{ area }'))"
) )
if self.label: if self.label:
op, label = self._parse_negatable(self.label)
template_filter += ( template_filter += (
f"|selectattr('entity_id', 'in', label_entities('{ self.label }'))" f"|{op}attr('entity_id', 'in', label_entities('{ label }'))"
) )
if self.exclude: if self.exclude:
@ -387,8 +399,12 @@ def main():
action="extend", action="extend",
help="explicitly include entities by id. Other entities will not be considered if this is specified. Listed entities must also match the specified device class", help="explicitly include entities by id. Other entities will not be considered if this is specified. Listed entities must also match the specified device class",
) )
common_args.add_argument("--area", type=str, help="area to filter by") common_args.add_argument(
common_args.add_argument("--label", type=str, help="label to filter by") "--area", type=str, help="area to filter by. '!' before negates"
)
common_args.add_argument(
"--label", type=str, help="label to filter by. '!' before negates"
)
common_args.add_argument( common_args.add_argument(
"-e", "-e",
"--exclude", "--exclude",