Handle bad scalar values as undefined rather than -1

This commit is contained in:
Adam Goldsmith 2023-03-10 21:49:35 -05:00
parent 82acfd3718
commit 780edf0423

View File

@ -17,6 +17,23 @@ import nagiosplugin
_log = logging.getLogger("nagiosplugin")
class ScalarOrUnknownContext(nagiosplugin.ScalarContext):
def evaluate(self, metric: nagiosplugin.Metric, resource: nagiosplugin.Resource):
if isinstance(metric.value, (int, float)):
return super().evaluate(metric, resource)
else:
return self.result_cls(nagiosplugin.state.Unknown, "non-scalar value", metric)
def performance(self, metric: nagiosplugin.Metric, resource: nagiosplugin.Resource):
if isinstance(metric.value, (int, float)):
return super().performance(metric, resource)
else:
return nagiosplugin.Performance(
metric.name, "U", metric.uom,
self.warning, self.critical,
metric.min, metric.max)
@dataclasses.dataclass
class Entities(nagiosplugin.Resource):
url: str
@ -56,16 +73,14 @@ class Entities(nagiosplugin.Resource):
state["attributes"].get(k) == v for k, v in self.filters
):
if self.attribute is not None:
value = state["attributes"].get(
self.attribute, -1 if self.numeric else "attribute missing"
)
value = state["attributes"].get(self.attribute, "missing attribute")
uom = None
else:
if self.numeric:
try:
value = float(state["state"])
except ValueError:
value = -1
value = state["state"]
else:
value = state["state"]
uom = state["attributes"].get("unit_of_measurement")
@ -79,8 +94,6 @@ class Entities(nagiosplugin.Resource):
else:
name = state["entity_id"]
if state["state"] == "unavailable":
_log.info(f"{state['entity_id']} unavailable")
yield nagiosplugin.Metric(
name,
value,
@ -340,7 +353,7 @@ def main():
attribute=args.attribute,
friendly_name=args.friendly,
),
nagiosplugin.ScalarContext(args.device_class, args.warning, args.critical),
ScalarOrUnknownContext(args.device_class, args.warning, args.critical),
)
elif args.subparser_name == "text":
check = nagiosplugin.Check(