From: Pere Diaz Bou Date: Tue, 14 Dec 2021 08:25:49 +0000 (+0100) Subject: monitoring/grafana: doctest util regex X-Git-Tag: v16.2.8~6^2~5 X-Git-Url: http://git-server-git.apps.pok.os.sepia.ceph.com/?a=commitdiff_plain;h=68a3d0fa802f17b483079dfb8dd548dd601516cb;p=ceph.git monitoring/grafana: doctest util regex Signed-off-by: Pere Diaz Bou --- diff --git a/monitoring/ceph-mixin/tests_dashboards/__init__.py b/monitoring/ceph-mixin/tests_dashboards/__init__.py index 204a5f0d721b..45147e5c3249 100644 --- a/monitoring/ceph-mixin/tests_dashboards/__init__.py +++ b/monitoring/ceph-mixin/tests_dashboards/__init__.py @@ -7,6 +7,8 @@ from typing import Any, List import yaml +from .util import replace_grafana_expr_variables + @dataclass class InputSeries: @@ -171,7 +173,7 @@ class PromqlTest: for variable, value in self.variables.items(): expr = self.promql_expr_test.expr - new_expr = re.sub(r'\${0}'.format(variable), str(value), expr) + new_expr = replace_grafana_expr_variables(expr, variable, value) self.set_expression(new_expr) test_as_dict = asdict(self.test_file) diff --git a/monitoring/ceph-mixin/tests_dashboards/util.py b/monitoring/ceph-mixin/tests_dashboards/util.py index b5872deafc99..1d8b57325eb0 100644 --- a/monitoring/ceph-mixin/tests_dashboards/util.py +++ b/monitoring/ceph-mixin/tests_dashboards/util.py @@ -1,4 +1,5 @@ import json +import re from pathlib import Path from typing import Any, Dict, Tuple, Union @@ -67,3 +68,25 @@ def add_dashboard_variables(data: Dict[str, Any], dashboard_data: Dict[str, Any] for variable in dashboard_data['templating']['list']: if 'name' in variable: data['variables'][variable['name']] = 'UNSET VARIABLE' + + +def replace_grafana_expr_variables(expr: str, variable: str, value: Any) -> str: + """ Replace grafana variables in expression with a value + + It should match the whole word, 'osd' musn't match with the 'osd' prefix in 'osd_hosts' + >>> replace_grafana_expr_variables('metric{name~="$osd_hosts|$other|$osd"}', \ + 'osd', 'replacement') + 'metric{name~="$osd_hosts|$other|replacement"}' + + >>> replace_grafana_expr_variables('metric{name~="$osd_hosts|$other|$osd"}', \ + 'other', 'replacement') + 'metric{name~="$osd_hosts|replacement|$osd"}' + + It replaces words with dollar prefix + >>> replace_grafana_expr_variables('metric{name~="no_dollar|$other|$osd"}', \ + 'no_dollar', 'replacement') + 'metric{name~="no_dollar|$other|$osd"}' + """ + regex = fr'\${variable}(?=\W)' + new_expr = re.sub(regex, fr'{str(value)}', expr) + return new_expr