Test rendered Kubernetes manifests with conftest before they merge
Run conftest against rendered Kubernetes manifests from a CI webhook and escalate every failed rule as a GitHub issue and a Slack alert.
Compare every Grafana PromQL query on two backends before moving to Prometheus 3, VictoriaMetrics or Mimir. Repoint dashboards after approval and roll back.
# SPDX-License-Identifier: Apache-2.0
id: grafana-prometheus-backend-switch-with-query-parity
namespace: company.team
description: Move Grafana dashboards from one Prometheus-compatible backend to
another. Every PromQL query of the dashboards and of the source rules runs on
both backends first. Dashboards are repointed only after a person has seen
which panels would answer differently.
concurrency:
limit: 1
behavior: QUEUE
inputs:
- id: mode
type: SELECT
values:
- ANALYZE
- SWITCH
- ROLLBACK
defaults: ANALYZE
description: ANALYZE compares the two backends and changes nothing. SWITCH
repoints dashboards to the new backend and checks them through Grafana.
ROLLBACK restores the dashboards that SWITCH changed.
- id: grafana_url
type: STRING
defaults: http://grafana:3000
description: Base URL of Grafana, reachable from the worker.
- id: grafana_token
type: SECRET
defaults: "{{ secret('GRAFANA_TOKEN') }}"
description: Service account token with the Editor role. A user:password pair
also works.
- id: source_datasource_uid
type: STRING
validator: ^[A-Za-z0-9_-]{1,60}$
description: UID of the Grafana datasource of the old backend. Dashboards that
use it are analyzed.
- id: source_url
type: STRING
description: URL of the old backend, reachable from the worker, for example
http://prometheus:9090.
- id: target_url
type: STRING
description: URL of the new backend, reachable from the worker. It must answer
the Prometheus HTTP API (/api/v1/query_range).
- id: target_grafana_url
type: STRING
defaults: ""
description: URL of the new backend as Grafana reaches it. Empty means the same
as target_url.
- id: target_datasource_uid
type: STRING
defaults: ""
validator: ^[A-Za-z0-9_-]{0,60}$
description: UID of the datasource that SWITCH creates for the new backend.
Empty means the source UID followed by -new.
- id: source_headers
type: SECRET
defaults: ""
description: JSON object of HTTP headers for the old backend, for example a
tenant header. Leave empty for none.
- id: target_headers
type: SECRET
defaults: ""
description: JSON object of HTTP headers for the new backend, for example
{"X-Scope-OrgID":"team"}.
- id: target_datasource_json
type: SECRET
defaults: ""
description: Optional JSON merged into the new Grafana datasource, with jsonData
and secureJsonData keys, for credentials or tenant headers.
- id: window
type: STRING
defaults: PT30M
validator: ^PT([0-9]+H)?([0-9]+M)?$
description: How far back the queries are compared. Both backends must hold data
for this window.
- id: step
type: STRING
defaults: 15s
validator: ^[0-9]+(s|m)$
description: Resolution of the comparison.
- id: rate_interval
type: STRING
defaults: 1m
validator: ^[0-9]+(s|m|h)$
description: Value used for $__rate_interval in the dashboard queries.
- id: rel_tol
type: STRING
defaults: "0.01"
validator: ^[0-9]*\.?[0-9]+$
description: Relative difference that still counts as equal. 0.01 is one percent.
- id: ignore_labels
type: STRING
defaults: ""
validator: ^[A-Za-z0-9_,]*$
description: Comma separated label names that are left out of the comparison,
for example __name__ or a label the new backend adds.
- id: dashboard_tags
type: STRING
defaults: ""
validator: ^[A-Za-z0-9_,-]*$
description: Only dashboards with one of these tags. Empty means all dashboards.
- id: folder_uids
type: STRING
defaults: ""
validator: ^[A-Za-z0-9_,-]*$
description: Only dashboards in these folders. Empty means all folders.
- id: include_rules
type: BOOL
defaults: true
description: Also compare the alerting and recording rules of the old backend.
- id: migration_name
type: STRING
defaults: grafana-backend
validator: ^[a-z0-9-]{1,40}$
description: Name of the migration. Its state is kept in the namespace KV store
under this name.
- id: tools_image
type: STRING
defaults: python:3.12-alpine
description: Image with Python 3.
- id: docker_network
type: STRING
defaults: bridge
description: Docker network of the task containers. They must reach Grafana and
both backends.
- id: dry_run
type: BOOL
defaults: true
description: Plan only. No dashboard and no datasource is changed.
- id: auto_remediate
type: BOOL
defaults: false
description: Allows the flow to change Grafana. A change runs only when this is
true and dry_run is false. Each change waits for an approval.
variables:
live: "{{ inputs.dry_run == false and inputs.auto_remediate == true }}"
approval_window: PT24H
target_uid: "{{ inputs.target_datasource_uid == '' ?
inputs.source_datasource_uid ~ '-new' : inputs.target_datasource_uid }}"
lib_py: |
import base64, json, math, os, re, sys, urllib.error, urllib.parse, urllib.request
def out(**values):
print('::' + json.dumps({'outputs': values}) + '::')
def http(method, url, body=None, headers=None, timeout=60):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method, headers={'Content-Type': 'application/json', **(headers or {})})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
raw = r.read()
return r.status, (json.loads(raw) if raw[:1] in b'{[' else raw.decode())
except urllib.error.HTTPError as e:
raw = e.read().decode()
try:
return e.code, json.loads(raw)
except ValueError:
return e.code, raw
except Exception as e:
return 0, str(e)
def grafana(method, path, body=None):
base = os.environ['GRAFANA_URL'].rstrip('/')
token = os.environ.get('GRAFANA_TOKEN', '')
headers = {'Authorization': 'Bearer ' + token} if token and ':' not in token else {'Authorization': 'Basic ' + base64.b64encode(token.encode()).decode()}
return http(method, base + path, body, headers)
def prom(base, path, params, timeout=60):
return http('GET', base.rstrip('/') + path + '?' + urllib.parse.urlencode(params), timeout=timeout)
def need(status, body, what):
if status != 200:
sys.exit('%s failed with HTTP %s: %s' % (what, status, str(body)[:300]))
return body
def seconds(text):
m = re.fullmatch(r'(\d+)(ms|s|m|h|d)', text.strip())
if not m:
sys.exit('"%s" is not a duration such as 30s, 5m or 6h' % text)
return int(m.group(1)) * {'ms': 0.001, 's': 1, 'm': 60, 'h': 3600, 'd': 86400}[m.group(2)]
def iso_to_seconds(text):
m = re.fullmatch(r'PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?', text.strip())
if not m or not any(m.groups()):
sys.exit('"%s" is not a duration such as PT10M or PT6H' % text)
h, mi, s = (int(x or 0) for x in m.groups())
return h * 3600 + mi * 60 + s
REL = float(os.environ.get('REL_TOL', '0.01'))
ABS = float(os.environ.get('ABS_TOL', '1e-9'))
EDGE = int(os.environ.get('EDGE_POINTS', '2'))
IGNORE = {x.strip() for x in os.environ.get('IGNORE_LABELS', '').split(',') if x.strip()}
def close(a, b):
if math.isnan(a) and math.isnan(b):
return True
if math.isinf(a) or math.isinf(b):
return a == b
return abs(a - b) <= max(ABS, REL * max(abs(a), abs(b)))
def matrix_to_series(body):
res = {}
for r in body['data']['result']:
key = tuple(sorted((k, v) for k, v in r['metric'].items() if k not in IGNORE))
res[key] = {round(float(t), 3): float(v) for t, v in r['values']}
return res
def compare_series(sa, sb):
"""Verdict for two {labels: {timestamp: value}} maps, the first one being the source."""
if not sa and not sb:
return {'verdict': 'EMPTY_BOTH', 'detail': 'no data in the window on either backend'}
if sa and not sb:
return {'verdict': 'EMPTY_TARGET', 'detail': '%d series on the source, none on the target' % len(sa)}
only_a, only_b = [k for k in sa if k not in sb], [k for k in sb if k not in sa]
compared = bad = missing = 0
worst = 0.0
for k, pts in sa.items():
other = sb.get(k, {})
for t, v in pts.items():
if t not in other:
missing += 1
continue
compared += 1
if not close(v, other[t]):
bad += 1
worst = max(worst, abs(v - other[t]) / max(abs(v), abs(other[t]), 1e-12))
extra = sum(1 for k in sb for t in sb[k] if k in sa and t not in sa[k])
problems = []
if only_a or only_b:
problems.append('series only on the source: %d, only on the target: %d' % (len(only_a), len(only_b)))
if bad:
problems.append('%d of %d points differ by more than %g%%, the largest by %.2f%%' % (bad, compared, REL * 100, worst * 100))
if missing > EDGE * max(len(sa), 1):
problems.append('%d source points have no target point' % missing)
if extra > EDGE * max(len(sa), 1):
problems.append('%d target points have no source point' % extra)
return {'verdict': 'DIFF' if problems else 'MATCH', 'detail': '; '.join(problems) or '%d points equal within %g%%' % (compared, REL * 100), 'series': len(sa), 'compared': compared, 'bad': bad, 'missing': missing}
collect_py: |
import json, os, re, sys
from lib import *
SRC_UID = os.environ['SOURCE_DS_UID']
STEP = seconds(os.environ.get('STEP', '15s'))
WINDOW = iso_to_seconds(os.environ.get('WINDOW', 'PT30M'))
RATE_INTERVAL = os.environ.get('RATE_INTERVAL', '1m')
TAGS = [t for t in os.environ.get('DASHBOARD_TAGS', '').split(',') if t.strip()]
FOLDERS = [t for t in os.environ.get('FOLDER_UIDS', '').split(',') if t.strip()]
ONLY = {t.strip() for t in os.environ.get('DASHBOARD_UIDS', '').split(',') if t.strip()}
ds = need(*grafana('GET', '/api/datasources/uid/' + SRC_UID), 'reading the source datasource')
if ds.get('type') != 'prometheus':
sys.exit('Datasource %s is a %s datasource, not a prometheus one.' % (SRC_UID, ds.get('type')))
is_default = bool(ds.get('isDefault'))
params = '?type=dash-db&limit=5000' + ''.join('&tag=' + t.strip() for t in TAGS) + ''.join('&folderUIDs=' + f.strip() for f in FOLDERS)
found = need(*grafana('GET', '/api/search' + params), 'listing dashboards')
if ONLY:
found = [f for f in found if f['uid'] in ONLY]
def refers(d):
"""True when a panel or target uses the source datasource (or the default one when it names none)."""
if d is None or d == '':
return is_default
if isinstance(d, str):
return d in (SRC_UID, ds.get('name'))
return d.get('uid') == SRC_UID or (d.get('uid') in (None, '') and is_default)
def builtin(expr):
rep = {'$__rate_interval': RATE_INTERVAL, '${__rate_interval}': RATE_INTERVAL, '$__interval': '%ds' % STEP, '${__interval}': '%ds' % STEP,
'$__interval_ms': str(int(STEP * 1000)), '$__range': '%ds' % WINDOW, '${__range}': '%ds' % WINDOW, '$__range_s': str(int(WINDOW)), '$__range_ms': str(int(WINDOW * 1000))}
for k in sorted(rep, key=len, reverse=True):
expr = expr.replace(k, rep[k])
return expr
def var_value(v):
cur = v.get('current') or {}
val = cur.get('value')
if v.get('type') == 'constant':
return v.get('query')
if val in ('$__all', ['$__all']):
return v.get('allValue') or '.*'
if isinstance(val, list):
return '|'.join(str(x) for x in val)
return None if val is None else str(val)
def substitute(expr, variables):
expr = builtin(expr)
for name, value in variables.items():
if value is None:
continue
for pat in ('$' + '{' + name + '}', '$' + name, '[[' + name + ']]'):
expr = re.sub(re.escape(pat) + (r'(?![A-Za-z0-9_])' if pat.startswith('$') and not pat.endswith('}') else ''), lambda m: value, expr)
return expr
queries, skipped, versions = [], [], {}
for item in found:
d = need(*grafana('GET', '/api/dashboards/uid/' + item['uid']), 'reading dashboard ' + item['uid'])['dashboard']
versions[item['uid']] = d.get('version', 0)
variables = {v['name']: var_value(v) for v in d.get('templating', {}).get('list', []) if v.get('name')}
def walk(panels):
for p in panels:
yield p
if p.get('panels'):
yield from walk(p['panels'])
for p in walk(d.get('panels', [])):
for t in p.get('targets', []):
expr = t.get('expr')
if not expr or t.get('hide'):
continue
if not refers(t.get('datasource') or p.get('datasource')):
continue
final = substitute(expr, variables)
if re.search(r'\$[A-Za-z_{]', final):
skipped.append('%s / %s: a variable stays unresolved' % (d['title'], p.get('title', p.get('id'))))
continue
queries.append({'kind': 'dashboard', 'dashboard': d['uid'], 'dashboard_title': d['title'], 'panel': p.get('id'), 'panel_title': p.get('title', ''), 'ref': t.get('refId', ''), 'expr': final})
if os.environ.get('INCLUDE_RULES', 'true') == 'true':
s, r = prom(os.environ['SOURCE_URL'], '/api/v1/rules', {})
if s == 200:
for g in r['data']['groups']:
for rule in g['rules']:
queries.append({'kind': 'rule', 'dashboard': '', 'dashboard_title': '', 'panel': None, 'panel_title': '%s %s' % (g['name'], rule['name']), 'ref': rule['type'], 'expr': rule['query']})
else:
skipped.append('the rules of the source could not be read (HTTP %s)' % s)
alert_rules = 0
s, rules = grafana('GET', '/api/v1/provisioning/alert-rules')
if s == 200 and isinstance(rules, list):
alert_rules = sum(any(x.get('datasourceUid') == SRC_UID for x in r.get('data', [])) for r in rules)
unique = {}
for q in queries:
unique.setdefault(q['expr'], []).append({k: q[k] for k in ('kind', 'dashboard', 'dashboard_title', 'panel', 'panel_title', 'ref')})
used = {q['dashboard'] for q in queries if q['kind'] == 'dashboard'}
used_found = [i for i in found if i['uid'] in used]
json.dump({'dashboards': [{'uid': i['uid'], 'title': i['title'], 'folder': i.get('folderTitle', ''), 'version': versions[i['uid']]} for i in used_found], 'queries': [{'expr': e, 'uses': u} for e, u in unique.items()], 'skipped': skipped}, open('queries.json', 'w'), indent=1)
out(alert_rules_on_source=alert_rules, versions=','.join('%s:%s' % (i['uid'], versions[i['uid']]) for i in used_found), dashboards=len(used_found), queries=len(queries), unique_queries=len(unique), rules=sum(q['kind'] == 'rule' for q in queries), skipped=len(skipped), skipped_list='; '.join(skipped)[:600])
parity_py: |
import concurrent.futures, json, math, os, time
from lib import *
STEP = seconds(os.environ.get('STEP', '15s'))
WINDOW = iso_to_seconds(os.environ.get('WINDOW', 'PT30M'))
LAG = int(os.environ.get('LAG_SECONDS', '30'))
SRC, TGT = os.environ['SOURCE_URL'], os.environ['TARGET_URL']
SRC_H = json.loads(os.environ.get('SOURCE_HEADERS') or '{}')
TGT_H = json.loads(os.environ.get('TARGET_HEADERS') or '{}')
end = int((time.time() - LAG) // STEP * STEP)
start = int(end - WINDOW)
def run(base, headers, expr):
q = base.rstrip('/') + '/api/v1/query_range?' + urllib.parse.urlencode({'query': expr, 'start': start, 'end': end, 'step': int(STEP)})
return http('GET', q, headers=headers, timeout=120)
def judge(expr):
s1, a = run(SRC, SRC_H, expr)
s2, b = run(TGT, TGT_H, expr)
if s1 != 200 or a.get('status') != 'success':
return {'verdict': 'SOURCE_ERROR', 'detail': str(a)[:200]}
if s2 != 200 or not isinstance(b, dict) or b.get('status') != 'success':
msg = b.get('error') if isinstance(b, dict) and b.get('error') else str(b)
return {'verdict': 'ERROR', 'detail': str(msg)[:240]}
return compare_series(matrix_to_series(a), matrix_to_series(b))
qs = json.load(open('queries.json'))
with concurrent.futures.ThreadPoolExecutor(max_workers=int(os.environ.get('PAR', '6'))) as ex:
results = list(ex.map(lambda q: {**q, **judge(q['expr'])}, qs['queries']))
json.dump({'start': start, 'end': end, 'step': STEP, 'results': results, 'dashboards': qs['dashboards']}, open('parity.json', 'w'), indent=1)
count = lambda v: sum(r['verdict'] == v for r in results)
rank = {'SOURCE_ERROR': 0, 'EMPTY_BOTH': 0, 'MATCH': 0, 'DIFF': 2, 'EMPTY_TARGET': 3, 'ERROR': 4}
per = {}
for r in results:
for u in r['uses']:
if u['kind'] == 'dashboard':
per.setdefault(u['dashboard'], []).append((r['verdict'], u['panel_title'], r['expr'], r['detail']))
titles = {d['uid']: d['title'] for d in qs['dashboards']}
blocked = sorted(d for d, rows in per.items() if any(rank[v] > 0 for v, *_ in rows))
clean = sorted(d for d in titles if d not in blocked)
rows = ['| Dashboard | Panel | Result | Why |', '|---|---|---|---|']
for d in sorted(per):
for v, panel, expr, detail in per[d]:
if v not in ('MATCH', 'EMPTY_BOTH'):
rows.append('| %s | %s | %s | %s |' % (titles[d], panel, v, detail.replace('|', '/')))
rule_rows = [r for r in results if any(u['kind'] == 'rule' for u in r['uses']) and r['verdict'] not in ('MATCH', 'EMPTY_BOTH')]
for r in rule_rows:
rows.append('| (rule) | %s | %s | %s |' % (r['uses'][0]['panel_title'], r['verdict'], r['detail'].replace('|', '/')))
open('report.md', 'w').write('\n'.join(rows) + '\n' if len(rows) > 2 else 'Every query returned the same answer on both backends.\n')
out(window_start=start, window_end=end, queries=len(results), match=count('MATCH'), diff=count('DIFF'), error=count('ERROR'), empty_target=count('EMPTY_TARGET'), empty_both=count('EMPTY_BOTH'), source_error=count('SOURCE_ERROR'),
dashboards=len(titles), clean_dashboards=','.join(clean), blocked_dashboards=','.join(blocked), clean_count=len(clean), blocked_count=len(blocked), rule_problems=len(rule_rows))
switch_py: |
import json, os, sys
from lib import *
SRC, NEW = os.environ['SOURCE_DS_UID'], os.environ['TARGET_DS_UID']
UIDS = [u.strip() for u in os.environ['DASHBOARD_UIDS'].split(',') if u.strip()]
TARGET_GRAFANA_URL = os.environ.get('TARGET_GRAFANA_URL') or os.environ['TARGET_URL']
EXTRA = json.loads(os.environ.get('TARGET_DS_JSON') or '{}')
src = need(*grafana('GET', '/api/datasources/uid/' + SRC), 'reading the source datasource')
s, existing = grafana('GET', '/api/datasources/uid/' + NEW)
if s == 404:
body = {'name': src['name'] + ' (new)', 'uid': NEW, 'type': 'prometheus', 'access': 'proxy', 'url': TARGET_GRAFANA_URL, 'isDefault': False,
'jsonData': {**(src.get('jsonData') or {}), 'httpMethod': 'POST', **EXTRA.get('jsonData', {})}, 'secureJsonData': EXTRA.get('secureJsonData', {})}
need(*grafana('POST', '/api/datasources', body), 'creating the new datasource')
created = True
else:
need(s, existing, 'reading the new datasource')
created = False
hs, health = grafana('GET', '/api/datasources/uid/%s/health' % NEW)
if hs != 200 and not isinstance(health, dict):
health = {'status': 'ERROR', 'message': str(health)[:200]}
if not isinstance(health, dict):
health = {'status': 'ERROR', 'message': str(health)[:200]}
if health.get('status') != 'OK':
if created:
grafana('DELETE', '/api/datasources/uid/' + NEW)
sys.exit('The new datasource is not healthy, so no dashboard was changed: %s' % health.get('message'))
def remap(value, holder):
if isinstance(value, dict) and value.get('uid') == SRC:
return {'type': 'prometheus', 'uid': NEW}
if isinstance(value, str) and value in (SRC, src['name']):
return {'type': 'prometheus', 'uid': NEW}
if value in (None, '') and src.get('isDefault') and ('expr' in holder or 'targets' in holder):
return {'type': 'prometheus', 'uid': NEW}
return value
def rewrite(node):
n = 0
if isinstance(node, dict):
if 'datasource' in node:
new = remap(node['datasource'], node)
if new != node['datasource']:
node['datasource'] = new
n += 1
for v in node.values():
n += rewrite(v)
elif isinstance(node, list):
for v in node:
n += rewrite(v)
return n
ANALYZED = dict(x.split(':') for x in os.environ.get('ANALYZED', '').split(',') if ':' in x)
moved, skipped, failed = [], [], []
for uid in UIDS:
s, cur = grafana('GET', '/api/dashboards/uid/' + uid)
if s != 200:
failed.append('%s: cannot read (HTTP %s)' % (uid, s))
continue
dash, meta = cur['dashboard'], cur['meta']
before = dash['version']
if uid in ANALYZED and str(before) != ANALYZED[uid]:
failed.append('%s: saved after the analysis (version %s, analyzed %s)' % (uid, before, ANALYZED[uid]))
continue
if rewrite(dash) == 0:
skipped.append(uid)
continue
s, res = grafana('POST', '/api/dashboards/db', {'dashboard': dash, 'overwrite': False, 'message': 'Repointed from %s to %s by Kestra' % (SRC, NEW), 'folderUid': meta.get('folderUid', '')})
if s == 200:
moved.append('%s:%d:%d' % (uid, before, res['version']))
else:
failed.append('%s: Grafana answered HTTP %s %s' % (uid, s, str(res)[:160]))
out(datasource_created=created, moved=len(moved), moved_list=','.join(moved), skipped=len(skipped), skipped_list=','.join(skipped), failed=len(failed), failed_list='; '.join(failed)[:600])
verify_py: |
import concurrent.futures, json, os, subprocess, sys, time
from lib import *
SRC, NEW = os.environ['SOURCE_DS_UID'], os.environ['TARGET_DS_UID']
STEP = seconds(os.environ.get('STEP', '15s'))
WINDOW = iso_to_seconds(os.environ.get('WINDOW', 'PT30M'))
IGNORE.add('name')
# read the queries again from the repointed dashboards: they must now use the new datasource
env = {**os.environ, 'SOURCE_DS_UID': NEW, 'INCLUDE_RULES': 'false'}
r = subprocess.run([sys.executable, 'collect.py'], env=env, capture_output=True, text=True)
if r.returncode != 0:
sys.exit(r.stdout + r.stderr)
qs = json.load(open('queries.json'))
end = int((time.time() - int(os.environ.get('LAG_SECONDS', '30'))) // STEP * STEP)
start = end - WINDOW
def ask(uid, expr):
body = {'queries': [{'refId': 'A', 'datasource': {'type': 'prometheus', 'uid': uid}, 'expr': expr, 'range': True, 'instant': False, 'intervalMs': int(STEP * 1000), 'maxDataPoints': 2000}],
'from': str(start * 1000), 'to': str(end * 1000)}
s, b = grafana('POST', '/api/ds/query', body)
if s != 200:
return s, b
res = b['results']['A']
if res.get('error'):
return 400, res['error']
return 200, res.get('frames', [])
def to_series(frames):
out = {}
for f in frames:
fields = f['schema']['fields']
times, values = f['data']['values'][0], f['data']['values'][1]
labels = dict(fields[1].get('labels') or {})
key = tuple(sorted((k, v) for k, v in labels.items() if k not in IGNORE))
out[key] = {round(t / 1000, 3): float(v) for t, v in zip(times, values) if v is not None}
return out
def judge(expr):
s1, a = ask(SRC, expr)
s2, b = ask(NEW, expr)
if s1 != 200:
return {'verdict': 'SOURCE_ERROR', 'detail': str(a)[:200]}
if s2 != 200:
return {'verdict': 'ERROR', 'detail': str(b)[:240]}
return compare_series(to_series(a), to_series(b))
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as ex:
results = list(ex.map(lambda q: {**q, **judge(q['expr'])}, qs['queries']))
MUST = {u.strip() for u in os.environ.get('MUST_MATCH', '').split(',') if u.strip()}
bad = [x for x in results if x['verdict'] not in ('MATCH', 'EMPTY_BOTH')]
must = [x for x in bad if not MUST or any(u['dashboard'] in MUST for u in x['uses'])]
json.dump(results, open('verify.json', 'w'), indent=1)
rows = ['| Dashboard | Panel | Result | Why |', '|---|---|---|---|'] + ['| %s | %s | %s | %s |' % (x['uses'][0]['dashboard_title'], x['uses'][0]['panel_title'], x['verdict'], x['detail'].replace('|', '/')) for x in bad]
open('verify.md', 'w').write('\n'.join(rows) + '\n' if bad else 'Grafana answers the same through the new datasource.\n')
out(must_match_problems=len(must), checked=len(results), match=sum(x['verdict'] == 'MATCH' for x in results), empty_both=sum(x['verdict'] == 'EMPTY_BOTH' for x in results), problems=len(bad),
problem_list='; '.join('%s [%s]' % (x['expr'][:60], x['verdict']) for x in must)[:800])
rollback_py: |
import json, os, sys
from lib import *
# MOVED is uid:before:after,... as written by switch.py. A dashboard is restored only when nobody saved it since the switch.
restored, edited, failed = [], [], []
for item in [m for m in os.environ['MOVED'].split(',') if m]:
uid, before, after = item.split(':')
s, cur = grafana('GET', '/api/dashboards/uid/' + uid)
if s != 200:
failed.append('%s: cannot read (HTTP %s)' % (uid, s))
continue
if cur['dashboard']['version'] != int(after):
edited.append(uid)
continue
s, old = grafana('GET', '/api/dashboards/uid/%s/versions/%s' % (uid, before))
if s != 200:
failed.append('%s: version %s cannot be read (HTTP %s)' % (uid, before, s))
continue
dash = old.get('data') or old.get('dashboard')
dash['version'] = cur['dashboard']['version']
dash['id'] = cur['dashboard'].get('id')
s, res = grafana('POST', '/api/dashboards/db', {'dashboard': dash, 'overwrite': False, 'message': 'Restored to version %s by Kestra' % before, 'folderUid': cur['meta'].get('folderUid', '')})
(restored if s == 200 else failed).append(uid if s == 200 else '%s: HTTP %s %s' % (uid, s, str(res)[:120]))
out(restored=len(restored), restored_list=','.join(restored), edited=len(edited), edited_list=','.join(edited), failed=len(failed), failed_list='; '.join(failed)[:500])
tasks:
- id: label_run
type: io.kestra.plugin.core.execution.Labels
labels:
migration: "{{ inputs.migration_name }}"
mode: "{{ inputs.mode | lower }}"
- id: read_state
type: io.kestra.plugin.core.kv.Get
key: "grafana-backend-{{ inputs.migration_name }}"
errorOnMissing: false
- id: current
type: io.kestra.plugin.core.output.OutputValues
values:
state: "{{ (outputs.read_state.value ?? {}).state ?? 'NONE' }}"
moved: "{{ (outputs.read_state.value ?? {}).moved ?? '' }}"
- id: require_allowed_state
type: io.kestra.plugin.core.execution.Fail
condition: "{{ inputs.mode == 'ROLLBACK' and outputs.current.values.state !=
'SWITCHED' }}"
errorMessage: There is no switch to roll back. ROLLBACK needs the state SWITCHED.
- id: analysis
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.mode != 'ROLLBACK' }}"
then:
- id: collect
type: io.kestra.plugin.scripts.shell.Commands
description: Reads the dashboards that use the source datasource, fills in the
template variables and collects every PromQL expression, plus the
rules of the old backend.
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
GRAFANA_URL: "{{ inputs.grafana_url }}"
GRAFANA_TOKEN: "{{ inputs.grafana_token }}"
SOURCE_DS_UID: "{{ inputs.source_datasource_uid }}"
SOURCE_URL: "{{ inputs.source_url }}"
TARGET_URL: "{{ inputs.target_url }}"
TARGET_GRAFANA_URL: "{{ inputs.target_grafana_url }}"
TARGET_DS_UID: "{{ render(vars.target_uid) }}"
SOURCE_HEADERS: "{{ inputs.source_headers }}"
TARGET_HEADERS: "{{ inputs.target_headers }}"
TARGET_DS_JSON: "{{ inputs.target_datasource_json }}"
WINDOW: "{{ inputs.window }}"
STEP: "{{ inputs.step }}"
RATE_INTERVAL: "{{ inputs.rate_interval }}"
REL_TOL: "{{ inputs.rel_tol }}"
IGNORE_LABELS: "{{ inputs.ignore_labels }}"
DASHBOARD_TAGS: "{{ inputs.dashboard_tags }}"
FOLDER_UIDS: "{{ inputs.folder_uids }}"
INCLUDE_RULES: "{{ inputs.include_rules }}"
inputFiles:
lib.py: "{{ vars.lib_py }}"
collect.py: "{{ vars.collect_py }}"
outputFiles:
- queries.json
commands:
- python collect.py
- id: require_queries
type: io.kestra.plugin.core.execution.Fail
condition: "{{ outputs.collect.vars.unique_queries == 0 and
outputs.current.values.state == 'NONE' }}"
errorMessage: No dashboard query uses this datasource. Check
source_datasource_uid, dashboard_tags and folder_uids.
- id: parity
type: io.kestra.plugin.scripts.shell.Commands
description: Runs every query on both backends over the same window and step,
then compares the series and the values.
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
GRAFANA_URL: "{{ inputs.grafana_url }}"
GRAFANA_TOKEN: "{{ inputs.grafana_token }}"
SOURCE_DS_UID: "{{ inputs.source_datasource_uid }}"
SOURCE_URL: "{{ inputs.source_url }}"
TARGET_URL: "{{ inputs.target_url }}"
TARGET_GRAFANA_URL: "{{ inputs.target_grafana_url }}"
TARGET_DS_UID: "{{ render(vars.target_uid) }}"
SOURCE_HEADERS: "{{ inputs.source_headers }}"
TARGET_HEADERS: "{{ inputs.target_headers }}"
TARGET_DS_JSON: "{{ inputs.target_datasource_json }}"
WINDOW: "{{ inputs.window }}"
STEP: "{{ inputs.step }}"
RATE_INTERVAL: "{{ inputs.rate_interval }}"
REL_TOL: "{{ inputs.rel_tol }}"
IGNORE_LABELS: "{{ inputs.ignore_labels }}"
DASHBOARD_TAGS: "{{ inputs.dashboard_tags }}"
FOLDER_UIDS: "{{ inputs.folder_uids }}"
INCLUDE_RULES: "{{ inputs.include_rules }}"
inputFiles:
lib.py: "{{ vars.lib_py }}"
parity.py: "{{ vars.parity_py }}"
queries.json: "{{ outputs.collect.outputFiles['queries.json'] }}"
outputFiles:
- parity.json
- report.md
commands:
- python parity.py
- id: show_report
type: io.kestra.plugin.core.log.Log
level: "{{ outputs.parity.vars.blocked_count + outputs.parity.vars.rule_problems
> 0 ? 'WARN' : 'INFO' }}"
message: |
{{ outputs.parity.vars.queries }} distinct queries from {{ outputs.parity.vars.dashboards }} dashboards and {{ outputs.collect.vars.rules }} rules: {{ outputs.parity.vars.match }} match, {{ outputs.parity.vars.diff }} differ, {{ outputs.parity.vars.error }} are rejected by the new backend, {{ outputs.parity.vars.empty_target }} have no data there, {{ outputs.parity.vars.empty_both }} have no data on either side.
Dashboards that answer the same: {{ outputs.parity.vars.clean_dashboards == '' ? 'none' : outputs.parity.vars.clean_dashboards }}. Dashboards with at least one panel that does not: {{ outputs.parity.vars.blocked_dashboards == '' ? 'none' : outputs.parity.vars.blocked_dashboards }}.
{{ outputs.collect.vars.alert_rules_on_source > 0 ? outputs.collect.vars.alert_rules_on_source ~ ' Grafana alert rules still query the old datasource and are not moved by this flow.' : '' }}{{ outputs.collect.vars.skipped > 0 ? ' Not analyzed: ' ~ outputs.collect.vars.skipped_list : '' }}
{{ read(outputs.parity.outputFiles['report.md']) }}
- id: label_analysis
type: io.kestra.plugin.core.execution.Labels
labels:
queries: "{{ outputs.parity.vars.queries }}"
blocked: "{{ outputs.parity.vars.blocked_count }}"
outcome: "{{ inputs.mode == 'ANALYZE' ? (outputs.parity.vars.blocked_count +
outputs.parity.vars.rule_problems == 0 ? 'identical' :
'differences') : 'awaiting-decision' }}"
- id: switch
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.mode == 'SWITCH' }}"
then:
- id: up_to_date
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.parity.vars.dashboards == 0 }}"
then:
- id: label_up_to_date
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: up-to-date
- id: stop_up_to_date
type: io.kestra.plugin.core.execution.Exit
state: SUCCESS
- id: require_comparable
type: io.kestra.plugin.core.execution.Fail
condition: "{{ outputs.parity.vars.source_error > 0 and
outputs.parity.vars.match == 0 }}"
errorMessage: The old backend rejected its own queries, so the comparison proves
nothing. Read the show_report log.
- id: plan_only
type: io.kestra.plugin.core.flow.If
condition: "{{ render(vars.live) != 'true' }}"
then:
- id: label_planned
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: planned
- id: stop_planned
type: io.kestra.plugin.core.execution.Exit
state: SUCCESS
- id: approve_switch
type: io.kestra.plugin.core.flow.Pause
description: Nothing is changed before an answer. Each repointed dashboard keeps
its version history in Grafana. ROLLBACK restores it.
pauseDuration: "{{ vars.approval_window }}"
behavior: CANCEL
onResume:
- id: decision
type: SELECT
displayName: Decision
isRadio: true
expression: >-
{{ outputs.parity.vars.blocked_count == 0 ? [ {'label':
'SWITCH_CLEAN: repoint all ' ~ outputs.parity.vars.clean_count ~ '
dashboards (' ~ outputs.parity.vars.clean_dashboards ~ ')',
'value': 'SWITCH_CLEAN'}, {'label': 'CANCEL: change nothing',
'value': 'CANCEL'} ] : (outputs.parity.vars.clean_count == 0 ? [
{'label': 'SWITCH_ALL: repoint all ' ~
outputs.parity.vars.dashboards ~ ' dashboards although none
answers the same (' ~ outputs.parity.vars.blocked_dashboards ~
')', 'value': 'SWITCH_ALL'}, {'label': 'CANCEL: change nothing',
'value': 'CANCEL'} ] : [ {'label': 'SWITCH_CLEAN: repoint the ' ~
outputs.parity.vars.clean_count ~ ' dashboards that answer the
same (' ~ outputs.parity.vars.clean_dashboards ~ ')', 'value':
'SWITCH_CLEAN'}, {'label': 'SWITCH_ALL: repoint all ' ~
outputs.parity.vars.dashboards ~ ' dashboards, including ' ~
outputs.parity.vars.blocked_count ~ ' with panels that answer
differently (' ~ outputs.parity.vars.blocked_dashboards ~ ')',
'value': 'SWITCH_ALL'}, {'label': 'CANCEL: change nothing',
'value': 'CANCEL'} ]) }}
- id: note
type: STRING
displayName: Note
description: Required for SWITCH_ALL. Say why the differing panels are
acceptable.
required: false
- id: cancelled
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approve_switch.onResume.decision == 'CANCEL' }}"
then:
- id: label_cancelled
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: cancelled
- id: stop_cancelled
type: io.kestra.plugin.core.execution.Exit
state: SUCCESS
- id: require_note
type: io.kestra.plugin.core.execution.Fail
condition: "{{ outputs.approve_switch.onResume.decision == 'SWITCH_ALL' and
(outputs.approve_switch.onResume.note ?? '') | trim == '' }}"
errorMessage: SWITCH_ALL needs a note that says why the panels that answer
differently are acceptable. Nothing was changed.
- id: chosen
type: io.kestra.plugin.core.output.OutputValues
values:
uids: "{{ outputs.approve_switch.onResume.decision == 'SWITCH_ALL' ?
(outputs.parity.vars.clean_dashboards ~ ',' ~
outputs.parity.vars.blocked_dashboards) :
outputs.parity.vars.clean_dashboards }}"
- id: switching
type: io.kestra.plugin.scripts.shell.Commands
description: Creates the datasource of the new backend if it is missing, checks
its health and repoints the chosen dashboards. A dashboard that was
saved after the analysis is left alone, because its queries were not
compared.
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
GRAFANA_URL: "{{ inputs.grafana_url }}"
GRAFANA_TOKEN: "{{ inputs.grafana_token }}"
SOURCE_DS_UID: "{{ inputs.source_datasource_uid }}"
SOURCE_URL: "{{ inputs.source_url }}"
TARGET_URL: "{{ inputs.target_url }}"
TARGET_GRAFANA_URL: "{{ inputs.target_grafana_url }}"
TARGET_DS_UID: "{{ render(vars.target_uid) }}"
SOURCE_HEADERS: "{{ inputs.source_headers }}"
TARGET_HEADERS: "{{ inputs.target_headers }}"
TARGET_DS_JSON: "{{ inputs.target_datasource_json }}"
WINDOW: "{{ inputs.window }}"
STEP: "{{ inputs.step }}"
RATE_INTERVAL: "{{ inputs.rate_interval }}"
REL_TOL: "{{ inputs.rel_tol }}"
IGNORE_LABELS: "{{ inputs.ignore_labels }}"
DASHBOARD_TAGS: "{{ inputs.dashboard_tags }}"
FOLDER_UIDS: "{{ inputs.folder_uids }}"
INCLUDE_RULES: "{{ inputs.include_rules }}"
inputFiles:
lib.py: "{{ vars.lib_py }}"
switch.py: "{{ vars.switch_py }}"
commands:
- DASHBOARD_UIDS="{{ outputs.chosen.values.uids }}" ANALYZED="{{
outputs.collect.vars.versions }}" python switch.py
- id: moved_total
type: io.kestra.plugin.core.output.OutputValues
values:
list: "{{ outputs.current.values.moved == '' ? outputs.switching.vars.moved_list
: (outputs.switching.vars.moved_list == '' ?
outputs.current.values.moved : outputs.current.values.moved ~ ',' ~
outputs.switching.vars.moved_list) }}"
- id: switched_state
type: io.kestra.plugin.core.kv.Set
description: Written even when some dashboards failed, so ROLLBACK knows what
was changed.
key: "grafana-backend-{{ inputs.migration_name }}"
kvType: JSON
value: >-
{{ {'state': 'SWITCHED', 'target_datasource': render(vars.target_uid),
'moved': outputs.moved_total.values.list, 'approved_note':
(outputs.approve_switch.onResume.note ?? '')} | toJson }}
- id: require_all_moved
type: io.kestra.plugin.core.execution.Fail
condition: "{{ outputs.switching.vars.failed > 0 }}"
errorMessage: "Some dashboards were not repointed: {{
outputs.switching.vars.failed_list }}. The others were. ROLLBACK
restores all of them. Run SWITCH again to continue."
- id: verify_switch
type: io.kestra.plugin.scripts.shell.Commands
description: Asks Grafana the same queries through the old and the new
datasource, so the proxy, the credentials and the datasource settings
are part of the check.
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
GRAFANA_URL: "{{ inputs.grafana_url }}"
GRAFANA_TOKEN: "{{ inputs.grafana_token }}"
SOURCE_DS_UID: "{{ inputs.source_datasource_uid }}"
SOURCE_URL: "{{ inputs.source_url }}"
TARGET_URL: "{{ inputs.target_url }}"
TARGET_GRAFANA_URL: "{{ inputs.target_grafana_url }}"
TARGET_DS_UID: "{{ render(vars.target_uid) }}"
SOURCE_HEADERS: "{{ inputs.source_headers }}"
TARGET_HEADERS: "{{ inputs.target_headers }}"
TARGET_DS_JSON: "{{ inputs.target_datasource_json }}"
WINDOW: "{{ inputs.window }}"
STEP: "{{ inputs.step }}"
RATE_INTERVAL: "{{ inputs.rate_interval }}"
REL_TOL: "{{ inputs.rel_tol }}"
IGNORE_LABELS: "{{ inputs.ignore_labels }}"
DASHBOARD_TAGS: "{{ inputs.dashboard_tags }}"
FOLDER_UIDS: "{{ inputs.folder_uids }}"
INCLUDE_RULES: "{{ inputs.include_rules }}"
inputFiles:
lib.py: "{{ vars.lib_py }}"
collect.py: "{{ vars.collect_py }}"
verify.py: "{{ vars.verify_py }}"
outputFiles:
- verify.md
commands:
- DASHBOARD_UIDS="{{ outputs.chosen.values.uids }}" MUST_MATCH="{{
outputs.parity.vars.clean_dashboards }}" python verify.py
- id: verify_through_grafana
type: io.kestra.plugin.core.execution.Assert
errorMessage: "Grafana answers differently through the new datasource for
dashboards that matched before: {{
outputs.verify_switch.vars.problem_list }}. The dashboards stay
repointed. Run ROLLBACK to restore them."
conditions:
- "{{ outputs.verify_switch.vars.must_match_problems == 0 }}"
- id: label_switched
type: io.kestra.plugin.core.execution.Labels
labels:
dashboards: "{{ outputs.switching.vars.moved }}"
outcome: "{{ outputs.approve_switch.onResume.decision == 'SWITCH_ALL' and
outputs.parity.vars.blocked_count > 0 ? 'switched-with-exceptions' :
'switched' }}"
- id: next_steps
type: io.kestra.plugin.core.log.Log
message: |
Repointed {{ outputs.switching.vars.moved }} dashboards to the datasource {{ render(vars.target_uid) }}. {{ outputs.verify_switch.vars.checked }} queries were checked through Grafana.
Move the Grafana alert rules and the rule files yourself, then retire the old backend when nothing reads it.
- id: rollback
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.mode == 'ROLLBACK' }}"
then:
- id: rollback_only_live
type: io.kestra.plugin.core.flow.If
condition: "{{ render(vars.live) != 'true' }}"
then:
- id: log_rollback_preview
type: io.kestra.plugin.core.log.Log
message: "Preview: ROLLBACK would restore {{ outputs.current.values.moved |
split(',') | length }} dashboards ({{ outputs.current.values.moved
}}), unless someone saved them since the switch."
- id: label_rollback_previewed
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: rollback-previewed
- id: stop_rollback_previewed
type: io.kestra.plugin.core.execution.Exit
state: SUCCESS
- id: approve_rollback
type: io.kestra.plugin.core.flow.Pause
description: Restores the dashboards that SWITCH changed to the version they had
before. A dashboard that was saved again after the switch is left
alone.
pauseDuration: "{{ vars.approval_window }}"
behavior: CANCEL
onResume:
- id: decision
type: SELECT
displayName: Decision
isRadio: true
expression: >-
{{ [ {'label': 'ROLLBACK: restore ' ~
(outputs.current.values.moved | split(',') | length) ~ '
dashboards', 'value': 'ROLLBACK'}, {'label': 'CANCEL: change
nothing', 'value': 'CANCEL'} ] }}
- id: rollback_cancelled
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approve_rollback.onResume.decision == 'CANCEL' }}"
then:
- id: label_rollback_cancelled
type: io.kestra.plugin.core.execution.Labels
labels:
outcome: cancelled
- id: stop_rollback_cancelled
type: io.kestra.plugin.core.execution.Exit
state: SUCCESS
- id: restoring
type: io.kestra.plugin.scripts.shell.Commands
containerImage: "{{ inputs.tools_image }}"
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
networkMode: "{{ inputs.docker_network }}"
entryPoint: []
env:
GRAFANA_URL: "{{ inputs.grafana_url }}"
GRAFANA_TOKEN: "{{ inputs.grafana_token }}"
SOURCE_DS_UID: "{{ inputs.source_datasource_uid }}"
SOURCE_URL: "{{ inputs.source_url }}"
TARGET_URL: "{{ inputs.target_url }}"
TARGET_GRAFANA_URL: "{{ inputs.target_grafana_url }}"
TARGET_DS_UID: "{{ render(vars.target_uid) }}"
SOURCE_HEADERS: "{{ inputs.source_headers }}"
TARGET_HEADERS: "{{ inputs.target_headers }}"
TARGET_DS_JSON: "{{ inputs.target_datasource_json }}"
WINDOW: "{{ inputs.window }}"
STEP: "{{ inputs.step }}"
RATE_INTERVAL: "{{ inputs.rate_interval }}"
REL_TOL: "{{ inputs.rel_tol }}"
IGNORE_LABELS: "{{ inputs.ignore_labels }}"
DASHBOARD_TAGS: "{{ inputs.dashboard_tags }}"
FOLDER_UIDS: "{{ inputs.folder_uids }}"
INCLUDE_RULES: "{{ inputs.include_rules }}"
inputFiles:
lib.py: "{{ vars.lib_py }}"
rollback.py: "{{ vars.rollback_py }}"
commands:
- MOVED="{{ outputs.current.values.moved }}" python rollback.py
- id: verify_rollback
type: io.kestra.plugin.core.execution.Assert
errorMessage: "Some dashboards were not restored: {{
outputs.restoring.vars.failed_list }}. Dashboards saved since the
switch: {{ outputs.restoring.vars.edited_list }}."
conditions:
- "{{ outputs.restoring.vars.failed == 0 }}"
- id: rolled_back_state
type: io.kestra.plugin.core.kv.Set
key: "grafana-backend-{{ inputs.migration_name }}"
kvType: JSON
value: '{"state":"ROLLED_BACK"}'
- id: label_rolled_back
type: io.kestra.plugin.core.execution.Labels
labels:
dashboards: "{{ outputs.restoring.vars.restored }}"
outcome: "{{ outputs.restoring.vars.edited > 0 ?
'rolled-back-with-edited-dashboards' : 'rolled-back' }}"
errors:
- id: label_failed
type: io.kestra.plugin.core.execution.Labels
labels:
failed: "true"
- id: alert_switch_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {'text': 'Grafana backend migration ' ~ inputs.migration_name ~ ' (' ~
inputs.mode ~ ') failed. Execution ' ~ execution.id ~ '. Dashboards that
were already repointed keep their version history. Run ROLLBACK to restore
them.'} | toJson }}
triggers:
- id: weekly_analysis
type: io.kestra.plugin.core.trigger.Schedule
disabled: true
cron: "0 6 * * 1"
inputs:
mode: ANALYZE
source_datasource_uid: prometheus
source_url: http://prometheus:9090
target_url: http://victoriametrics:8428
dry_run: true
auto_remediate: false
Moving dashboards to Prometheus 3, VictoriaMetrics, Mimir or Thanos usually means changing a datasource and looking at the panels. A panel that fails or shows different numbers is found by whoever opens it. This flow collects every PromQL query of your dashboards and of the old backend's rules, runs each one on both backends over the same window. It shows which panels would answer differently before any dashboard is changed.
collect reads the dashboards that use the source datasource, fills in the template variables and $__rate_interval. It lists every expression and the rules of the old backend.parity runs each query with query_range on both backends and compares the series and the values. Each query ends as MATCH, DIFF, ERROR (the new backend rejects it), EMPTY_TARGET (no data there) or EMPTY_BOTH.approve_switch (Pause) offers SWITCH_CLEAN for the dashboards whose panels all match. SWITCH_ALL needs a note.switching creates a datasource for the new backend, checks its health and repoints the dashboards. A dashboard that was saved after the analysis is left alone.verify_switch asks Grafana the same queries through the old and the new datasource, so the proxy and the credentials are part of the proof.A list of panels that break, with the reason. On the test cluster Prometheus 3.5 rejected holt_winters. VictoriaMetrics returned rate() values up to 21% apart and kept metric names that Prometheus drops.
Platform teams that upgrade Prometheus or move to VictoriaMetrics, Mimir, Thanos or a managed service.
The queries come from Grafana itself, so nothing is listed by hand. Pause shows the counts. KV keeps what was changed. Assert fails the run when a dashboard that matched answers differently through Grafana.
18 runs on Kestra 2.0.6 with Prometheus 2.55.1 as the source, Prometheus 3.5.0 and VictoriaMetrics 1.122.0 as targets and Grafana 11.6.0. Covered: identical backends, a rejected function, rate differences, a target without data, an unhealthy datasource, a dashboard saved during the approval, a rerun, rollback and a dashboard saved after the switch. Mimir, Thanos and managed services were not run.
Grafana with a service account token (Editor role) and an old Prometheus-compatible backend that both Kestra and Grafana can reach. Docker workers must reach Grafana and both backends.
GRAFANA_TOKEN and SLACK_WEBHOOK_URL. Tenant headers go into the two header inputs.
source_datasource_uid, source_url and target_url are required. window and step set the comparison. ignore_labels leaves labels out. dry_run defaults to true and auto_remediate to false.
show_report log.dry_run false and auto_remediate true, run SWITCH and approve.Grafana alert rules and rule files are listed but not moved. Add a task that copies them after the switch. Raise rel_tol where a small gap is acceptable.
This blueprint was created by zkasuran.
Run conftest against rendered Kubernetes manifests from a CI webhook and escalate every failed rule as a GitHub issue and a Slack alert.
Deletes ConfigMaps and Secrets no pod references and reports the cleanup on Slack.
Audits Project Contour ingress controller for Envoy xDS configuration NACKs, CDS sync delay, and proxy disconnects.
In-place container OS package hotpatching with SecOps approval gates and post-patch verification.
On every push, collect the last ten commit subjects, check them with the Conventional Commits pattern, and escalate any violation to GitHub and Slack.
Audits HashiCorp Consul Raft consensus cluster leadership and voter quorum to prevent service discovery outages.
