summaryrefslogtreecommitdiff
path: root/grafana_dashboards/parser.py
blob: 6f17df6d7af990f28b8c88cae2ed306ee320b6ef (plain)
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
# Copyright 2015 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import hashlib
import io
import json
import logging
import yaml

from slugify import slugify

from grafana_dashboards.schema.dashboard import Dashboard

LOG = logging.getLogger(__name__)


class YamlParser(object):

    def __init__(self):
        self.data = {}

    def get_dashboard(self, slug):
        data = self.data.get('dashboard', {}).get(slug, None)
        md5 = None
        if data:
            # Sort json keys to help our md5 hash are constant.
            content = json.dumps(data, sort_keys=True)
            md5 = hashlib.md5(content.encode('utf-8')).hexdigest()
        LOG.debug('Dashboard %s: %s' % (slug, md5))

        return data, md5

    def parse(self, fn):
        with io.open(fn, 'r', encoding='utf-8') as fp:
            self.parse_fp(fp)

    def parse_fp(self, fp):
        data = yaml.safe_load(fp)
        result = self.validate(data)
        for item in result.items():
            group = self.data.get(item[0], {})
            # Create slug to make it easier to find dashboards.
            title = item[1]['title']
            slug = slugify(title)
            if slug in group:
                raise Exception(
                    "Duplicate dashboard found in '{0}: '{1}' "
                    "already defined".format(fp.name, title))
            group[slug] = item[1]
            self.data[item[0]] = group

    def validate(self, data):
        schema = Dashboard()
        return schema.validate(data)