f391ad9727d53377c37c5e39cdc5934b0eb462f2
[yardstick.git] / api / utils / influx.py
1 ##############################################################################
2 # Copyright (c) 2016 Huawei Technologies Co.,Ltd 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
12 from six.moves import configparser as ConfigParser
13 # NOTE(ralonsoh): pylint E0401 import error
14 # https://github.com/PyCQA/pylint/issues/1640
15 from six.moves.urllib.parse import urlsplit  # pylint: disable=relative-import
16 from influxdb import client as influxdb_client
17
18 from yardstick.common import constants as consts
19 from yardstick.common import exceptions
20 from yardstick import dispatcher
21
22
23 logger = logging.getLogger(__name__)
24
25
26 def get_data_db_client():
27     parser = ConfigParser.ConfigParser()
28     try:
29         parser.read(consts.CONF_FILE)
30         return _get_influxdb_client(parser)
31     except ConfigParser.NoOptionError:
32         logger.error('Can not find the key')
33         raise
34
35
36 def _get_influxdb_client(parser):
37     if dispatcher.INFLUXDB not in parser.get('DEFAULT', 'dispatcher'):
38         raise exceptions.InfluxDBConfigurationMissing()
39
40     ip = _get_ip(parser.get('dispatcher_influxdb', 'target'))
41     user = parser.get('dispatcher_influxdb', 'username')
42     password = parser.get('dispatcher_influxdb', 'password')
43     db_name = parser.get('dispatcher_influxdb', 'db_name')
44     return influxdb_client.InfluxDBClient(ip, consts.INFLUXDB_PORT, user,
45                                           password, db_name)
46
47
48 def _get_ip(url):
49     return urlsplit(url).hostname
50
51
52 def query(query_sql):
53     try:
54         client = get_data_db_client()
55         logger.debug('Start to query: %s', query_sql)
56         return list(client.query(query_sql).get_points())
57     except RuntimeError:
58         logger.error('dispatcher is not influxdb')
59         raise