From b799ee07f593376df00973ecf06b7b1e3db62fa6 Mon Sep 17 00:00:00 2001 From: Leon <82407168+sed-i@users.noreply.github.com> Date: Mon, 27 Nov 2023 11:03:18 -0500 Subject: [PATCH] Fix alerts assignment when event is None (#103) --- src/charm.py | 6 ++++-- tests/unit/test_relation_monitors.py | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/charm.py b/src/charm.py index b0b91a9..4b4eb62 100755 --- a/src/charm.py +++ b/src/charm.py @@ -446,7 +446,7 @@ def _downstream_prometheus_scrape_relation_broken(self, _): self._stored.have_prometheus = False self._set_status() - def _on_nrpe_targets_changed(self, event): + def _on_nrpe_targets_changed(self, event: Optional[NrpeTargetsChangedEvent]): """Send NRPE jobs over to MetricsEndpointAggregator.""" if event and isinstance(event, NrpeTargetsChangedEvent): removed_targets = event.removed_targets @@ -461,9 +461,11 @@ def _on_nrpe_targets_changed(self, event): ) nrpes = cast(List[Dict[str, Any]], event.current_targets) + current_alerts = event.current_alerts else: # If the event arg is None, then the stored state value is already up-to-date. nrpes = self.nrpe_exporter.endpoints() + current_alerts = self.nrpe_exporter.alerts() self._modify_enrichment_file(endpoints=nrpes) @@ -472,7 +474,7 @@ def _on_nrpe_targets_changed(self, event): nrpe["target"], nrpe["app_name"], **nrpe["additional_fields"] ) - for alert in event.current_alerts: + for alert in current_alerts: self.metrics_aggregator.set_alert_rule_data( re.sub(r"/", "_", alert["labels"]["juju_unit"]), alert, diff --git a/tests/unit/test_relation_monitors.py b/tests/unit/test_relation_monitors.py index 124971d..bd9da87 100644 --- a/tests/unit/test_relation_monitors.py +++ b/tests/unit/test_relation_monitors.py @@ -81,3 +81,19 @@ def test_monitors_changed(self): ] ) self.assertEqual(expected, self.mock_enrichment_file.read_text()) + + def test_prometheus(self): + # GIVEN a post-startup charm + self.harness.begin_with_initial_hooks() + + # WHEN "monitors" and "downstream-prometheus-scrape" relations join + rel_id_nrpe = self.harness.add_relation("monitors", "nrpe") + self.harness.add_relation_unit(rel_id_nrpe, "nrpe/0") + self.harness.update_relation_data(rel_id_nrpe, "nrpe/0", self.default_unit_data) + + rel_id_prom = self.harness.add_relation("downstream-prometheus-scrape", "prom") + self.harness.add_relation_unit(rel_id_prom, "prom/0") + + # THEN alert rules are transferred to prometheus over relation data + app_data = self.harness.get_relation_data(rel_id_prom, "cos-proxy") + self.assertIn("alert_rules", app_data)