forked from canonical/prometheus-k8s-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prometheus_scrape.py
1760 lines (1438 loc) · 67.7 KB
/
prometheus_scrape.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""## Overview.
This document explains how to integrate with the Prometheus charm
for the purposes of providing a metrics endpoint to Prometheus. It
also explains how alternative implementations of the Prometheus charm
may maintain the same interface and be backward compatible with all
currently integrated charms. Finally this document is the
authoritative reference on the structure of relation data that is
shared between Prometheus charms and any other charm that intends to
provide a scrape target for Prometheus.
## Provider Library Usage
This Prometheus charm interacts with its scrape targets using its
charm library. Charms seeking to expose a metric endpoints for the
Prometheus charm, must do so using the `MetricsEndpointProvider`
object from this charm library. For the simplest use cases, using the
`MetricsEndpointProvider` object only requires instantiating it,
typically in the constructor of your charm (the one which exposes a
metrics endpoint). The `MetricsEndpointProvider` constructor requires
the name of the relation over which a scrape target (metrics endpoint)
is exposed to the Prometheus charm. This relation must use the
`prometheus_scrape` interface. The address of the metrics endpoint is
set to the unit address, by each unit of the `MetricsEndpointProvider`
charm. These units set their address in response to a specific
`CharmEvent`. Hence instantiating the `MetricsEndpointProvider` also
requires a `CharmEvent` object in response to which each unit will
post its address into the unit's relation data for the Prometheus
charm. Since container restarts of Kubernetes charms can result in
change of IP addresses, this event is typically `PebbleReady`. For
example, assuming your charm exposes a metrics endpoint over a
relation named "metrics_endpoint", you may instantiate
`MetricsEndpointProvider` as follows
from charms.prometheus_k8s.v0.prometheus_scrape import MetricsEndpointProvider
def __init__(self, *args):
super().__init__(*args)
...
self.metrics_endpoint = MetricsEndpointProvider(self, "metrics-endpoint",
self.on.container_name_pebble_ready)
...
In this example `container_name_pebble_ready` is the `PebbleReady` event
in response to which each unit will advertise its address. Also note
that the first argument (`self`) to `MetricsEndpointProvider` is always a
reference to the parent (scrape target) charm.
An instantiated `MetricsEndpointProvider` object will ensure that each unit of
its parent charm, is a scrape target for the `MetricsEndpointConsumer`
(Prometheus). By default `MetricsEndpointProvider` assumes each unit of the
consumer charm exports its metrics at a path given by `/metrics` on
port 80. The defaults may be changed by providing the
`MetricsEndpointProvider` constructor an optional argument (`jobs`) that
represents list of Prometheus scrape job specification using Python
standard data structures. This job specification is a subset of
Prometheus' own [scrape
configuration](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config)
format but represented using Python data structures. More than one job
may be provided using the `jobs` argument. Hence `jobs` accepts a list
of dictionaries where each dictionary represents one `<scrape_config>`
object as described in the Prometheus documentation. The current
supported configuration subset is: `job_name`, `metrics_path`,
`static_configs`
Suppose it is required to change the port on which scraped metrics are
exposed to 8000. This may be done by providing the following data
structure as the value of `jobs`.
```
[
{
"static_configs": [
{
"targets": ["*:8000"]
}
]
}
]
```
The wildcard ("*") host specification implies that the scrape targets
will automatically be set to the host addresses advertised by each
unit of the consumer charm.
It is also possible to change the metrics path and scrape multiple
ports, for example
```
[
{
"metrics_path": "/my-metrics-path",
"static_configs": [
{
"targets": ["*:8000", "*:8081"],
}
]
}
]
```
More complex scrape configurations are possible. For example
```
[
{
"static_configs": [
{
"targets": ["10.1.32.215:7000", "*:8000"],
"labels": {
"some-key": "some-value"
}
}
]
}
]
```
This example scrapes the target "10.1.32.215" at port 7000 in addition
to scraping each unit at port 8000. There is however one difference
between wildcard targets (specified using "*") and fully qualified
targets (such as "10.1.32.215"). The Prometheus charm automatically
associates labels with metrics generated by each target. These labels
localise the source of metrics within the Juju topology by specifying
its "model name", "model UUID", "application name" and "unit
name". However unit name is associated only with wildcard targets but
not with fully qualified targets.
Multiple jobs with different metrics paths and labels are allowed, but
each job must be given a unique name. For example
```
[
{
"job_name": "my-first-job",
"metrics_path": "one-path",
"static_configs": [
{
"targets": ["*:7000"],
"labels": {
"some-key": "some-value"
}
}
]
},
{
"job_name": "my-second-job",
"metrics_path": "another-path",
"static_configs": [
{
"targets": ["*:8000"],
"labels": {
"some-other-key": "some-other-value"
}
}
]
}
]
```
It is also possible to configure other scrape related parameters using
these job specifications as described by the Prometheus
[documentation](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config).
The permissible subset of job specific scrape configuration parameters
supported in a `MetricsEndpointProvider` job specification are:
- `job_name`
- `metrics_path`
- `static_configs`
- `scrape_interval`
- `scrape_timeout`
- `proxy_url`
- `relabel_configs`
- `metrics_relabel_configs`
- `sample_limit`
- `label_limit`
- `label_name_length_limit`
- `label_value_length_limit`
## Consumer Library Usage
The `MetricsEndpointConsumer` object may be used by Prometheus
charms to manage relations with their scrape targets. For this
purposes a Prometheus charm needs to do two things
1. Instantiate the `MetricsEndpointConsumer` object providing it
with three two pieces of information
- A reference to the parent (Prometheus) charm.
- Name of the relation that the Prometheus charm uses to interact with
scrape targets. This relation must confirm to the
`prometheus_scrape` interface.
For example a Prometheus charm may instantiate the
`MetricsEndpointConsumer` in its constructor as follows
from charms.prometheus_k8s.v0.prometheus_scrape import MetricsEndpointConsumer
def __init__(self, *args):
super().__init__(*args)
...
self.metrics_consumer = MetricsEndpointConsumer(
self, "metrics-endpoint"
)
...
2. A Prometheus charm also needs to respond to the
`TargetsChangedEvent` event of the `MetricsEndpointConsumer` by adding itself as
and observer for these events, as in
self.framework.observe(
self.metrics_consumer.on.targets_changed,
self._on_scrape_targets_changed,
)
In responding to the `TargetsChangedEvent` event the Prometheus
charm must update the Prometheus configuration so that any new scrape
targets are added and/or old ones removed from the list of scraped
endpoints. For this purpose the `MetricsEndpointConsumer` object
exposes a `jobs()` method that returns a list of scrape jobs. Each
element of this list is the Prometheus scrape configuration for that
job. In order to update the Prometheus configuration, the Prometheus
charm needs to replace the current list of jobs with the list provided
by `jobs()` as follows
def _on_scrape_targets_changed(self, event):
...
scrape_jobs = self.metrics_consumer.jobs()
for job in scrape_jobs:
prometheus_scrape_config.append(job)
...
## Alerting Rules
This charm library also supports gathering alerting rules from all
related `MetricsEndpointProvider` charms and enabling corresponding alerts within the
Prometheus charm. Alert rules are automatically gathered by `MetricsEndpointProvider`
charms when using this library, from a directory conventionally named
`prometheus_alert_rules`. This directory must reside at the top level
in the `src` folder of the consumer charm. Each file in this directory
is assumed to be a single alert rule in YAML format. The file name must
have the `.rule` extension. The format of this alert rule conforms to the
[Prometheus docs](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/).
An example of the contents of one such file is shown below.
```
alert: HighRequestLatency
expr: job:request_latency_seconds:mean5m{my_key=my_value, %%juju_topology%%} > 0.5
for: 10m
labels:
severity: Medium
type: HighLatency
annotations:
summary: High request latency for {{ $labels.instance }}.
```
It is **very important** to note the `%%juju_topology%%` filter in the
expression for the alert rule shown above. This filter is a stub that
is automatically replaced by the metrics provider charm's Juju
topology (application, model and its UUID). Such a topology filter is
essential to ensure that alert rules submitted by one provider charm
generates alerts only for that same charm. The Prometheus charm may
be related to multiple metrics provider charms. Without this, filter
rules submitted by one provider charm will also result in
corresponding alerts for other provider charms. Hence every alert rule
expression must include such a topology filter stub.
Gathering alert rules and generating rule files within the Prometheus
charm is easily done using the `alerts()` method of
`MetricsEndpointConsumer`. Alerts generated by the Prometheus will
automatically include Juju topology labels in the alerts. These labels
indicate the source of the alert. The following labels are
automatically included with each alert
- `juju_model`
- `juju_model_uuid`
- `juju_application`
## Relation Data
The Prometheus charm uses both application and unit relation data to
obtain information regarding its scrape jobs, alert rules and scrape
targets. This relation data is in JSON format and it closely resembles
the YAML structure of Prometheus [scrape configuration]
(https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config).
Units of consumer charm advertise their address over unit relation
data using the `prometheus_scrape_host` key. While the
`scrape_metadata`, `scrape_jobs` and `alert_rules` keys in application
relation data provide eponymous information.
"""
import dataclasses
import json
import logging
import os
from collections import defaultdict
from pathlib import Path
from typing import List, Optional, Union
import yaml
from ops.charm import CharmBase, RelationMeta, RelationRole
from ops.framework import EventBase, EventSource, Object, ObjectEvents
# The unique Charmhub library identifier, never change it
LIBID = "bc84295fef5f4049878f07b131968ee2"
# Increment this major API version when introducing breaking changes
LIBAPI = 0
# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version
LIBPATCH = 11
logger = logging.getLogger(__name__)
ALLOWED_KEYS = {
"job_name",
"metrics_path",
"static_configs",
"scrape_interval",
"scrape_timeout",
"proxy_url",
"relabel_configs",
"metrics_relabel_configs",
"sample_limit",
"label_limit",
"label_name_length_limit",
"label_value_lenght_limit",
}
DEFAULT_JOB = {
"metrics_path": "/metrics",
"static_configs": [{"targets": ["*:80"]}],
}
DEFAULT_RELATION_NAME = "metrics-endpoint"
RELATION_INTERFACE_NAME = "prometheus_scrape"
DEFAULT_ALERT_RULES_RELATIVE_PATH = "./src/prometheus_alert_rules"
class RelationNotFoundError(Exception):
"""Raised if there is no relation with the given name."""
def __init__(self, relation_name: str):
self.relation_name = relation_name
self.message = f"No relation named '{relation_name}' found"
super().__init__(self.message)
class RelationInterfaceMismatchError(Exception):
"""Raised if the relation with the given name has a different interface."""
def __init__(
self,
relation_name: str,
expected_relation_interface: str,
actual_relation_interface: str,
):
self.relation_name = relation_name
self.expected_relation_interface = expected_relation_interface
self.actual_relation_interface = actual_relation_interface
self.message = (
f"The '{relation_name}' relation has '{actual_relation_interface}' as "
f"interface rather than the expected '{expected_relation_interface}'"
)
super().__init__(self.message)
class RelationRoleMismatchError(Exception):
"""Raised if the relation with the given name has a different direction."""
def __init__(
self,
relation_name: str,
expected_relation_role: RelationRole,
actual_relation_role: RelationRole,
):
self.relation_name = relation_name
self.expected_relation_interface = expected_relation_role
self.actual_relation_role = actual_relation_role
self.message = (
f"The '{relation_name}' relation has role '{repr(actual_relation_role)}' "
f"rather than the expected '{repr(expected_relation_role)}'"
)
super().__init__(self.message)
def _validate_relation_by_interface_and_direction(
charm: CharmBase,
relation_name: str,
expected_relation_interface: str,
expected_relation_role: RelationRole,
):
"""Verifies that a relation has the necessary characteristics.
Verifies that the `relation_name` provided: (1) exists in metadata.yaml,
(2) declares as interface the interface name passed as `relation_interface`
and (3) has the right "direction", i.e., it is a relation that `charm`
provides or requires.
Args:
charm: a `CharmBase` object to scan for the matching relation.
relation_name: the name of the relation to be verified.
expected_relation_interface: the interface name to be matched by the
relation named `relation_name`.
expected_relation_role: whether the `relation_name` must be either
provided or required by `charm`.
Raises:
RelationNotFoundError: If there is no relation in the charm's metadata.yaml
with the same name as provided via `relation_name` argument.
RelationInterfaceMismatchError: The relation with the same name as provided
via `relation_name` argument does not have the same relation interface
as specified via the `expected_relation_interface` argument.
RelationRoleMismatchError: If the relation with the same name as provided
via `relation_name` argument does not have the same role as specified
via the `expected_relation_role` argument.
"""
if relation_name not in charm.meta.relations:
raise RelationNotFoundError(relation_name)
relation: RelationMeta = charm.meta.relations[relation_name]
actual_relation_interface = relation.interface_name
if actual_relation_interface != expected_relation_interface:
raise RelationInterfaceMismatchError(
relation_name, expected_relation_interface, actual_relation_interface
)
if expected_relation_role == RelationRole.provides:
if relation_name not in charm.meta.provides:
raise RelationRoleMismatchError(
relation_name, RelationRole.provides, RelationRole.requires
)
elif expected_relation_role == RelationRole.requires:
if relation_name not in charm.meta.requires:
raise RelationRoleMismatchError(
relation_name, RelationRole.requires, RelationRole.provides
)
else:
raise Exception(f"Unexpected RelationDirection: {expected_relation_role}")
def _sanitize_scrape_configuration(job) -> dict:
"""Restrict permissible scrape configuration options.
If job is empty then a default job is returned. The
default job is
```
{
"metrics_path": "/metrics",
"static_configs": [{"targets": ["*:80"]}],
}
```
Args:
job: a dict containing a single Prometheus job
specification.
Returns:
a dictionary containing a sanitized job specification.
"""
sanitized_job = DEFAULT_JOB.copy()
sanitized_job.update({key: value for key, value in job.items() if key in ALLOWED_KEYS})
return sanitized_job
@dataclasses.dataclass(frozen=True)
class JujuTopology:
"""Dataclass for storing and formatting juju topology information."""
model: str
model_uuid: str
application: str
charm_name: str
@staticmethod
def from_charm(charm):
"""Factory method for creating the topology dataclass from a given charm."""
return JujuTopology(
model=charm.model.name,
model_uuid=charm.model.uuid,
application=charm.model.app.name,
charm_name=charm.meta.name,
)
@staticmethod
def from_relation_data(data):
"""Factory method for creating the topology dataclass from a relation data dict."""
return JujuTopology(
model=data["model"],
model_uuid=data["model_uuid"],
application=data["application"],
charm_name=data["charm_name"],
)
@property
def identifier(self) -> str:
"""Format the topology information into a terse string."""
return f"{self.model}_{self.model_uuid}_{self.application}"
@property
def scrape_identifier(self):
"""Format the topology information into a scrape identifier."""
return "juju_{}_{}_{}_prometheus_scrape".format(
self.model,
self.model_uuid[:7],
self.application,
)
@property
def promql_labels(self) -> str:
"""Format the topology information into a verbose string."""
return 'juju_model="{}", juju_model_uuid="{}", juju_application="{}"'.format(
self.model, self.model_uuid, self.application
)
def as_dict(self) -> dict:
"""Format the topology information into a dict."""
return dataclasses.asdict(self)
def as_dict_with_promql_labels(self):
"""Format the topology information into a dict with keys having 'juju_' as prefix."""
return {
"juju_model": self.model,
"juju_model_uuid": self.model_uuid,
"juju_application": self.application,
"juju_charm": self.charm_name,
}
def render(self, template: str):
"""Render a juju-topology template string with topology info."""
return template.replace("%%juju_topology%%", self.promql_labels)
def load_alert_rule_from_file(path: Path, topology: JujuTopology) -> Optional[dict]:
"""Load alert rule from a rules file.
Args:
path: path to a *.rule file with a single rule ("groups" super section omitted).
topology: a `JujuTopology` instance.
"""
with path.open() as rule_file:
# Load a list of rules from file then add labels and filters
try:
rule = yaml.safe_load(rule_file)
except Exception as e:
logger.error("Failed to read alert rules from %s: %s", path.name, e)
return None
else:
# add "juju_" topology labels
if "labels" not in rule:
rule["labels"] = {}
rule["labels"].update(topology.as_dict_with_promql_labels())
if "expr" not in rule:
logger.error("Invalid alert rule %s: missing an 'expr' property.", path.name)
return None
# insert juju topology filters into a prometheus alert rule
rule["expr"] = topology.render(rule["expr"])
return rule
def load_alert_rules_from_dir(
dir_path: Union[str, Path], topology: JujuTopology, *, recursive: bool = False
) -> List[dict]:
"""Load alert rules from rule files.
All rules from files for the same directory are loaded into a single
group. The generated name of this group includes juju topology.
By default, only the top directory is scanned; for nested scanning, pass `recursive=True`.
Args:
dir_path: directory containing *.rule files (alert rules without groups).
topology: a `JujuTopology` instance.
recursive: flag indicating whether to scan for rule files recursively.
Returns:
a list of prometheus alert rule groups.
"""
alerts = defaultdict(list)
def _group_name(path) -> str:
"""Generate group name from path and topology.
The group name is made up of the relative path between the root dir_path, the file path,
and topology identifier.
Args:
path: path to rule file.
"""
relpath = os.path.relpath(os.path.dirname(path), dir_path)
# Generate group name:
# - prefix, from the relative path of the rule file;
# - name, from juju topology
return (
f"{'' if relpath == '.' else relpath.replace(os.path.sep, '_') + '_'}"
f"{topology.identifier}_alerts"
)
for path in filter(Path.is_file, Path(dir_path).glob("**/*.rule" if recursive else "*.rule")):
if rule := load_alert_rule_from_file(path, topology):
logger.debug("Reading alert rule from %s", path)
alerts[_group_name(path)].append(rule)
# Gather all alerts into a list of groups since Prometheus
# requires alerts be part of some group
groups = [{"name": k, "rules": v} for k, v in alerts.items()]
return groups
class TargetsChangedEvent(EventBase):
"""Event emitted when Prometheus scrape targets change."""
def __init__(self, handle, relation_id):
super().__init__(handle)
self.relation_id = relation_id
def snapshot(self):
"""Save scrape target relation information."""
return {"relation_id": self.relation_id}
def restore(self, snapshot):
"""Restore scrape target relation information."""
self.relation_id = snapshot["relation_id"]
class MonitoringEvents(ObjectEvents):
"""Event descriptor for events raised by `MetricsEndpointConsumer`."""
targets_changed = EventSource(TargetsChangedEvent)
class MetricsEndpointConsumer(Object):
"""A Prometheus based Monitoring service provider."""
on = MonitoringEvents()
def __init__(self, charm: CharmBase, relation_name: str = DEFAULT_RELATION_NAME):
"""A Prometheus based Monitoring service provider.
Args:
charm: a `CharmBase` instance that manages this
instance of the Prometheus service.
relation_name: an optional string name of the relation between `charm`
and the Prometheus charmed service. The default is "metrics-endpoint".
It is strongly advised not to change the default, so that people
deploying your charm will have a consistent experience with all
other charms that consume metrics endpoints.
Raises:
RelationNotFoundError: If there is no relation in the charm's metadata.yaml
with the same name as provided via `relation_name` argument.
RelationInterfaceMismatchError: The relation with the same name as provided
via `relation_name` argument does not have the `prometheus_scrape` relation
interface.
RelationRoleMismatchError: If the relation with the same name as provided
via `relation_name` argument does not have the `RelationRole.requires`
role.
"""
_validate_relation_by_interface_and_direction(
charm, relation_name, RELATION_INTERFACE_NAME, RelationRole.requires
)
super().__init__(charm, relation_name)
self._charm = charm
self._relation_name = relation_name
events = self._charm.on[relation_name]
self.framework.observe(events.relation_changed, self._on_metrics_provider_relation_changed)
self.framework.observe(
events.relation_departed, self._on_metrics_provider_relation_departed
)
def _on_metrics_provider_relation_changed(self, event):
"""Handle changes in related consumers.
Anytime there are changes in relations between Prometheus
and metrics provider charms the Prometheus charm is informed,
through a `TargetsChangedEvent` event. The Prometheus charm can
then choose to update its scrape configuration.
Args:
event: a `CharmEvent` in response to which the Prometheus
charm must update its scrape configuration.
"""
rel_id = event.relation.id
self.on.targets_changed.emit(relation_id=rel_id)
def _on_metrics_provider_relation_departed(self, event):
"""Update job config when consumers depart.
When a metrics provider departs the scrape configuration
for that provider is removed from the list of scrape jobs and
the Prometheus is informed through a `TargetsChangedEvent`
event.
Args:
event: a `CharmEvent` that indicates a metrics provider
unit has departed.
"""
rel_id = event.relation.id
self.on.targets_changed.emit(relation_id=rel_id)
def jobs(self) -> list:
"""Fetch the list of scrape jobs.
Returns:
A list consisting of all the static scrape configurations
for each related `MetricsEndpointProvider` that has specified
its scrape targets.
"""
scrape_jobs = []
for relation in self._charm.model.relations[self._relation_name]:
static_scrape_jobs = self._static_scrape_config(relation)
if static_scrape_jobs:
scrape_jobs.extend(static_scrape_jobs)
return scrape_jobs
def alerts(self) -> dict:
"""Fetch alerts for all relations.
A Prometheus alert rules file consists of a list of "groups". Each
group consists of a list of alerts (`rules`) that are sequentially
executed. This method returns all the alert rules provided by each
related metrics provider charm. These rules may be used to generate a
separate alert rules file for each relation since the returned list
of alert groups are indexed by relation ID. Also for each relation ID
associated scrape metadata such as Juju model, UUID and application
name are provided so the a unique name may be generated for the rules
file. For each relation the structure of data returned is a dictionary
with four keys
- groups
- model
- model_uuid
- application
The value of the `groups` key is such that it may be used to generate
a Prometheus alert rules file directly using `yaml.dump` but the
`groups` key itself must be included as this is required by Prometheus,
for example as in `yaml.dump({"groups": alerts["groups"]})`.
Currently the `MetricsEndpointProvider` only accepts a list of rules and these
rules are all placed into a single group, even though Prometheus itself
allows for multiple groups within a single alert rules file.
Returns:
a dictionary mapping the name of an alert rule group to the group.
"""
alerts = {}
for relation in self._charm.model.relations[self._relation_name]:
if not relation.units:
continue
alert_rules = json.loads(relation.data[relation.app].get("alert_rules", "{}"))
if not alert_rules:
continue
try:
for group in alert_rules["groups"]:
alerts[group["name"]] = group
except KeyError as e:
logger.error(
"Relation %s has invalid data : %s",
relation.id,
e,
)
return alerts
def _static_scrape_config(self, relation) -> list:
"""Generate the static scrape configuration for a single relation.
Args:
relation: an `ops.model.Relation` object whose static
scrape configuration is required.
Returns:
A list (possibly empty) of scrape jobs. Each job is a
valid Prometheus scrape configuration for that job,
represented as a Python dictionary.
"""
if not relation.units:
return []
scrape_jobs = json.loads(relation.data[relation.app].get("scrape_jobs", "[]"))
if not scrape_jobs:
return []
scrape_metadata = json.loads(relation.data[relation.app].get("scrape_metadata", "{}"))
if not scrape_metadata:
return scrape_jobs
job_name_prefix = JujuTopology.from_relation_data(scrape_metadata).scrape_identifier
hosts = self._relation_hosts(relation)
labeled_job_configs = []
for job in scrape_jobs:
config = self._labeled_static_job_config(
_sanitize_scrape_configuration(job),
job_name_prefix,
hosts,
scrape_metadata,
)
labeled_job_configs.append(config)
return labeled_job_configs
def _relation_hosts(self, relation) -> dict:
"""Fetch host names and address of all consumer units for a single relation.
Args:
relation: An `ops.model.Relation` object for which the host name to
address mapping is required.
Returns:
A dictionary that maps unit names to unit addresses for
the specified relation.
"""
return {
unit.name: relation.data[unit].get("prometheus_scrape_host")
for unit in relation.units
if relation.data[unit].get("prometheus_scrape_host")
}
def _labeled_static_job_config(self, job, job_name_prefix, hosts, scrape_metadata) -> dict:
"""Construct labeled job configuration for a single job.
Args:
job: a dictionary representing the job configuration as obtained from
`MetricsEndpointProvider` over relation data.
job_name_prefix: a string that may either be used as the
job name if none is provided or used as a prefix for
the provided job name.
hosts: a dictionary mapping host names to host address for
all units of the relation for which this job configuration
must be constructed.
scrape_metadata: scrape configuration metadata obtained
from `MetricsEndpointProvider` from the same relation for
which this job configuration is being constructed.
Returns:
A dictionary representing a Prometheus job configuration
for a single job.
"""
name = job.get("job_name")
job_name = f"{job_name_prefix}_{name}" if name else job_name_prefix
labeled_job = job.copy()
labeled_job["job_name"] = job_name
static_configs = job.get("static_configs")
labeled_job["static_configs"] = []
instance_relabel_config = {
"source_labels": ["juju_model", "juju_model_uuid", "juju_application"],
"separator": "_",
"target_label": "instance",
"regex": "(.*)",
}
# label all static configs in the Prometheus job
# labeling inserts Juju topology information and
# sets a relable config for instance labels
for static_config in static_configs:
labels = static_config.get("labels", {}) if static_configs else {}
all_targets = static_config.get("targets", [])
# split all targets into those which will have unit labels
# and those which will not
ports = []
unitless_targets = []
for target in all_targets:
host, port = target.split(":")
if host.strip() == "*":
ports.append(port.strip())
else:
unitless_targets.append(target)
# label scrape targets that do not have unit labels
if unitless_targets:
unitless_config = self._labeled_unitless_config(
unitless_targets, labels, scrape_metadata
)
labeled_job["static_configs"].append(unitless_config)
# label scrape targets that do have unit labels
for host_name, host_address in hosts.items():
static_config = self._labeled_unit_config(
host_name, host_address, ports, labels, scrape_metadata
)
labeled_job["static_configs"].append(static_config)
if "juju_unit" not in instance_relabel_config["source_labels"]:
instance_relabel_config["source_labels"].append("juju_unit")
# ensure topology relabeling of instance label is last in order of relabelings
relabel_configs = job.get("relabel_configs", [])
relabel_configs.append(instance_relabel_config)
labeled_job["relabel_configs"] = relabel_configs
return labeled_job
def _set_juju_labels(self, labels, scrape_metadata) -> dict:
"""Create a copy of metric labels with Juju topology information.
Args:
labels: a dictionary containing Prometheus metric labels.
scrape_metadata: scrape related metadata provided by
`MetricsEndpointProvider`.
Returns:
a copy of the `labels` dictionary augmented with Juju
topology information with the exception of unit name.
"""
juju_labels = labels.copy() # deep copy not needed
juju_labels.update(
JujuTopology.from_relation_data(scrape_metadata).as_dict_with_promql_labels()
)
return juju_labels
def _labeled_unitless_config(self, targets, labels, scrape_metadata) -> dict:
"""Static scrape configuration for fully qualified host addresses.
Fully qualified hosts are those scrape targets for which the
address are not automatically determined by
`MetricsEndpointConsumer` but instead are specified by the
`MetricsEndpointProvider`.
Args:
targets: a list of addresses of fully qualified hosts.
labels: labels specified by `MetricsEndpointProvider` clients
which are associated with `targets`.
scrape_metadata: scrape related metadata provided by `MetricsEndpointProvider`.
Returns:
A dictionary containing the static scrape configuration
for a list of fully qualified hosts.
"""
juju_labels = self._set_juju_labels(labels, scrape_metadata)
unitless_config = {"targets": targets, "labels": juju_labels}
return unitless_config
def _labeled_unit_config(
self, host_name, host_address, ports, labels, scrape_metadata
) -> dict:
"""Static scrape configuration for a wildcard host.
Wildcard hosts are those scrape targets whose address is
automatically determined by `MetricsEndpointConsumer`.
Args:
host_name: a string representing the unit name of the wildcard host.
host_address: a string representing the address of the wildcard host.
ports: list of ports on which this wildcard host exposes its metrics.
labels: a dictionary of labels provided by
`MetricsEndpointProvider` intended to be associated with
this wildcard host.
scrape_metadata: scrape related metadata provided by `MetricsEndpointProvider`.
Returns:
A dictionary containing the static scrape configuration
for a single wildcard host.
"""
juju_labels = self._set_juju_labels(labels, scrape_metadata)
# '/' is not allowed in Prometheus label names. It technically works,
# but complex queries silently fail
juju_labels["juju_unit"] = f"{host_name.replace('/', '-')}"
static_config = {"labels": juju_labels}
if ports:
targets = []
for port in ports:
targets.append(f"{host_address}:{port}")
static_config["targets"] = targets
else:
static_config["targets"] = [host_address]