Merge ~sajoupa/charm-telegraf:expose_ip_ranges into charm-telegraf:master

Proposed by Laurent Sesquès
Status: Rejected
Rejected by: Laurent Sesquès
Proposed branch: ~sajoupa/charm-telegraf:expose_ip_ranges
Merge into: charm-telegraf:master
Diff against target: 495 lines (+193/-78)
6 files modified
src/config.yaml (+6/-0)
src/reactive/telegraf.py (+139/-50)
src/templates/prometheus_client.tmpl (+4/-0)
src/templates/telegraf.conf.tmpl (+0/-6)
src/tests/functional/tests/bundles/bionic-monitoring.yaml (+1/-0)
src/tests/unit/test_telegraf.py (+43/-22)
Reviewer Review Type Date Requested Status
Paul Goins Needs Information
Canonical IS Reviewers Pending
Canonical IS Reviewers Pending
Review via email: mp+396503@code.launchpad.net

Commit message

Add support for prometheus_ip_range, allowing to restrict access to prometheus-client.

Also fixing:
- allow setting prometheus_output_port (and prometheus_ip_range) even when related to prometheus
- fix restart condition when the prometheus-client plugin is changed
- make the default port 9103 instead of 9216 when related to prometheus (https://github.com/prometheus/prometheus/wiki/Default-port-allocations says 9216 is "New Relic exporter", according to IANA it's bacula-sd)

To post a comment you must log in.
Revision history for this message
Haw Loeung (hloeung) wrote :

Quick first pass, see comment.

Revision history for this message
Haw Loeung (hloeung) :
Revision history for this message
Haw Loeung (hloeung) :
Revision history for this message
Laurent Sesquès (sajoupa) wrote :

Thanks, I addressed them.

Revision history for this message
Laurent Sesquès (sajoupa) wrote :

(saving comments, hopefully for real this time)

Revision history for this message
🤖 Canonical IS Merge Bot (canonical-is-mergebot) wrote :

This merge proposal is being monitored by mergebot. Change the status to Approved to merge.

Revision history for this message
🤖 Canonical IS Merge Bot (canonical-is-mergebot) wrote :

Unable to determine commit message from repository - please click "Set commit message" and enter the commit message manually.

Revision history for this message
Paul Goins (vultaire) wrote :

Thanks for the MR.

This seems like a fairly large MR if the intent is purely to address bug #1890102. I wonder if the code can be reduced here? I haven't read the whole MR yet, but I've read 1/3rd to 1/2, and it seems like maybe it's addressing something else as well? Could you explain?

Additionally, as axino noted on the above bug, this can be addressed, albeit more verbose, via the extra_options config value. Is this insufficient? And if it is, could we focus the change on adding the config and updating the template to consume that config value?

To be clear, I'm not trying to brush off these changes - but I am not understanding why all these changes are needed based upon the bug this is connected to. If there are other bugs to be fixed, it'd be better to fix those via additional MRs, in my opinion.

Best Regards,
Paul Goins

review: Needs Information
Revision history for this message
Laurent Sesquès (sajoupa) wrote :

Thanks for the review.
We can do about anything with exta_options, but that's not ideal. Also, if we set an IP range manually with extra_options, then to allow related prometheuses, we must manually add their IP addresses to extra_options (and remove them on relation-departed, etc.).

This change also allows setting prometheus_output_port (and prometheus_ip_range) even when related to prometheus. Previously in a relation with prometheus, the charm could only set the port to 9126. https://github.com/prometheus/prometheus/wiki/Default-port-allocations says 9216 is "New Relic exporter", according to IANA it's bacula-sd so I made it default to 9103 (admittedly, changing the default could be in a separate MP).

Revision history for this message
Laurent Sesquès (sajoupa) wrote :

> https://github.com/prometheus/prometheus/wiki/Default-port-allocations says
> 9216 is "New Relic exporter", according to IANA it's bacula-sd so I made it
> default to 9103 (admittedly, changing the default could be in a separate MP).
9103 is bacula-sd actually according to IANA. But Prometheus considers it as the collectd port, so still a better default (also the telegraf charm default).

Revision history for this message
Laurent Sesquès (sajoupa) wrote :

Unmerged commits

a9d2bea... by Laurent Sesquès

prometheus_ip_range support: a few code improvements

fa4e7c9... by Laurent Sesquès

add unit tests for prometheus_ip_range

68a5407... by Laurent Sesquès

remove TODO comment about get_prometheus_port(), actually not relevant

689fb2b... by Laurent Sesquès

rework flags and wording for prometheus-client

8623c5f... by Laurent Sesquès

prometheus_client output plugin: fix reactive logic, update unit tests

9359340... by Laurent Sesquès

revamp prometheus-client output configuration to add ip_range, fix bugs with prometheus relation

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
diff --git a/src/config.yaml b/src/config.yaml
index 66f6105..b94071b 100644
--- a/src/config.yaml
+++ b/src/config.yaml
@@ -206,3 +206,9 @@ options:
206 Note: The complete datasource inserted into dashboard will be206 Note: The complete datasource inserted into dashboard will be
207 "$prometheus_datasource - Juju generated source"207 "$prometheus_datasource - Juju generated source"
208 This matches how the Prometheus2/Grafana charms format the datasource.208 This matches how the Prometheus2/Grafana charms format the datasource.
209 prometheus_ip_range:
210 default: ""
211 type: string
212 description: >
213 If set, the list of IP Ranges which are allowed to access metrics.
214 ex: prometheus_ip_range = "[192.168.0.0/24, 192.168.1.0/30]"
diff --git a/src/reactive/telegraf.py b/src/reactive/telegraf.py
index 136c271..fe71d43 100644
--- a/src/reactive/telegraf.py
+++ b/src/reactive/telegraf.py
@@ -159,7 +159,14 @@ def list_config_files():
159 current_states = get_states()159 current_states = get_states()
160160
161 for plugin in list_supported_plugins():161 for plugin in list_supported_plugins():
162 if "plugins.{}.configured".format(plugin) in current_states.keys():162 # The prometheus_client plugin can be configured either from a relation or
163 # from the juju config
164 if ("plugins.{}.configured".format(plugin) in current_states.keys()) or (
165 "{}.configured".format(plugin) in current_states.keys()
166 ):
167 # The "prometheus-client" relation sets the "prometheus_client" plugin
168 if plugin == "prometheus-client":
169 plugin = "prometheus_client"
163 config_path = "{}/{}.conf".format(get_configs_dir(), plugin)170 config_path = "{}/{}.conf".format(get_configs_dir(), plugin)
164 config_files.append(config_path)171 config_files.append(config_path)
165172
@@ -327,8 +334,14 @@ def get_prometheus_port():
327 return False334 return False
328 if config.get("prometheus_output_port") == "default":335 if config.get("prometheus_output_port") == "default":
329 return 9103336 return 9103
330 else:337 return int(config.get("prometheus_output_port"))
331 return int(config.get("prometheus_output_port"))338
339
340def get_prometheus_ip_range():
341 config = hookenv.config()
342 if config.get("prometheus_ip_range") == "":
343 return []
344 return config.get("prometheus_ip_range").split(",")
332345
333346
334def get_socket_listener_port():347def get_socket_listener_port():
@@ -415,6 +428,7 @@ def update_sysstat_config_with_sdac_xall(path="/etc/sysstat/sysstat"):
415428
416429
417def configure_telegraf(): # noqa: C901430def configure_telegraf(): # noqa: C901
431 hookenv.log("Generating telegraf.conf", level=hookenv.DEBUG)
418 update_sysstat_config_with_sdac_xall()432 update_sysstat_config_with_sdac_xall()
419 config = hookenv.config()433 config = hookenv.config()
420 context = config.copy()434 context = config.copy()
@@ -503,9 +517,6 @@ def configure_telegraf(): # noqa: C901
503 )517 )
504 context["logfile"] = ""518 context["logfile"] = ""
505519
506 if get_prometheus_port():
507 context["prometheus_output_port"] = get_prometheus_port()
508 check_prometheus_port("prometheus_output", get_prometheus_port())
509 context["extra_options"] = get_extra_options()520 context["extra_options"] = get_extra_options()
510521
511 if get_socket_listener_port():522 if get_socket_listener_port():
@@ -566,10 +577,10 @@ def configure_telegraf(): # noqa: C901
566 context=context,577 context=context,
567 )578 )
568579
580 # Make sure that only the right service is enabled, then defer to start_or_restart()
569 for service in [DEB_SERVICE, SNAP_SERVICE]:581 for service in [DEB_SERVICE, SNAP_SERVICE]:
570 if service == get_service():582 if service == get_service():
571 host.service_resume(service)583 host.service_resume(service)
572 host.service_reload(service)
573 else:584 else:
574 try:585 try:
575 host.service_pause(service)586 host.service_pause(service)
@@ -621,6 +632,7 @@ def install_telegraf():
621632
622@when("telegraf.installed")633@when("telegraf.installed")
623@when("apt.installed.telegraf")634@when("apt.installed.telegraf")
635@when("plugins.prometheus-client.configured")
624@when_not("telegraf.configured")636@when_not("telegraf.configured")
625@when_not("telegraf.apt.configured")637@when_not("telegraf.apt.configured")
626def configure_telegraf_deb():638def configure_telegraf_deb():
@@ -629,6 +641,7 @@ def configure_telegraf_deb():
629641
630@when("telegraf.installed")642@when("telegraf.installed")
631@when("snap.installed.telegraf")643@when("snap.installed.telegraf")
644@when("plugins.prometheus-client.configured")
632@when_not("telegraf.configured")645@when_not("telegraf.configured")
633@when_not("telegraf.snap.configured")646@when_not("telegraf.snap.configured")
634def configure_telegraf_snap():647def configure_telegraf_snap():
@@ -653,6 +666,7 @@ def handle_config_changes():
653 if config.changed("extra_options"):666 if config.changed("extra_options"):
654 for plugin in list_supported_plugins():667 for plugin in list_supported_plugins():
655 clear_flag("plugins.{}.configured".format(plugin))668 clear_flag("plugins.{}.configured".format(plugin))
669 clear_flag("prometheus-client.relation.configured")
656 # if something else changed, let's reconfigure telegraf itself just in case670 # if something else changed, let's reconfigure telegraf itself just in case
657671
658 if config.changed("extra_plugins"):672 if config.changed("extra_plugins"):
@@ -665,6 +679,14 @@ def handle_config_changes():
665 ):679 ):
666 clear_flag("telegraf.installed")680 clear_flag("telegraf.installed")
667 clear_flag("extra_plugins.configured")681 clear_flag("extra_plugins.configured")
682 clear_flag("plugins.prometheus-client.configured")
683 clear_flag("prometheus-client.relation.configured")
684
685 if config.changed("prometheus_output_port") or config.changed(
686 "prometheus_ip_range"
687 ):
688 clear_flag("plugins.prometheus-client.configured")
689 clear_flag("prometheus-client.relation.configured")
668 clear_flag("telegraf.configured")690 clear_flag("telegraf.configured")
669 clear_flag("telegraf.apt.configured")691 clear_flag("telegraf.apt.configured")
670 clear_flag("telegraf.snap.configured")692 clear_flag("telegraf.snap.configured")
@@ -983,7 +1005,7 @@ def redis_input(redis):
983[[inputs.redis]]1005[[inputs.redis]]
984 servers = ["tcp://{{ host }}:{{ port }}"]1006 servers = ["tcp://{{ host }}:{{ port }}"]
985 # Until https://github.com/influxdata/telegraf/issues/5036 is fixed1007 # Until https://github.com/influxdata/telegraf/issues/5036 is fixed
986 fielddrop = ["aof_last_bgrewrite_status","aof_last_write_status","maxmemory_policy","rdb_last_bgsave_status","used_memory_dataset_perc","used_memory_peak_perc"]1008 fielddrop = ["aof_last_bgrewrite_status","aof_last_write_status","maxmemory_policy","rdb_last_bgsave_status","used_memory_dataset_perc","used_memory_peak_perc"] # noqa E501
987""" # noqa E501 (inline template)1009""" # noqa E501 (inline template)
988 config_path = "{}/{}.conf".format(get_configs_dir(), "redis")1010 config_path = "{}/{}.conf".format(get_configs_dir(), "redis")
9891011
@@ -1185,59 +1207,124 @@ def influxdb_api_output(influxdb):
1185 set_flag("telegraf.needs_reload")1207 set_flag("telegraf.needs_reload")
11861208
11871209
1210def generate_prometheus_output_config(prometheus_output_port, prometheus_ip_range):
1211 # If extra_options are set for prometheus_client, let's integrate them
1212 extra_options = get_extra_options()
1213 options = extra_options["outputs"].get("prometheus_client", {})
1214 listen = options.pop("listen", None)
1215 if not listen:
1216 listen = ":{}".format(prometheus_output_port)
1217 elif int(listen.split(":", 1)[1]) != prometheus_output_port:
1218 hookenv.log(
1219 """prometheus_output_port is {}, but extra_options would set it
1220 to {}. Choosing {} from prometheus_output_port.""".format(
1221 prometheus_output_port,
1222 int(listen.split(":", 1)[1]),
1223 prometheus_output_port,
1224 ),
1225 level=hookenv.WARNING,
1226 )
1227 listen = "{}:{}".format(listen.split(":", 1)[0], prometheus_output_port)
1228
1229 options_ip_range = options.pop("ip_range", [])
1230 ip_range = options_ip_range + prometheus_ip_range
1231
1232 return {
1233 "listen": listen,
1234 "ip_range": ip_range,
1235 "extra_options": render_extra_options(
1236 "outputs", "prometheus_client", extra_options=extra_options
1237 ),
1238 }
1239
1240
1241def render_prometheus_client_config(port, ip_range):
1242 config_path = "{}/{}.conf".format(get_configs_dir(), "prometheus_client")
1243 hookenv.log(
1244 "Updating {} plugin config file. Port is {} and ip_range is {}".format(
1245 "prometheus_client", port, ip_range
1246 ),
1247 level=hookenv.INFO,
1248 )
1249 context = generate_prometheus_output_config(port, ip_range)
1250 render(
1251 source="prometheus_client.tmpl",
1252 templates_dir=get_templates_dir(),
1253 target=config_path,
1254 context=context,
1255 )
1256
1257
1188@when("prometheus-client.available")1258@when("prometheus-client.available")
1189@when("telegraf.installed")1259@when_not("prometheus-client.relation.configured")
1190def prometheus_client(prometheus):1260def configure_prometheus_client_with_relation(prometheus):
1191 template = """1261 hookenv.log(
1192[[outputs.prometheus_client]]1262 "Configuring prometheus_client output plugin, with prometheus-client relation",
1193 listen = "{{ listen }}"1263 level=hookenv.DEBUG,
1194"""1264 )
1265 if get_prometheus_port():
1266 port = get_prometheus_port()
1267 else:
1268 # We have a relation with prometheus, but removed the port number config.
1269 # Default to 9103.
1270 port = "9103"
1271 # We'll iterate through the prometheus-client relation counterparts,
1272 # inform them of our address so that they scrape it, and get their egress subnets
1273 # so that we can allow them
1274 remote_egress_subnets = []
1195 for relation_id in hookenv.relation_ids("prometheus-client"):1275 for relation_id in hookenv.relation_ids("prometheus-client"):
1196 # if juju 2.x+ then we'll attempt to get the network space address1276 # if juju 2.x+ then we'll attempt to get the network space address
1197 try:1277 try:
1198 hookenv.log("Network Info")1278 hookenv.log("Getting local betwork info", level=hookenv.DEBUG)
1199 network_info = hookenv.network_get(1279 network_info = hookenv.network_get(
1200 "prometheus-client", relation_id=relation_id1280 "prometheus-client", relation_id=relation_id
1201 )1281 )
1202 hookenv.log(network_info)1282 hookenv.log(network_info, level=hookenv.DEBUG)
1203 if "ingress-addresses" in network_info:1283 if "ingress-addresses" in network_info:
1204 ip_addr = network_info.get("ingress-addresses")[0]1284 ip_addr = network_info.get("ingress-addresses")[0]
1205 else:1285 else:
1206 ip_addr = hookenv.network_get_primary_address("prometheus-client")1286 ip_addr = hookenv.network_get_primary_address("prometheus-client")
1287 for unit in hookenv.related_units(relation_id):
1288 hookenv.log(
1289 "Getting remote egress subnet for relation {} - {}".format(
1290 unit, relation_id
1291 ),
1292 level=hookenv.DEBUG,
1293 )
1294 remote_egress_subnets.append(
1295 hookenv.relation_get("egress-subnets", unit, relation_id)
1296 )
1207 except NotImplementedError:1297 except NotImplementedError:
1208 # if that fails, just let prometheus.configure(...) do it's default1298 # if that fails, just let prometheus.configure(...) do it's default
1209 ip_addr = None1299 ip_addr = None
1210 if get_prometheus_port():
1211 hookenv.log("Prometheus configured globally, skipping plugin setup")
1212 prometheus.configure(
1213 get_prometheus_port(), hostname=ip_addr, private_address=ip_addr
1214 )
1215 set_flag("prometheus-client.configured")
1216 # bail out, nothing more need to be configured here
1217 return
1218 port = 9126
1219 extra_options = get_extra_options()
1220 options = extra_options["outputs"].get("prometheus-client", {})
1221 listen = options.pop("listen", None)
1222 if listen is not None:
1223 hookenv.log(
1224 "Configuring prometheus_client plugin to listen on: '{}'".format(listen)
1225 )
1226 port = int(listen.split(":", 1)[1])
1227 else:
1228 listen = ":{}".format(port)
1229 check_prometheus_port("prometheus_output", port)
1230 prometheus.configure(port, hostname=ip_addr, private_address=ip_addr)1300 prometheus.configure(port, hostname=ip_addr, private_address=ip_addr)
1231 config_path = "{}/{}.conf".format(get_configs_dir(), "prometheus-client")1301 check_prometheus_port("prometheus_output", port)
1232 hookenv.log("Updating {} plugin config file".format("prometheus-client"))1302 # If prometheus_ip_range is empty, all remote IPs are allowed
1233 context = {"listen": listen}1303 ip_range = get_prometheus_ip_range()
1234 content = render_template(template, context) + render_extra_options(1304 if ip_range != []:
1235 "outputs", "prometheus_client", extra_options=extra_options1305 ip_range = ip_range + remote_egress_subnets
1236 )1306 render_prometheus_client_config(port, ip_range)
1237 host.write_file(config_path, content.encode("utf-8"))1307 set_flag("plugins.prometheus-client.configured")
1308 set_flag("prometheus-client.relation.configured")
1309 set_flag("telegraf.needs_reload")
1310
1311
1312@when_not("prometheus-client.available")
1313@when_not("plugins.prometheus-client.configured")
1314def configure_prometheus_client():
1315 hookenv.log("Configuring prometheus_client output plugin", level=hookenv.DEBUG)
1316 if get_prometheus_port():
1317 port = get_prometheus_port()
1318 else:
1319 # No relation tp prometheus, no port configured: do not configure the plugin
1238 set_flag("plugins.prometheus-client.configured")1320 set_flag("plugins.prometheus-client.configured")
1239 set_flag("telegraf.needs_reload")1321 return
1240 set_flag("prometheus-client.configured")1322 check_prometheus_port("prometheus_output", port)
1323 ip_range = get_prometheus_ip_range()
1324 render_prometheus_client_config(port, ip_range)
1325 set_flag("plugins.prometheus-client.configured")
1326 set_flag("telegraf.needs_reload")
1327 clear_flag("prometheus-client.relation.configured")
12411328
12421329
1243def convert_days(time_string):1330def convert_days(time_string):
@@ -1295,21 +1382,21 @@ def render_prometheus_rules(prometheus_rules):
12951382
12961383
1297@when_not("prometheus-client.available")1384@when_not("prometheus-client.available")
1298@when("plugins.prometheus-client.configured")1385@when("prometheus-client.relation.configured")
1299def prometheus_client_departed():1386def prometheus_client_departed():
1300 hookenv.log("prometheus-client relation not available")1387 hookenv.log("prometheus-client relation not available")
1301 config_path = "{}/{}.conf".format(get_configs_dir(), "prometheus-client")1388 config_path = "{}/{}.conf".format(get_configs_dir(), "prometheus_client")
1302 rels = hookenv.relations_of_type("prometheus-client")1389 rels = hookenv.relations_of_type("prometheus-client")
1303 if not rels and os.path.exists(config_path):1390 if not rels and os.path.exists(config_path):
1304 hookenv.log("Deleting {} plugin config file".format("prometheus-client"))1391 hookenv.log("Deleting {} plugin config file".format("prometheus-client"))
1305 os.unlink(config_path)1392 os.unlink(config_path)
1306 clear_flag("plugins.prometheus-client.configured")1393 clear_flag("plugins.prometheus-client.configured")
1307 set_flag("telegraf.needs_reload")
1308 clear_flag("prometheus-client.configured")
13091394
13101395
1311@when(1396@when(
1312 "prometheus-client.configured", "endpoint.dashboards.joined", "leadership.is_leader"1397 "plugins.prometheus-client.configured",
1398 "endpoint.dashboards.joined",
1399 "leadership.is_leader",
1313)1400)
1314@when_not("grafana.configured")1401@when_not("grafana.configured")
1315def register_grafana_dashboard():1402def register_grafana_dashboard():
@@ -1384,6 +1471,8 @@ def grafana_dashboard_import_failed():
13841471
13851472
1386@when("telegraf.needs_reload")1473@when("telegraf.needs_reload")
1474@when("telegraf.installed")
1475@when("telegraf.configured")
1387def start_or_restart():1476def start_or_restart():
1388 states = sorted(1477 states = sorted(
1389 [1478 [
diff --git a/src/templates/prometheus_client.tmpl b/src/templates/prometheus_client.tmpl
1390new file mode 1006441479new file mode 100644
index 0000000..a6e3c06
--- /dev/null
+++ b/src/templates/prometheus_client.tmpl
@@ -0,0 +1,4 @@
1[[outputs.prometheus_client]]
2 listen = "{{ listen }}"
3 ip_range = {{ ip_range }}
4{%- if extra_options %}{{ extra_options }}{%- endif %}
diff --git a/src/templates/telegraf.conf.tmpl b/src/templates/telegraf.conf.tmpl
index af59ed5..966b4a9 100644
--- a/src/templates/telegraf.conf.tmpl
+++ b/src/templates/telegraf.conf.tmpl
@@ -80,12 +80,6 @@
8080
81{{ outputs }}81{{ outputs }}
8282
83{% if prometheus_output_port %}
84[[outputs.prometheus_client]]
85 listen = ":{{ prometheus_output_port }}"
86 {%- if extra_options['outputs']['prometheus_client'] %}{{ render_options('prometheus_client', 'outputs', extra_options['outputs']) }}{%- endif %}
87{%- endif %}
88
89###############################################################################83###############################################################################
90# INPUTS #84# INPUTS #
91###############################################################################85###############################################################################
diff --git a/src/tests/functional/tests/bundles/bionic-monitoring.yaml b/src/tests/functional/tests/bundles/bionic-monitoring.yaml
index 120eab8..c7a487b 100644
--- a/src/tests/functional/tests/bundles/bionic-monitoring.yaml
+++ b/src/tests/functional/tests/bundles/bionic-monitoring.yaml
@@ -8,6 +8,7 @@ applications:
8 num_units: 08 num_units: 0
9 options:9 options:
10 prometheus_datasource: prometheus210 prometheus_datasource: prometheus2
11 prometheus_ip_range: '0.0.0.0/0'
11 grafana:12 grafana:
12 charm: cs:grafana13 charm: cs:grafana
13 num_units: 114 num_units: 1
diff --git a/src/tests/unit/test_telegraf.py b/src/tests/unit/test_telegraf.py
index afc3625..9b7343b 100644
--- a/src/tests/unit/test_telegraf.py
+++ b/src/tests/unit/test_telegraf.py
@@ -753,12 +753,11 @@ def test_prometheus_global(monkeypatch, config):
753 monkeypatch.setattr(telegraf.hookenv, "open_port", lambda p: open_ports.add(p))753 monkeypatch.setattr(telegraf.hookenv, "open_port", lambda p: open_ports.add(p))
754 monkeypatch.setattr(telegraf.hookenv, "close_port", lambda p: open_ports.remove(p))754 monkeypatch.setattr(telegraf.hookenv, "close_port", lambda p: open_ports.remove(p))
755 config["prometheus_output_port"] = "default"755 config["prometheus_output_port"] = "default"
756 telegraf.configure_telegraf()756 telegraf.configure_prometheus_client()
757 expected = """757 expected = """[[outputs.prometheus_client]]
758[[outputs.prometheus_client]]
759 listen = ":9103"758 listen = ":9103"
760"""759 ip_range = []"""
761 config_file = base_dir().join("telegraf.conf")760 config_file = base_dir().join("telegraf.d", "prometheus_client.conf")
762 assert expected in config_file.read()761 assert expected in config_file.read()
763762
764763
@@ -777,15 +776,14 @@ outputs:
777 cpu: ["cpu0"]776 cpu: ["cpu0"]
778777
779"""778"""
780 telegraf.configure_telegraf()779 telegraf.configure_prometheus_client()
781 expected = """780 expected = """[[outputs.prometheus_client]]
782[[outputs.prometheus_client]]
783 listen = ":9103"781 listen = ":9103"
782 ip_range = []
784 namedrop = ["aerospike*"]783 namedrop = ["aerospike*"]
785 [outputs.prometheus_client.tagpass]784 [outputs.prometheus_client.tagpass]
786 cpu = ["cpu0"]785 cpu = ["cpu0"]"""
787"""786 config_file = base_dir().join("telegraf.d", "prometheus_client.conf")
788 config_file = base_dir().join("telegraf.conf")
789 assert expected in config_file.read()787 assert expected in config_file.read()
790788
791789
@@ -1072,7 +1070,9 @@ def test_prometheus_client_output(mocker, monkeypatch, config):
1072 monkeypatch.setattr(telegraf.hookenv, "open_port", lambda p: None)1070 monkeypatch.setattr(telegraf.hookenv, "open_port", lambda p: None)
10731071
1074 relation_ids = ["prometheus-client:0"]1072 relation_ids = ["prometheus-client:0"]
1073 related_units = ["prometheus/0"]
1075 monkeypatch.setattr(telegraf.hookenv, "relation_ids", lambda r: relation_ids)1074 monkeypatch.setattr(telegraf.hookenv, "relation_ids", lambda r: relation_ids)
1075 monkeypatch.setattr(telegraf.hookenv, "related_units", lambda r: related_units)
10761076
1077 network_get_primary_address = mocker.patch.object(1077 network_get_primary_address = mocker.patch.object(
1078 telegraf.hookenv, "network_get_primary_address", return_value="foo"1078 telegraf.hookenv, "network_get_primary_address", return_value="foo"
@@ -1082,28 +1082,48 @@ def test_prometheus_client_output(mocker, monkeypatch, config):
1082 telegraf.hookenv, "network_get", return_value={"ingress_addresses": ["1.2.3.4"]}1082 telegraf.hookenv, "network_get", return_value={"ingress_addresses": ["1.2.3.4"]}
1083 )1083 )
10841084
1085 mocker.patch.object(telegraf.hookenv, "relation_get", return_value="5.6.7.8/32")
1086
1085 interface = mocker.Mock(spec=RelationBase)1087 interface = mocker.Mock(spec=RelationBase)
1086 interface.configure = mocker.Mock()1088 interface.configure = mocker.Mock()
1087 telegraf.prometheus_client(interface)1089
1090 # Test that telegraf will allow scraping from related prometheus, and from ranges in
1091 # prometheus_ip_range
1092 config["prometheus_ip_range"] = "127.0.0.1/32,10.0.0.0/8"
1093 telegraf.configure_prometheus_client_with_relation(interface)
1088 expected = """1094 expected = """
1089 [[outputs.prometheus_client]]1095 [[outputs.prometheus_client]]
1090 listen = ":9126"1096 listen = ":9103"
1097 ip_range = ['127.0.0.1/32', '10.0.0.0/8', '5.6.7.8/32']
1091"""1098"""
1092 assert (1099 assert (
1093 configs_dir().join("prometheus-client.conf").read().strip() == expected.strip()1100 configs_dir().join("prometheus_client.conf").read().strip() == expected.strip()
1094 )1101 )
1102 # prometheus_ip_range is empty, test that all IPs are allowed, not just the related
1103 # prometheus
1104 # prometheus_output_port is also empty, we should get 9103 by default
1095 network_get_primary_address.assert_called_once_with("prometheus-client")1105 network_get_primary_address.assert_called_once_with("prometheus-client")
1096 interface.configure.assert_called_once_with(1106 interface.configure.assert_called_once_with(
1097 9126, hostname="foo", private_address="foo"1107 "9103", hostname="foo", private_address="foo"
1108 )
1109 config["prometheus_ip_range"] = ""
1110 telegraf.configure_prometheus_client_with_relation(interface)
1111 expected = """
1112 [[outputs.prometheus_client]]
1113 listen = ":9103"
1114 ip_range = []
1115"""
1116 assert (
1117 configs_dir().join("prometheus_client.conf").read().strip() == expected.strip()
1098 )1118 )
10991119
11001120
1101def test_prometheus_client_output_departed(mocker, monkeypatch, config):1121def test_prometheus_client_output_departed(mocker, monkeypatch, config):
1102 configs_dir().join("prometheus-client.conf").write("empty")1122 configs_dir().join("prometheus_client.conf").write("empty")
1103 relations = [1]1123 relations = [1]
1104 monkeypatch.setattr(telegraf.hookenv, "relations_of_type", lambda n: relations)1124 monkeypatch.setattr(telegraf.hookenv, "relations_of_type", lambda n: relations)
1105 telegraf.prometheus_client_departed()1125 telegraf.prometheus_client_departed()
1106 assert configs_dir().join("prometheus-client.conf").exists()1126 assert configs_dir().join("prometheus_client.conf").exists()
1107 relations.pop()1127 relations.pop()
1108 telegraf.prometheus_client_departed()1128 telegraf.prometheus_client_departed()
1109 assert not configs_dir().join("prometheus-client.conf").exists()1129 assert not configs_dir().join("prometheus-client.conf").exists()
@@ -1198,17 +1218,18 @@ def test_restart_on_output_plugin_relation_departed(mocker, monkeypatch, config)
1198 mocker.patch.object(1218 mocker.patch.object(
1199 telegraf.hookenv, "network_get", return_value={"ingress_addresses": ["1.2.3.4"]}1219 telegraf.hookenv, "network_get", return_value={"ingress_addresses": ["1.2.3.4"]}
1200 )1220 )
1201 config["prometheus_output_port"] = ""1221 config["prometheus_output_port"] = "9103"
1202 bus.discover()1222 bus.discover()
1223 set_flag("telegraf.installed")
1203 set_flag("snap.telegraf.installed")1224 set_flag("snap.telegraf.installed")
1204 set_flag("telegraf.configured")1225 set_flag("telegraf.configured")
1205 interface = mocker.Mock(spec=RelationBase)1226 interface = mocker.Mock(spec=RelationBase)
1206 interface.configure = mocker.Mock()1227 interface.configure = mocker.Mock()
1207 telegraf.prometheus_client(interface)1228 telegraf.configure_prometheus_client_with_relation(interface)
1208 assert configs_dir().join("prometheus-client.conf").exists()1229 assert configs_dir().join("prometheus_client.conf").exists()
1209 # dispatch, file should be gone and telegraf restarted.1230 # dispatch, file should still be present and telegraf restarted.
1210 bus.dispatch()1231 bus.dispatch()
1211 assert not configs_dir().join("prometheus-client.conf").exists()1232 assert configs_dir().join("prometheus_client.conf").exists()
1212 service_restart.assert_called_with(telegraf.DEB_SERVICE)1233 service_restart.assert_called_with(telegraf.DEB_SERVICE)
12131234
12141235

Subscribers

People subscribed via source and target branches

to all changes: