pylint fixes: remove redundant parens, fix comparison order
[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 from __future__ import absolute_import
10
11 import logging
12
13 import six.moves.configparser as ConfigParser
14 from six.moves.urllib.parse import urlsplit
15 from influxdb import InfluxDBClient
16
17 from api import conf
18
19 logger = logging.getLogger(__name__)
20
21
22 def get_data_db_client():
23     parser = ConfigParser.ConfigParser()
24     try:
25         parser.read(conf.OUTPUT_CONFIG_FILE_PATH)
26
27         if parser.get('DEFAULT', 'dispatcher') != 'influxdb':
28             raise RuntimeError
29
30         return _get_client(parser)
31     except ConfigParser.NoOptionError:
32         logger.error('can not find the key')
33         raise
34
35
36 def _get_client(parser):
37     ip = _get_ip(parser.get('dispatcher_influxdb', 'target'))
38     username = parser.get('dispatcher_influxdb', 'username')
39     password = parser.get('dispatcher_influxdb', 'password')
40     db_name = parser.get('dispatcher_influxdb', 'db_name')
41     return InfluxDBClient(ip, conf.PORT, username, password, db_name)
42
43
44 def _get_ip(url):
45     return urlsplit(url).hostname
46
47
48 def query(query_sql):
49     try:
50         client = get_data_db_client()
51         logger.debug('Start to query: %s', query_sql)
52         return list(client.query(query_sql).get_points())
53     except RuntimeError:
54         logger.error('dispatcher is not influxdb')
55         raise