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") _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 @dataclasses.dataclass
class Entities(nagiosplugin.Resource): class Entities(nagiosplugin.Resource):
url: str url: str
@ -56,16 +73,14 @@ class Entities(nagiosplugin.Resource):
state["attributes"].get(k) == v for k, v in self.filters state["attributes"].get(k) == v for k, v in self.filters
): ):
if self.attribute is not None: if self.attribute is not None:
value = state["attributes"].get( value = state["attributes"].get(self.attribute, "missing attribute")
self.attribute, -1 if self.numeric else "attribute missing"
)
uom = None uom = None
else: else:
if self.numeric: if self.numeric:
try: try:
value = float(state["state"]) value = float(state["state"])
except ValueError: except ValueError:
value = -1 value = state["state"]
else: else:
value = state["state"] value = state["state"]
uom = state["attributes"].get("unit_of_measurement") uom = state["attributes"].get("unit_of_measurement")
@ -79,8 +94,6 @@ class Entities(nagiosplugin.Resource):
else: else:
name = state["entity_id"] name = state["entity_id"]
if state["state"] == "unavailable":
_log.info(f"{state['entity_id']} unavailable")
yield nagiosplugin.Metric( yield nagiosplugin.Metric(
name, name,
value, value,
@ -340,7 +353,7 @@ def main():
attribute=args.attribute, attribute=args.attribute,
friendly_name=args.friendly, 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": elif args.subparser_name == "text":
check = nagiosplugin.Check( check = nagiosplugin.Check(