Simon Pasquier | ab3d122 | 2017-06-26 15:18:19 +0200 | [diff] [blame] | 1 | #!/usr/bin/python3 |
| 2 | # Copyright 2016 Mirantis, Inc. |
| 3 | # |
| 4 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 5 | # not use this file except in compliance with the License. You may obtain |
| 6 | # a copy of the License at |
| 7 | # |
| 8 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | # |
| 10 | # Unless required by applicable law or agreed to in writing, software |
| 11 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | # License for the specific language governing permissions and limitations |
| 14 | # under the License. |
| 15 | # |
| 16 | |
| 17 | import sys |
| 18 | import glob |
| 19 | import os |
| 20 | import json |
| 21 | |
| 22 | |
| 23 | def usage(): |
| 24 | h = """ |
| 25 | Format and sanitize Grafana dashboards |
| 26 | |
| 27 | Usage: {} <DIRECTORY|FILE> |
| 28 | |
| 29 | The program will: |
| 30 | * Sort keys alphabetically. |
| 31 | * Remove sections: |
| 32 | templating.list[].current |
| 33 | templating.list[].options |
| 34 | * Override the time entry to {{"from": "now-1h","to": "now"}} |
| 35 | * Enable the sharedCrosshair tooltip |
| 36 | * Increment the version number |
| 37 | |
| 38 | WARNING: this script modifies directly the given file(s). |
| 39 | |
| 40 | If a DIRECTORY is provided, all files with suffix '.json' are modified. |
| 41 | """ |
| 42 | print(h.format(sys.argv[0])) |
| 43 | |
| 44 | if len(sys.argv) != 2: |
| 45 | usage() |
| 46 | sys.exit(1) |
| 47 | |
| 48 | arg = sys.argv[1] |
| 49 | |
| 50 | if os.path.isdir(arg): |
| 51 | path = "{}/*.json".format(arg) |
| 52 | elif os.path.isfile(arg): |
| 53 | path = arg |
| 54 | else: |
| 55 | print("'{}' no such file or directory".format(arg)) |
| 56 | usage() |
| 57 | sys.exit(1) |
| 58 | |
| 59 | for f in glob.glob(path): |
| 60 | data = None |
| 61 | absf = os.path.abspath(f) |
| 62 | with open(absf) as out: |
| 63 | data = json.load(out) |
| 64 | for k, v in data.items(): |
| 65 | if k == 'annotations': |
| 66 | for anno in v.get('list', []): |
| 67 | anno['datasource'] = 'lma' |
| 68 | |
| 69 | if k == 'templating': |
| 70 | variables = v.get('list', []) |
| 71 | for o in variables: |
| 72 | if o['type'] == 'query': |
| 73 | o['options'] = [] |
| 74 | o['current'] = {} |
| 75 | o['refresh_on_load'] = True |
| 76 | |
| 77 | data['time'] = {'from': 'now-1h', 'to': 'now'} |
| 78 | data['sharedCrosshair'] = True |
| 79 | data['refresh'] = '1m' |
| 80 | data['id'] = None |
| 81 | |
| 82 | if data.get('version', None): |
| 83 | data['version'] = data['version'] + 1 |
| 84 | else: |
| 85 | data['version'] = 1 |
| 86 | |
| 87 | with open(absf, 'w') as out: |
| 88 | out.write(json.dumps(data, indent=2, sort_keys=True)) |