"Fossies" - the Fresh Open Source Software Archive 
Member "monasca-log-api-2.9.0/devstack/files/grafana/grafana.py" (1 Apr 2019, 3671 Bytes) of package /linux/misc/openstack/monasca-log-api-2.9.0.tar.gz:
As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style:
standard) with prefixed line numbers.
Alternatively you can here
view or
download the uninterpreted source code file.
For more information about "grafana.py" see the
Fossies "Dox" file reference documentation.
1 #!/usr/bin/env python
2 # coding=utf-8
3
4 # (C) Copyright 2017 Hewlett Packard Enterprise Development LP
5 # (C) Copyright 2018 FUJITSU LIMITED
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License"); you may
8 # not use this file except in compliance with the License. You may obtain
9 # a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 # License for the specific language governing permissions and limitations
17 # under the License.
18
19 import glob
20 import json
21 import logging
22 import os
23 import sys
24 import time
25
26 from requests import RequestException
27 from requests import Session
28
29 LOG_LEVEL = logging.getLevelName(os.environ.get('LOG_LEVEL', 'INFO'))
30 logging.basicConfig(level=LOG_LEVEL)
31
32 logger = logging.getLogger(__name__)
33
34 GRAFANA_URL = os.environ.get('GRAFANA_URL', 'http://localhost:3000')
35 GRAFANA_USERNAME = os.environ.get('GRAFANA_USERNAME', 'mini-mon')
36 GRAFANA_PASSWORD = os.environ.get('GRAFANA_PASSWORD', 'password')
37 GRAFANA_USERS = [{'user': GRAFANA_USERNAME, 'password': GRAFANA_PASSWORD, 'email': ''}]
38
39 DASHBOARDS_DIR = sys.argv[1]
40
41
42 def retry(retries=5, delay=2.0, exc_types=(RequestException,)):
43 def decorator(func):
44 def f_retry(*args, **kwargs):
45 for i in range(retries):
46 try:
47 return func(*args, **kwargs)
48 except exc_types as exc:
49 if i < retries - 1:
50 logger.debug('Caught exception, retrying...',
51 exc_info=True)
52 time.sleep(delay)
53 else:
54 logger.exception('Failed after %d attempts', retries)
55 if isinstance(exc, RequestException):
56 logger.debug('Response was: %r', exc.response.text)
57
58 raise
59 return f_retry
60 return decorator
61
62 def create_login_payload():
63 if os.environ.get('GRAFANA_USERS'):
64 try:
65 json.loads(os.environ.get('GRAFANA_USERS'))
66 except ValueError:
67 print("Invalid type GRAFANA_USERS")
68 raise
69 grafana_users = json.loads(os.environ.get('GRAFANA_USERS'))
70 else:
71 grafana_users = GRAFANA_USERS
72 return grafana_users
73
74 @retry(retries=24, delay=5.0)
75 def login(session, user):
76 r = session.post('{url}/login'.format(url=GRAFANA_URL),
77 json=user,
78 timeout=5)
79 r.raise_for_status()
80
81 def create_dashboard_payload(json_path):
82 with open(json_path, 'r') as f:
83 dashboard = json.load(f)
84 dashboard['id'] = None
85
86 return {
87 'dashboard': dashboard,
88 'overwrite': True
89 }
90
91 def main():
92 for user in create_login_payload():
93 logging.info('Opening a Grafana session...')
94 session = Session()
95 login(session, user)
96
97 for path in sorted(glob.glob('{dir}/*.json'.format(dir=DASHBOARDS_DIR))):
98 logging.info('Creating dashboard from file: {path}'.format(path=path))
99 r = session.post('{url}/api/dashboards/db'.format(url=GRAFANA_URL),
100 json=create_dashboard_payload(path))
101 logging.debug('Response: %r', r.json())
102 r.raise_for_status()
103
104 logging.info('Ending %r session...', user.get('user'))
105 session.get('{url}/logout'.format(url=GRAFANA_URL))
106
107 logging.info('Finished successfully.')
108
109
110 if __name__ == '__main__':
111 main()