1e1b42f7cabf0068ec01eaa29416abd45ad46221
[bottlenecks.git] / monitor / automated-dashboard-datasource.py
1 ##############################################################################
2 # Copyright (c) 2017 Huawei Tech and others.
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 import logging
11 import socket
12 import requests
13 from oslo_serialization import jsonutils
14
15
16 logger = logging.getLogger(__name__)
17
18
19 def _create_dashboard(ip, port, path):
20     url = 'http://admin:admin@{}:{}/api/dashboards/db'.format(ip, port)
21     logger.info("Fetched IP for dashboard creation!")
22     with open(path) as f:
23         data = jsonutils.load(f)
24     try:
25         post(url, {"dashboard": data})
26         logger.info( "Trying to post dashboard json!")
27     except Exception:
28         logger.info("Create dashboard failed")
29         raise
30
31
32 def _create_data_source(ip, port):
33     url = 'http://admin:admin@{}:{}/api/datasources'.format(ip, port)
34     logger.info("Fetched URL for datasource")
35     data = {
36         "name": "automated-ds",
37         "type": "prometheus",
38         "access": "direct",
39         "url": "http://{}:9090".format(ip),
40     }
41     try:
42         post(url, data)
43         logger.info("Trying to post datasource")
44
45     except Exception:
46         logger.info("Create Datasources failed")
47         raise
48
49
50 def post(url, data):
51     data = jsonutils.dump_as_bytes(data)
52     logger.info("In post method for dumping data")
53     headers = {'Content-Type': 'application/json'}
54     try:
55         response = requests.post(url, data=data, headers=headers)
56         result = response.json()
57         logger.debug('The result is: %s', result)
58         logger.info("Trying to post")
59         return result
60     except Exception as e:
61         logger.info("Failed post" + str(e))
62         raise
63
64
65 ip_address = socket.gethostbyname(socket.gethostname())
66 _create_dashboard(ip_address, 3000, '/var/lib/grafana/' +
67                   'dashboards/' +
68                   'prometheus-system_rev1.json')
69 _create_data_source(ip_address, 3000)