Add/modify the Grafana Dashboard
[bottlenecks.git] / monitor / dashboard / 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 MONITOR_DASHBOARD = "/home/opnfv/bottlenecks/monitor/dashboard/"
18
19
20 def _create_dashboard(ip, port, path):
21     url = 'http://admin:admin@{}:{}/api/dashboards/db'.format(ip, port)
22     logger.info("Fetched IP for dashboard creation!")
23     with open(path) as f:
24         data = jsonutils.load(f)
25     try:
26         post(url, {"dashboard": data})
27         logger.info("Trying to post dashboard json!")
28     except Exception:
29         logger.info("Create dashboard failed")
30         raise
31
32
33 def _create_data_source(ip, port):
34     url = 'http://admin:admin@{}:{}/api/datasources'.format(ip, port)
35     logger.info("Fetched URL for datasource")
36     data = {
37         "name": "automated-ds",
38         "type": "prometheus",
39         "access": "direct",
40         "url": "http://{}:9090".format(ip),
41     }
42     try:
43         post(url, data)
44         logger.info("Trying to post datasource")
45
46     except Exception:
47         logger.info("Create Datasources failed")
48         raise
49
50
51 def post(url, data):
52     data = jsonutils.dump_as_bytes(data)
53     logger.info("In post method for dumping data")
54     headers = {'Content-Type': 'application/json'}
55     try:
56         response = requests.post(url, data=data, headers=headers)
57         result = response.json()
58         logger.debug('The result is: %s', result)
59         logger.info("Trying to post")
60         return result
61     except Exception as e:
62         logger.info("Failed post" + str(e))
63         raise
64
65
66 ip_address = socket.gethostbyname(socket.gethostname())
67 _create_data_source(ip_address, 3000)
68 _create_dashboard(ip_address, 3000, MONITOR_DASHBOARD + 'stats_overview.json')
69 _create_dashboard(ip_address, 3000,
70                   MONITOR_DASHBOARD + 'jump_server_status.json')