Merge "add CheckConnectivity scenario"
[yardstick.git] / yardstick / dispatcher / influxdb.py
1 ##############################################################################
2 # Copyright (c) 2015 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 from __future__ import absolute_import
11
12 import logging
13 import time
14
15 import requests
16
17 from yardstick.common import utils
18 from third_party.influxdb.influxdb_line_protocol import make_lines
19 from yardstick.dispatcher.base import Base as DispatchBase
20
21 LOG = logging.getLogger(__name__)
22
23
24 class InfluxdbDispatcher(DispatchBase):
25     """Dispatcher class for posting data into an influxdb target.
26     """
27
28     __dispatcher_type__ = "Influxdb"
29
30     def __init__(self, conf):
31         super(InfluxdbDispatcher, self).__init__(conf)
32         db_conf = conf['dispatcher_influxdb']
33         self.timeout = int(db_conf.get('timeout', 5))
34         self.target = db_conf.get('target', 'http://127.0.0.1:8086')
35         self.db_name = db_conf.get('db_name', 'yardstick')
36         self.username = db_conf.get('username', 'root')
37         self.password = db_conf.get('password', 'root')
38
39         self.influxdb_url = "%s/write?db=%s" % (self.target, self.db_name)
40
41         self.task_id = -1
42
43     def flush_result_data(self, data):
44         LOG.debug('Test result all : %s', data)
45         if self.target == '':
46             # if the target was not set, do not do anything
47             LOG.error('Dispatcher target was not set, no data will be posted.')
48
49         result = data['result']
50         self.tags = result['info']
51         self.task_id = result['task_id']
52         self.criteria = result['criteria']
53         testcases = result['testcases']
54
55         for case, data in testcases.items():
56             tc_criteria = data['criteria']
57             for record in data['tc_data']:
58                 # skip results with no data because we influxdb encode empty dicts
59                 if record.get("data"):
60                     self._upload_one_record(record, case, tc_criteria)
61
62         return 0
63
64     def _upload_one_record(self, data, case, tc_criteria):
65         try:
66             line = self._data_to_line_protocol(data, case, tc_criteria)
67             LOG.debug('Test result line format : %s', line)
68             res = requests.post(self.influxdb_url,
69                                 data=line,
70                                 auth=(self.username, self.password),
71                                 timeout=self.timeout)
72             if res.status_code != 204:
73                 LOG.error('Test result posting finished with status code'
74                           ' %d.', res.status_code)
75                 LOG.error(res.text)
76
77         except Exception as err:
78             LOG.exception('Failed to record result data: %s', err)
79
80     def _data_to_line_protocol(self, data, case, criteria):
81         msg = {}
82         point = {
83             "measurement": case,
84             "fields": utils.flatten_dict_key(data["data"]),
85             "time": self._get_nano_timestamp(data),
86             "tags": self._get_extended_tags(criteria),
87         }
88         msg["points"] = [point]
89         msg["tags"] = self.tags
90
91         return make_lines(msg).encode('utf-8')
92
93     def _get_nano_timestamp(self, results):
94         try:
95             timestamp = results["timestamp"]
96         except Exception:
97             timestamp = time.time()
98
99         return str(int(float(timestamp) * 1000000000))
100
101     def _get_extended_tags(self, criteria):
102         tags = {
103             "task_id": self.task_id,
104             "criteria": criteria
105         }
106
107         return tags