8f3604745e2327d6bdc34df969691595b79534b2
[yardstick.git] / api / utils / influx.py
1 ##############################################################################
2 # Copyright (c) 2016 Huawei Technologies Co.,Ltd and others.
3 # Copyright (c) 2019 Intel Corporation
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10
11 import logging
12
13 from six.moves import configparser as ConfigParser
14 # NOTE(ralonsoh): pylint E0401 import error
15 # https://github.com/PyCQA/pylint/issues/1640
16 from six.moves.urllib.parse import urlsplit  # pylint: disable=relative-import
17 from influxdb import client as influxdb_client
18
19 from yardstick.common import constants as consts
20 from yardstick.common import exceptions
21 from yardstick import dispatcher
22
23
24 logger = logging.getLogger(__name__)
25
26 def get_data_db_client(db=None):
27     parser = ConfigParser.ConfigParser()
28     try:
29         parser.read(consts.CONF_FILE)
30         return _get_influxdb_client(parser, db)
31     except ConfigParser.NoOptionError:
32         logger.error('Can not find the key')
33         raise
34
35 def _get_influxdb_client(parser, db=None):
36     if dispatcher.INFLUXDB not in parser.get('DEFAULT', 'dispatcher'):
37         raise exceptions.InfluxDBConfigurationMissing()
38
39     ip = _get_ip(parser.get('dispatcher_influxdb', 'target'))
40     user = parser.get('dispatcher_influxdb', 'username')
41     password = parser.get('dispatcher_influxdb', 'password')
42     if db is None:
43         db_name = parser.get('dispatcher_influxdb', 'db_name')
44     else:
45         db_name = db
46
47     return influxdb_client.InfluxDBClient(ip, consts.INFLUXDB_PORT, user,
48                                           password, db_name)
49
50
51 def _get_ip(url):
52     return urlsplit(url).hostname
53
54
55 def query(query_sql, db=None):
56     try:
57         client = get_data_db_client(db)
58         logger.debug('Start to query: %s', query_sql)
59         return list(client.query(query_sql).get_points())
60     except RuntimeError:
61         logger.error('dispatcher is not influxdb')
62         raise