-
Notifications
You must be signed in to change notification settings - Fork 5
/
grafana_dashboard.py
2012 lines (1669 loc) · 78.5 KB
/
grafana_dashboard.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 Grafana charm
for the purpose of providing a dashboard which can be used by
end users. It also explains the structure of the data
expected by the `grafana-dashboard` interface, and may provide a
mechanism or reference point for providing a compatible interface
or library by providing a definitive reference guide to the
structure of relation data which is shared between the Grafana
charm and any charm providing datasource information.
## Provider Library Usage
The Grafana charm interacts with its dashboards using its charm
library. The goal of this library is to be as simple to use as
possible, and instantiation of the class with or without changing
the default arguments provides a complete use case. For the simplest
use case of a charm which bundles dashboards and provides a
`provides: grafana-dashboard` interface,
requires:
grafana-dashboard:
interface: grafana_dashboard
creation of a `GrafanaDashboardProvider` object with the default arguments is
sufficient.
:class:`GrafanaDashboardProvider` expects that bundled dashboards should
be included in your charm with a default path of:
path/to/charm.py
path/to/src/grafana_dashboards/*.{json|json.tmpl|.tmpl}
Where the files are Grafana dashboard JSON data either from the
Grafana marketplace, or directly exported from a Grafana instance.
Refer to the [official docs](https://grafana.com/tutorials/provision-dashboards-and-data-sources/)
for more information.
When constructing a dashboard that is intended to be consumed by COS, make sure to use variables
for your datasources, and name them "prometheusds" and "lokids". You can also use the following
juju topology variables in your dashboards: $juju_model, $juju_model_uuid, $juju_application
and $juju_unit. Note, however, that if metrics are coming via peripheral charms (scrape-config
or cos-config) then topology labels would not exist.
The default constructor arguments are:
`charm`: `self` from the charm instantiating this library
`relation_name`: grafana-dashboard
`dashboards_path`: "/src/grafana_dashboards"
If your configuration requires any changes from these defaults, they
may be set from the class constructor. It may be instantiated as
follows:
from charms.grafana_k8s.v0.grafana_dashboard import GrafanaDashboardProvider
class FooCharm:
def __init__(self, *args):
super().__init__(*args, **kwargs)
...
self.grafana_dashboard_provider = GrafanaDashboardProvider(self)
...
The first argument (`self`) should be a reference to the parent (providing
dashboards), as this charm's lifecycle events will be used to re-submit
dashboard information if a charm is upgraded, the pod is restarted, or other.
An instantiated `GrafanaDashboardProvider` validates that the path specified
in the constructor (or the default) exists, reads the file contents, then
compresses them with LZMA and adds them to the application relation data
when a relation is established with Grafana.
Provided dashboards will be checked by Grafana, and a series of dropdown menus
providing the ability to select query targets by Juju Model, application instance,
and unit will be added if they do not exist.
To avoid requiring `jinja` in `GrafanaDashboardProvider` users, template validation
and rendering occurs on the other side of the relation, and relation data in
the form of:
{
"event": {
"valid": `true|false`,
"errors": [],
}
}
Will be returned if rendering or validation fails. In this case, the
`GrafanaDashboardProvider` object will emit a `dashboard_status_changed` event
of the type :class:`GrafanaDashboardEvent`, which will contain information
about the validation error.
This information is added to the relation data for the charms as serialized JSON
from a dict, with a structure of:
```
{
"application": {
"dashboards": {
"uuid": a uuid generated to ensure a relation event triggers,
"templates": {
"file:{hash}": {
"content": `{compressed_template_data}`,
"charm": `charm.meta.name`,
"juju_topology": {
"model": `charm.model.name`,
"model_uuid": `charm.model.uuid`,
"application": `charm.app.name`,
"unit": `charm.unit.name`,
}
},
"file:{other_file_hash}": {
...
},
},
},
},
}
```
This is ingested by :class:`GrafanaDashboardConsumer`, and is sufficient for configuration.
The [COS Configuration Charm](https://charmhub.io/cos-configuration-k8s) can be used to
add dashboards which are not bundled with charms.
## Consumer Library Usage
The `GrafanaDashboardConsumer` object may be used by Grafana
charms to manage relations with available dashboards. For this
purpose, a charm consuming Grafana dashboard information should do
the following things:
1. Instantiate the `GrafanaDashboardConsumer` object by providing it a
reference to the parent (Grafana) charm and, optionally, the name of
the relation that the Grafana charm uses to interact with dashboards.
This relation must confirm to the `grafana-dashboard` interface.
For example a Grafana charm may instantiate the
`GrafanaDashboardConsumer` in its constructor as follows
from charms.grafana_k8s.v0.grafana_dashboard import GrafanaDashboardConsumer
def __init__(self, *args):
super().__init__(*args)
...
self.grafana_dashboard_consumer = GrafanaDashboardConsumer(self)
...
2. A Grafana charm also needs to listen to the
`GrafanaDashboardConsumer` events emitted by the `GrafanaDashboardConsumer`
by adding itself as an observer for these events:
self.framework.observe(
self.grafana_source_consumer.on.sources_changed,
self._on_dashboards_changed,
)
Dashboards can be retrieved the :meth:`dashboards`:
It will be returned in the format of:
```
[
{
"id": unique_id,
"relation_id": relation_id,
"charm": the name of the charm which provided the dashboard,
"content": compressed_template_data
},
]
```
The consuming charm should decompress the dashboard.
"""
import base64
import hashlib
import json
import logging
import lzma
import os
import platform
import re
import subprocess
import tempfile
import uuid
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
import yaml
from ops.charm import (
CharmBase,
HookEvent,
RelationBrokenEvent,
RelationChangedEvent,
RelationCreatedEvent,
RelationEvent,
RelationRole,
)
from ops.framework import (
EventBase,
EventSource,
Object,
ObjectEvents,
StoredDict,
StoredList,
StoredState,
)
from ops.model import Relation
# The unique Charmhub library identifier, never change it
LIBID = "c49eb9c7dfef40c7b6235ebd67010a3f"
# 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 = 32
logger = logging.getLogger(__name__)
DEFAULT_RELATION_NAME = "grafana-dashboard"
DEFAULT_PEER_NAME = "grafana"
RELATION_INTERFACE_NAME = "grafana_dashboard"
TOPOLOGY_TEMPLATE_DROPDOWNS = [ # type: ignore
{
"allValue": ".*",
"datasource": "${prometheusds}",
"definition": "label_values(up,juju_model)",
"description": None,
"error": None,
"hide": 0,
"includeAll": True,
"label": "Juju model",
"multi": True,
"name": "juju_model",
"query": {
"query": "label_values(up,juju_model)",
"refId": "StandardVariableQuery",
},
"refresh": 1,
"regex": "",
"skipUrlSync": False,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": False,
},
{
"allValue": ".*",
"datasource": "${prometheusds}",
"definition": 'label_values(up{juju_model=~"$juju_model"},juju_model_uuid)',
"description": None,
"error": None,
"hide": 0,
"includeAll": True,
"label": "Juju model uuid",
"multi": True,
"name": "juju_model_uuid",
"query": {
"query": 'label_values(up{juju_model=~"$juju_model"},juju_model_uuid)',
"refId": "StandardVariableQuery",
},
"refresh": 1,
"regex": "",
"skipUrlSync": False,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": False,
},
{
"allValue": ".*",
"datasource": "${prometheusds}",
"definition": 'label_values(up{juju_model=~"$juju_model",juju_model_uuid=~"$juju_model_uuid"},juju_application)',
"description": None,
"error": None,
"hide": 0,
"includeAll": True,
"label": "Juju application",
"multi": True,
"name": "juju_application",
"query": {
"query": 'label_values(up{juju_model=~"$juju_model",juju_model_uuid=~"$juju_model_uuid"},juju_application)',
"refId": "StandardVariableQuery",
},
"refresh": 1,
"regex": "",
"skipUrlSync": False,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": False,
},
{
"allValue": ".*",
"datasource": "${prometheusds}",
"definition": 'label_values(up{juju_model=~"$juju_model",juju_model_uuid=~"$juju_model_uuid",juju_application=~"$juju_application"},juju_unit)',
"description": None,
"error": None,
"hide": 0,
"includeAll": True,
"label": "Juju unit",
"multi": True,
"name": "juju_unit",
"query": {
"query": 'label_values(up{juju_model=~"$juju_model",juju_model_uuid=~"$juju_model_uuid",juju_application=~"$juju_application"},juju_unit)',
"refId": "StandardVariableQuery",
},
"refresh": 1,
"regex": "",
"skipUrlSync": False,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": False,
},
]
DATASOURCE_TEMPLATE_DROPDOWNS = [ # type: ignore
{
"description": None,
"error": None,
"hide": 0,
"includeAll": True,
"label": "Prometheus datasource",
"multi": True,
"name": "prometheusds",
"options": [],
"query": "prometheus",
"refresh": 1,
"regex": "",
"skipUrlSync": False,
"type": "datasource",
},
{
"description": None,
"error": None,
"hide": 0,
"includeAll": True,
"label": "Loki datasource",
"multi": True,
"name": "lokids",
"options": [],
"query": "loki",
"refresh": 1,
"regex": "",
"skipUrlSync": False,
"type": "datasource",
},
]
REACTIVE_CONVERTER = { # type: ignore
"allValue": None,
"datasource": "${prometheusds}",
"definition": 'label_values(up{juju_model=~"$juju_model",juju_model_uuid=~"$juju_model_uuid",juju_application=~"$juju_application"},host)',
"description": None,
"error": None,
"hide": 0,
"includeAll": True,
"label": "hosts",
"multi": True,
"name": "host",
"options": [],
"query": {
"query": 'label_values(up{juju_model=~"$juju_model",juju_model_uuid=~"$juju_model_uuid",juju_application=~"$juju_application"},host)',
"refId": "StandardVariableQuery",
},
"refresh": 1,
"regex": "",
"skipUrlSync": False,
"sort": 1,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": False,
}
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 = "No relation named '{}' found".format(relation_name)
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 = (
"The '{}' relation has '{}' as "
"interface rather than the expected '{}'".format(
relation_name, actual_relation_interface, 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 = "The '{}' relation has role '{}' rather than the expected '{}'".format(
relation_name, repr(actual_relation_role), repr(expected_relation_role)
)
super().__init__(self.message)
class InvalidDirectoryPathError(Exception):
"""Raised if the grafana dashboards folder cannot be found or is otherwise invalid."""
def __init__(
self,
grafana_dashboards_absolute_path: str,
message: str,
):
self.grafana_dashboards_absolute_path = grafana_dashboards_absolute_path
self.message = message
super().__init__(self.message)
def _resolve_dir_against_charm_path(charm: CharmBase, *path_elements: str) -> str:
"""Resolve the provided path items against the directory of the main file.
Look up the directory of the charmed operator file being executed. This is normally
going to be the charm.py file of the charm including this library. Then, resolve
the provided path elements and return its absolute path.
Raises:
InvalidDirectoryPathError if the resolved path does not exist or it is not a directory
"""
charm_dir = Path(str(charm.charm_dir))
if not charm_dir.exists() or not charm_dir.is_dir():
# Operator Framework does not currently expose a robust
# way to determine the top level charm source directory
# that is consistent across deployed charms and unit tests
# Hence for unit tests the current working directory is used
# TODO: updated this logic when the following ticket is resolved
# https://github.com/canonical/operator/issues/643
charm_dir = Path(os.getcwd())
dir_path = charm_dir.absolute().joinpath(*path_elements)
if not dir_path.exists():
raise InvalidDirectoryPathError(str(dir_path), "directory does not exist")
if not dir_path.is_dir():
raise InvalidDirectoryPathError(str(dir_path), "is not a directory")
return str(dir_path)
def _validate_relation_by_interface_and_direction(
charm: CharmBase,
relation_name: str,
expected_relation_interface: str,
expected_relation_role: RelationRole,
) -> None:
"""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
named like the value of the `relation_name` argument.
RelationInterfaceMismatchError: If the relation interface of the
relation named as the provided `relation_name` argument does not
match the `expected_relation_interface` argument.
RelationRoleMismatchError: If the relation named as the provided `relation_name`
argument has a different role than what is specified by the
`expected_relation_role` argument.
"""
if relation_name not in charm.meta.relations:
raise RelationNotFoundError(relation_name)
relation = charm.meta.relations[relation_name]
actual_relation_interface = relation.interface_name
if actual_relation_interface and 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("Unexpected RelationDirection: {}".format(expected_relation_role))
def _encode_dashboard_content(content: Union[str, bytes]) -> str:
if isinstance(content, str):
content = bytes(content, "utf-8")
return base64.b64encode(lzma.compress(content)).decode("utf-8")
def _decode_dashboard_content(encoded_content: str) -> str:
return lzma.decompress(base64.b64decode(encoded_content.encode("utf-8"))).decode()
def _convert_dashboard_fields(content: str, inject_dropdowns: bool = True) -> str:
"""Make sure values are present for Juju topology.
Inserts Juju topology variables and selectors into the template, as well as
a variable for Prometheus.
"""
dict_content = json.loads(content)
datasources = {}
existing_templates = False
template_dropdowns = (
TOPOLOGY_TEMPLATE_DROPDOWNS + DATASOURCE_TEMPLATE_DROPDOWNS # type: ignore
if inject_dropdowns
else DATASOURCE_TEMPLATE_DROPDOWNS
)
# If the dashboard has __inputs, get the names to replace them. These are stripped
# from reactive dashboards in GrafanaDashboardAggregator, but charm authors in
# newer charms may import them directly from the marketplace
if "__inputs" in dict_content:
for field in dict_content["__inputs"]:
if "type" in field and field["type"] == "datasource":
datasources[field["name"]] = field["pluginName"].lower()
del dict_content["__inputs"]
# If no existing template variables exist, just insert our own
if "templating" not in dict_content:
dict_content["templating"] = {"list": list(template_dropdowns)} # type: ignore
else:
# Otherwise, set a flag so we can go back later
existing_templates = True
for template_value in dict_content["templating"]["list"]:
# Build a list of `datasource_name`: `datasource_type` mappings
# The "query" field is actually "prometheus", "loki", "influxdb", etc
if "type" in template_value and template_value["type"] == "datasource":
datasources[template_value["name"]] = template_value["query"].lower()
# Put our own variables in the template
for d in template_dropdowns: # type: ignore
if d not in dict_content["templating"]["list"]:
dict_content["templating"]["list"].insert(0, d)
dict_content = _replace_template_fields(dict_content, datasources, existing_templates)
return json.dumps(dict_content)
def _replace_template_fields( # noqa: C901
dict_content: dict, datasources: dict, existing_templates: bool
) -> dict:
"""Make templated fields get cleaned up afterwards.
If existing datasource variables are present, try to substitute them.
"""
replacements = {"loki": "${lokids}", "prometheus": "${prometheusds}"}
used_replacements = [] # type: List[str]
# If any existing datasources match types we know, or we didn't find
# any templating variables at all, template them.
if datasources or not existing_templates:
panels = dict_content.get("panels", {})
if panels:
dict_content["panels"] = _template_panels(
panels, replacements, used_replacements, existing_templates, datasources
)
# Find panels nested under rows
rows = dict_content.get("rows", {})
if rows:
for row_idx, row in enumerate(rows):
if "panels" in row.keys():
rows[row_idx]["panels"] = _template_panels(
row["panels"],
replacements,
used_replacements,
existing_templates,
datasources,
)
dict_content["rows"] = rows
# Finally, go back and pop off the templates we stubbed out
deletions = []
for tmpl in dict_content["templating"]["list"]:
if tmpl["name"] and tmpl["name"] in used_replacements:
deletions.append(tmpl)
for d in deletions:
dict_content["templating"]["list"].remove(d)
return dict_content
def _template_panels(
panels: dict,
replacements: dict,
used_replacements: list,
existing_templates: bool,
datasources: dict,
) -> dict:
"""Iterate through a `panels` object and template it appropriately."""
# Go through all the panels. If they have a datasource set, AND it's one
# that we can convert to ${lokids} or ${prometheusds}, by stripping off the
# ${} templating and comparing the name to the list we built, replace it,
# otherwise, leave it alone.
#
for panel in panels:
if "datasource" not in panel or not panel.get("datasource"):
continue
if not existing_templates:
datasource = panel.get("datasource")
if type(datasource) == str:
if "loki" in datasource:
panel["datasource"] = "${lokids}"
elif "grafana" in datasource:
continue
else:
panel["datasource"] = "${prometheusds}"
elif type(datasource) == dict:
# In dashboards exported by Grafana 9, datasource type is dict
dstype = datasource.get("type", "")
if dstype == "loki":
panel["datasource"]["uid"] = "${lokids}"
elif dstype == "prometheus":
panel["datasource"]["uid"] = "${prometheusds}"
else:
logger.debug("Unrecognized datasource type '%s'; skipping", dstype)
continue
else:
logger.error("Unknown datasource format: skipping")
continue
else:
if type(panel["datasource"]) == str:
if panel["datasource"].lower() in replacements.values():
# Already a known template variable
continue
# Strip out variable characters and maybe braces
ds = re.sub(r"(\$|\{|\})", "", panel["datasource"])
if ds not in datasources.keys():
# Unknown, non-templated datasource, potentially a Grafana builtin
continue
replacement = replacements.get(datasources[ds], "")
if replacement:
used_replacements.append(ds)
panel["datasource"] = replacement or panel["datasource"]
elif type(panel["datasource"]) == dict:
dstype = panel["datasource"].get("type", "")
if panel["datasource"].get("uid", "").lower() in replacements.values():
# Already a known template variable
continue
# Strip out variable characters and maybe braces
ds = re.sub(r"(\$|\{|\})", "", panel["datasource"].get("uid", ""))
if ds not in datasources.keys():
# Unknown, non-templated datasource, potentially a Grafana builtin
continue
replacement = replacements.get(datasources[ds], "")
if replacement:
used_replacements.append(ds)
panel["datasource"]["uid"] = replacement
else:
logger.error("Unknown datasource format: skipping")
continue
return panels
def _inject_labels(content: str, topology: dict, transformer: "CosTool") -> str:
"""Inject Juju topology into panel expressions via CosTool.
A dashboard will have a structure approximating:
{
"__inputs": [],
"templating": {
"list": [
{
"name": "prometheusds",
"type": "prometheus"
}
]
},
"panels": [
{
"foo": "bar",
"targets": [
{
"some": "field",
"expr": "up{job="foo"}"
},
{
"some_other": "field",
"expr": "sum(http_requests_total{instance="$foo"}[5m])}
}
],
"datasource": "${someds}"
}
]
}
`templating` is used elsewhere in this library, but the structure is not rigid. It is
not guaranteed that a panel will actually have any targets (it could be a "spacer" with
no datasource, hence no expression). It could have only one target. It could have multiple
targets. It could have multiple targets of which only one has an `expr` to evaluate. We need
to try to handle all of these concisely.
`cos-tool` (`github.com/canonical/cos-tool` as a Go module in general)
does not know "Grafana-isms", such as using `[$_variable]` to modify the query from the user
interface, so we add placeholders (as `5y`, since it must parse, but a dashboard looking for
five years for a panel query would be unusual).
Args:
content: dashboard content as a string
topology: a dict containing topology values
transformer: a 'CosTool' instance
Returns:
dashboard content with replaced values.
"""
dict_content = json.loads(content)
if "panels" not in dict_content.keys():
return json.dumps(dict_content)
# Go through all the panels and inject topology labels
# Panels may have more than one 'target' where the expressions live, so that must be
# accounted for. Additionally, `promql-transform` does not necessarily gracefully handle
# expressions with range queries including variables. Exclude these.
#
# It is not a certainty that the `datasource` field will necessarily reflect the type, so
# operate on all fields.
panels = dict_content["panels"]
topology_with_prefix = {"juju_{}".format(k): v for k, v in topology.items()}
# We need to use an index so we can insert the changed element back later
for panel_idx, panel in enumerate(panels):
if type(panel) is not dict:
continue
# Use the index to insert it back in the same location
panels[panel_idx] = _modify_panel(panel, topology_with_prefix, transformer)
return json.dumps(dict_content)
def _modify_panel(panel: dict, topology: dict, transformer: "CosTool") -> dict:
"""Inject Juju topology into panel expressions via CosTool.
Args:
panel: a dashboard panel as a dict
topology: a dict containing topology values
transformer: a 'CosTool' instance
Returns:
the panel with injected values
"""
if "targets" not in panel.keys():
return panel
# Pre-compile a regular expression to grab values from inside of []
range_re = re.compile(r"\[(?P<value>.*?)\]")
# Do the same for any offsets
offset_re = re.compile(r"offset\s+(?P<value>-?\s*[$\w]+)")
known_datasources = {"${prometheusds}": "promql", "${lokids}": "logql"}
targets = panel["targets"]
# We need to use an index so we can insert the changed element back later
for idx, target in enumerate(targets):
# If there's no expression, we don't need to do anything
if "expr" not in target.keys():
continue
expr = target["expr"]
if "datasource" not in panel.keys():
continue
if type(panel["datasource"]) == str:
if panel["datasource"] not in known_datasources:
continue
querytype = known_datasources[panel["datasource"]]
elif type(panel["datasource"]) == dict:
if panel["datasource"]["uid"] not in known_datasources:
continue
querytype = known_datasources[panel["datasource"]["uid"]]
else:
logger.error("Unknown datasource format: skipping")
continue
# Capture all values inside `[]` into a list which we'll iterate over later to
# put them back in-order. Then apply the regex again and replace everything with
# `[5y]` so promql/parser will take it.
#
# Then do it again for offsets
range_values = [m.group("value") for m in range_re.finditer(expr)]
expr = range_re.sub(r"[5y]", expr)
offset_values = [m.group("value") for m in offset_re.finditer(expr)]
expr = offset_re.sub(r"offset 5y", expr)
# Retrieve the new expression (which may be unchanged if there were no label
# matchers in the expression, or if tt was unable to be parsed like logql. It's
# virtually impossible to tell from any datasource "name" in a panel what the
# actual type is without re-implementing a complete dashboard parser, but no
# harm will some from passing invalid promql -- we'll just get the original back.
#
replacement = transformer.inject_label_matchers(expr, topology, querytype)
if replacement == target["expr"]:
# promql-tranform caught an error. Move on
continue
# Go back and substitute values in [] which were pulled out
# Enumerate with an index... again. The same regex is ok, since it will still match
# `[(.*?)]`, which includes `[5y]`, our placeholder
for i, match in enumerate(range_re.finditer(replacement)):
# Replace one-by-one, starting from the left. We build the string back with
# `str.replace(string_to_replace, replacement_value, count)`. Limit the count
# to one, since we are going through one-by-one through the list we saved earlier
# in `range_values`.
replacement = replacement.replace(
"[{}]".format(match.group("value")),
"[{}]".format(range_values[i]),
1,
)
for i, match in enumerate(offset_re.finditer(replacement)):
# Replace one-by-one, starting from the left. We build the string back with
# `str.replace(string_to_replace, replacement_value, count)`. Limit the count
# to one, since we are going through one-by-one through the list we saved earlier
# in `range_values`.
replacement = replacement.replace(
"offset {}".format(match.group("value")),
"offset {}".format(offset_values[i]),
1,
)
# Use the index to insert it back in the same location
targets[idx]["expr"] = replacement
panel["targets"] = targets
return panel
def _type_convert_stored(obj):
"""Convert Stored* to their appropriate types, recursively."""
if isinstance(obj, StoredList):
return list(map(_type_convert_stored, obj))
if isinstance(obj, StoredDict):
rdict = {} # type: Dict[Any, Any]
for k in obj.keys():
rdict[k] = _type_convert_stored(obj[k])
return rdict
return obj
class GrafanaDashboardsChanged(EventBase):
"""Event emitted when Grafana dashboards change."""
def __init__(self, handle, data=None):
super().__init__(handle)
self.data = data
def snapshot(self) -> Dict:
"""Save grafana source information."""
return {"data": self.data}
def restore(self, snapshot):
"""Restore grafana source information."""
self.data = snapshot["data"]
class GrafanaDashboardEvents(ObjectEvents):
"""Events raised by :class:`GrafanaSourceEvents`."""
dashboards_changed = EventSource(GrafanaDashboardsChanged)
class GrafanaDashboardEvent(EventBase):
"""Event emitted when Grafana dashboards cannot be resolved.
Enables us to set a clear status on the provider.
"""
def __init__(self, handle, errors: List[Dict[str, str]] = [], valid: bool = False):
super().__init__(handle)
self.errors = errors
self.error_message = "; ".join([error["error"] for error in errors if "error" in error])
self.valid = valid
def snapshot(self) -> Dict:
"""Save grafana source information."""
return {
"error_message": self.error_message,
"valid": self.valid,
"errors": json.dumps(self.errors),
}
def restore(self, snapshot):
"""Restore grafana source information."""
self.error_message = snapshot["error_message"]
self.valid = snapshot["valid"]
self.errors = json.loads(str(snapshot["errors"]))
class GrafanaProviderEvents(ObjectEvents):
"""Events raised by :class:`GrafanaSourceEvents`."""
dashboard_status_changed = EventSource(GrafanaDashboardEvent)
class GrafanaDashboardProvider(Object):
"""An API to provide Grafana dashboards to a Grafana charm."""
_stored = StoredState()
on = GrafanaProviderEvents() # pyright: ignore
def __init__(
self,
charm: CharmBase,
relation_name: str = DEFAULT_RELATION_NAME,
dashboards_path: str = "src/grafana_dashboards",
) -> None:
"""API to provide Grafana dashboard to a Grafana charmed operator.
The :class:`GrafanaDashboardProvider` object provides an API
to upload dashboards to a Grafana charm. In its most streamlined
usage, the :class:`GrafanaDashboardProvider` is integrated in a
charmed operator as follows:
self.grafana = GrafanaDashboardProvider(self)
The :class:`GrafanaDashboardProvider` will look for dashboard
templates in the `<charm-py-directory>/grafana_dashboards` folder.
Additionally, dashboard templates can be uploaded programmatically
via the :method:`GrafanaDashboardProvider.add_dashboard` method.
To use the :class:`GrafanaDashboardProvider` API, you need a relation
defined in your charm operator's metadata.yaml as follows:
provides:
grafana-dashboard:
interface: grafana_dashboard
If you would like to use relation name other than `grafana-dashboard`,