Tools to make Grafana dashboards from templates
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

parser.py 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright 2015 Red Hat, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing permissions and limitations
  13. # under the License.
  14. import hashlib
  15. import io
  16. import json
  17. import logging
  18. import yaml
  19. from slugify import slugify
  20. from grafana_dashboards.schema.dashboard import Dashboard
  21. LOG = logging.getLogger(__name__)
  22. class YamlParser(object):
  23. def __init__(self):
  24. self.data = {}
  25. def get_dashboard(self, slug):
  26. data = self.data.get('dashboard', {}).get(slug, None)
  27. md5 = None
  28. if data:
  29. # Sort json keys to help our md5 hash are constant.
  30. content = json.dumps(data, sort_keys=True)
  31. md5 = hashlib.md5(content.encode('utf-8')).hexdigest()
  32. LOG.debug('Dashboard %s: %s' % (slug, md5))
  33. return data, md5
  34. def parse(self, fn):
  35. with io.open(fn, 'r', encoding='utf-8') as fp:
  36. self.parse_fp(fp)
  37. def parse_fp(self, fp):
  38. data = yaml.safe_load(fp)
  39. result = self.validate(data)
  40. for item in result.items():
  41. group = self.data.get(item[0], {})
  42. # Create slug to make it easier to find dashboards.
  43. title = item[1]['title']
  44. slug = slugify(title)
  45. if slug in group:
  46. raise Exception(
  47. "Duplicate dashboard found in '{0}: '{1}' "
  48. "already defined".format(fp.name, title))
  49. group[slug] = item[1]
  50. self.data[item[0]] = group
  51. def validate(self, data):
  52. schema = Dashboard()
  53. return schema.validate(data)