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