Skip to content

Commit

Permalink
Allow static scrape targets without a port set (#332)
Browse files Browse the repository at this point in the history
This commit ensures that Metrics Endpoint Consumer accepts
static scrape targets that do not have a port set.

closes #327
  • Loading branch information
Balbir Thomas authored Jul 22, 2022
1 parent bf15cd4 commit 4b54576
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
22 changes: 21 additions & 1 deletion lib/charms/prometheus_k8s/v0/prometheus_scrape.py
Original file line number Diff line number Diff line change
Expand Up @@ -1128,7 +1128,7 @@ def _labeled_static_job_config(self, job, job_name_prefix, hosts, scrape_metadat
ports = []
unitless_targets = []
for target in all_targets:
host, port = target.split(":")
host, port = self._target_parts(target)
if host.strip() == "*":
ports.append(port.strip())
else:
Expand Down Expand Up @@ -1157,6 +1157,26 @@ def _labeled_static_job_config(self, job, job_name_prefix, hosts, scrape_metadat

return labeled_job

def _target_parts(self, target) -> list:
"""Extract host and port from a wildcard target.
Args:
target: a string specifying a scrape target. A
scrape target is expected to have the format
"host:port". The host part may be a wildcard
"*" and the port part can be missing (along
with ":") in which case port is set to 80.
Returns:
a list with target host and port as in [host, port]
"""
if ":" in target:
parts = target.split(":")
else:
parts = [target, "80"]

return parts

def _set_juju_labels(self, labels, scrape_metadata) -> dict:
"""Create a copy of metric labels with Juju topology information.
Expand Down
33 changes: 33 additions & 0 deletions tests/unit/test_endpoint_consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,39 @@ def test_consumer_overwrites_juju_topology_labels(self):
for label_name, label_value in labels.items():
self.assertNotEqual(label_value, bad_labels[label_name])

def test_consumer_accepts_targets_without_a_port_set(self):
self.assertEqual(self.harness.charm._stored.num_events, 0)

rel_id = self.harness.add_relation(RELATION_NAME, "consumer")
jobs = DEFAULT_JOBS.copy()
jobs[0]["static_configs"] = [
{
"targets": ["*"],
}
]
self.harness.update_relation_data(
rel_id,
"consumer",
{
"scrape_metadata": json.dumps(SCRAPE_METADATA),
"scrape_jobs": json.dumps(jobs),
},
)
self.assertEqual(self.harness.charm._stored.num_events, 1)
self.harness.add_relation_unit(rel_id, "consumer/0")
self.harness.update_relation_data(
rel_id,
"consumer/0",
{
"prometheus_scrape_unit_address": "1.1.1.1",
"prometheus_scrape_unit_name": "provider/0",
},
)
self.assertEqual(self.harness.charm._stored.num_events, 2)

jobs = self.harness.charm.prometheus_consumer.jobs()
self.validate_jobs(jobs)

def test_consumer_returns_alerts_rules_file(self):
self.assertEqual(self.harness.charm._stored.num_events, 0)

Expand Down

0 comments on commit 4b54576

Please sign in to comment.