Last active
May 8, 2023 06:21
-
-
Save abcdlsj/e4c3ca9e5a291b224caf468d0239600a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import click | |
import json | |
stitle = "panel 名称" | |
sexpr = "指标" | |
salert = "告警" | |
def preety_print(dashboard, result): | |
print("## " + dashboard) | |
for key in result: | |
print("### " + key) | |
for subkey in result[key]: | |
if subkey == stitle: | |
continue | |
if subkey == sexpr: | |
print(" " + subkey + ":") | |
print( | |
" " + "\n ".join(["```" + expr + "```" for expr in result[key][subkey]])) | |
elif subkey == salert: | |
print(" " + subkey + ":") | |
print(" " + "\n ".join(result[key][subkey])) | |
salert_obj = {} | |
for key in result: | |
for subkey in result[key]: | |
if subkey == salert: | |
for alert in result[key][subkey]: | |
if salert_obj.get(alert): | |
salert_obj[alert].append(key) | |
else: | |
salert_obj[alert] = [key] | |
print("## 告警") | |
for key in salert_obj: | |
print("### " + key) | |
print(" " + "\n ".join(salert_obj[key])) | |
@click.command() | |
@click.option('--file', default='', help='Path to grafana json file') | |
def parse(file): | |
result = {} | |
dashboard = '' | |
with open(file, 'r') as f: | |
grafana = json.load(f) | |
for grafana_key in grafana: | |
if grafana_key == 'title': | |
dashboard = grafana[grafana_key] | |
if grafana_key == 'panels': | |
for panel in grafana[grafana_key]: | |
if panel['type'] != 'graph': | |
continue | |
item = {} | |
for panel_key in panel: | |
if panel_key == 'title': | |
item[stitle] = panel[panel_key] | |
if panel_key == 'targets': | |
for target in panel[panel_key]: | |
for target_key in target: | |
if target_key == 'expr': | |
expr = target[target_key] | |
expr = expr.replace('\n', '') | |
if item.get(sexpr): | |
item[sexpr].append(expr) | |
else: | |
item[sexpr] = [expr] | |
if panel_key == 'alert': | |
for alert_key in panel[panel_key]: | |
if alert_key == 'message': | |
message = panel[panel_key][alert_key] | |
if item.get(salert): | |
item[salert].append(message) | |
else: | |
item[salert] = [message] | |
result[item[stitle]] = item | |
preety_print(dashboard, result) | |
if __name__ == '__main__': | |
parse() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment