Skip to content

Commit

Permalink
set relation data on leader elected so alert rules are properly set (#…
Browse files Browse the repository at this point in the history
…277)

* set relation data on leader elected so alert rules are properly set

* Check type in unit test

* data will never be None
  • Loading branch information
dstathis authored May 19, 2022
1 parent 6f2676c commit 95116e6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/charms/prometheus_k8s/v0/prometheus_scrape.py
Original file line number Diff line number Diff line change
Expand Up @@ -1577,6 +1577,9 @@ def __init__(

self.framework.observe(self._charm.on.upgrade_charm, self._set_scrape_job_spec)

# If there is no leader during relation_joined we will still need to set alert rules.
self.framework.observe(self._charm.on.leader_elected, self._set_scrape_job_spec)

def _set_scrape_job_spec(self, event):
"""Ensure scrape target information is made available to prometheus.
Expand Down
23 changes: 23 additions & 0 deletions tests/unit/test_endpoint_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,3 +615,26 @@ def test_unit_label_is_retained_if_hard_coded(self):
for rule in group["rules"]:
self.assertIn("juju_unit", rule["labels"])
self.assertIn("juju_unit=", rule["expr"])


class TestNoLeader(unittest.TestCase):
"""Tests the case where leader is not set immediately."""

def setUp(self):
self.harness = Harness(EndpointProviderCharm, meta=PROVIDER_META)
self.addCleanup(self.harness.cleanup)
self.harness.set_leader(False)
self.harness.begin_with_initial_hooks()

@patch("ops.testing._TestingModelBackend.network_get")
def test_alert_rules(self, _):
"""Verify alert rules are added when leader is elected after the relation is created."""
rel_id = self.harness.add_relation(RELATION_NAME, "provider")
self.harness.add_relation_unit(rel_id, "provider/0")
self.harness.set_leader(True)

data = self.harness.get_relation_data(rel_id, self.harness.model.app.name).get(
"alert_rules"
)
self.assertIsNotNone(data)
self.assertGreater(len(data), 0) # type: ignore[arg-type]

0 comments on commit 95116e6

Please sign in to comment.