-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrafana-backup-over-api.py
86 lines (68 loc) · 2.78 KB
/
grafana-backup-over-api.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
#!/usr/bin/env python3
import requests
import logging
import os
import sys
import json
import yaml
import tempfile
import shutil
import argparse
logging.basicConfig(level=logging.DEBUG,
format=u'%(pathname)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s')
def main():
params_parser = argparse.ArgumentParser(
description='Grafana dashboards and datasources backup',
epilog='Create tarball with grafana data'
)
required = params_parser.add_argument_group('required named arguments')
required.add_argument('--api-key', metavar='<key>', dest='key',
help='Your API Key, it must have admin permissions', required=True)
required.add_argument('--api-url', metavar='<url>', dest='url',
help='Api url', required=True)
params_parser.add_argument('--archivename', metavar="<name>", dest="archivename",
help='Archive name of output file (WITHOUT FILE EXTENSION)', default='grafana-backup')
params_parser.add_argument('action', default='backup', choices=['backup', 'restore'],
help='Action, it can be "backup" or "restore"')
args = params_parser.parse_args()
api_url = args.url
api_key = args.key
api_session = requests.Session()
api_session.headers.update({"Authorization": "Bearer {}".format(api_key)})
try:
r = api_session.get(api_url+"/datasources")
datasources = r.json()
# print(yaml.dump(datasources, indent=2, default_flow_style=False))
print(json.dumps(datasources, indent=2))
except:
logging.error("Can't get datasources list")
return
try:
r = api_session.get(api_url+"/search")
dashboards_list = r.json()
print(json.dumps(dashboards_list, indent=2))
except:
logging.error("Can't get dashboards list")
return
tmpdirname = tempfile.TemporaryDirectory()
dashboards_dir = tmpdirname.name+"/dashboards"
os.makedirs(dashboards_dir, exist_ok=True)
with open(tmpdirname.name+"/datasources.json", "w") as fp:
json.dump(datasources, fp, indent=2)
for dashboard in dashboards_list:
try:
r = api_session.get(api_url+"/dashboards/{uri}".format(**dashboard))
dashboard_ref = r.json()
filename = dashboard_ref["meta"]["slug"]+".json"
fp = open(dashboards_dir+"/"+filename, "w")
r = json.dump(dashboard_ref, fp, indent=2)
fp.close()
logging.debug(dashboards_dir+"/"+filename)
except:
logging.error("Can't get dashboard '{title}' with id {id} ({uri})".format(**dashboard))
tmpdirname.cleanup()
raise
shutil.make_archive(args.archivename, "gztar", root_dir=tmpdirname.name)
tmpdirname.cleanup()
if __name__ == '__main__':
main()