dispatcher use YARDSTICK_BRANCH to distinguish different branch
[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 import os
11 import json
12 import logging
13 import requests
14 import time
15
16 from oslo_config import cfg
17
18 from yardstick.dispatcher.base import Base as DispatchBase
19 from yardstick.dispatcher.influxdb_line_protocol import make_lines
20
21 LOG = logging.getLogger(__name__)
22
23 CONF = cfg.CONF
24 influx_dispatcher_opts = [
25     cfg.StrOpt('target',
26                default='http://127.0.0.1:8086',
27                help='The target where the http request will be sent. '
28                     'If this is not set, no data will be posted. For '
29                     'example: target = http://hostname:1234/path'),
30     cfg.StrOpt('db_name',
31                default='yardstick',
32                help='The database name to store test results.'),
33     cfg.StrOpt('username',
34                default='root',
35                help='The user name to access database.'),
36     cfg.StrOpt('password',
37                default='root',
38                help='The user password to access database.'),
39     cfg.IntOpt('timeout',
40                default=5,
41                help='The max time in seconds to wait for a request to '
42                     'timeout.'),
43 ]
44
45 CONF.register_opts(influx_dispatcher_opts, group="dispatcher_influxdb")
46
47
48 class InfluxdbDispatcher(DispatchBase):
49     """Dispatcher class for posting data into an influxdb target.
50     """
51
52     __dispatcher_type__ = "Influxdb"
53
54     def __init__(self, conf):
55         super(InfluxdbDispatcher, self).__init__(conf)
56         self.timeout = CONF.dispatcher_influxdb.timeout
57         self.target = CONF.dispatcher_influxdb.target
58         self.db_name = CONF.dispatcher_influxdb.db_name
59         self.username = CONF.dispatcher_influxdb.username
60         self.password = CONF.dispatcher_influxdb.password
61         self.influxdb_url = "%s/write?db=%s" % (self.target, self.db_name)
62         self.raw_result = []
63         self.case_name = ""
64         self.tc = ""
65         self.task_id = -1
66         self.runners_info = {}
67         self.static_tags = {
68             "pod_name": os.environ.get('NODE_NAME', 'unknown'),
69             "installer": os.environ.get('INSTALLER_TYPE', 'unknown'),
70             "deploy_scenario": os.environ.get('DEPLOY_SCENARIO', 'unknown'),
71             "version": os.path.basename(os.environ.get('YARDSTICK_BRANCH',
72                                                        'unknown'))
73
74         }
75
76     def _dict_key_flatten(self, data):
77         next_data = {}
78
79         if not [v for v in data.values()
80                 if type(v) == dict or type(v) == list]:
81             return data
82
83         for k, v in data.iteritems():
84             if type(v) == dict:
85                 for n_k, n_v in v.iteritems():
86                     next_data["%s.%s" % (k, n_k)] = n_v
87             elif type(v) == list:
88                 for index, item in enumerate(v):
89                     next_data["%s%d" % (k, index)] = item
90             else:
91                 next_data[k] = v
92
93         return self._dict_key_flatten(next_data)
94
95     def _get_nano_timestamp(self, results):
96         try:
97             timestamp = results["benchmark"]["timestamp"]
98         except Exception:
99             timestamp = time.time()
100
101         return str(int(float(timestamp) * 1000000000))
102
103     def _get_extended_tags(self, data):
104         runner_info = self.runners_info[data["runner_id"]]
105         tags = {
106             "runner_id": data["runner_id"],
107             "task_id": self.task_id,
108             "scenarios": runner_info["scenarios"]
109         }
110         if "host" in runner_info:
111             tags["host"] = runner_info["host"]
112         if "target" in runner_info:
113             tags["target"] = runner_info["target"]
114
115         return tags
116
117     def _data_to_line_protocol(self, data):
118         msg = {}
119         point = {}
120         point["measurement"] = self.tc
121         point["fields"] = self._dict_key_flatten(data["benchmark"]["data"])
122         point["time"] = self._get_nano_timestamp(data)
123         point["tags"] = self._get_extended_tags(data)
124         msg["points"] = [point]
125         msg["tags"] = self.static_tags
126
127         return make_lines(msg).encode('utf-8')
128
129     def record_result_data(self, data):
130         LOG.debug('Test result : %s' % json.dumps(data))
131         self.raw_result.append(data)
132         if self.target == '':
133             # if the target was not set, do not do anything
134             LOG.error('Dispatcher target was not set, no data will'
135                       'be posted.')
136             return -1
137
138         if isinstance(data, dict) and "scenario_cfg" in data:
139             self.tc = data["scenario_cfg"]["tc"]
140             self.task_id = data["scenario_cfg"]["task_id"]
141             scenario_cfg = data["scenario_cfg"]
142             runner_id = data["runner_id"]
143             self.runners_info[runner_id] = {"scenarios": scenario_cfg["type"]}
144             if "host" in scenario_cfg:
145                 self.runners_info[runner_id]["host"] = scenario_cfg["host"]
146             if "target" in scenario_cfg:
147                 self.runners_info[runner_id]["target"] = scenario_cfg["target"]
148             return 0
149
150         if self.tc == "":
151             LOG.error('Test result : %s' % json.dumps(data))
152             LOG.error('The case_name cannot be found, no data will be posted.')
153             return -1
154
155         try:
156             line = self._data_to_line_protocol(data)
157             LOG.debug('Test result line format : %s' % line)
158             res = requests.post(self.influxdb_url,
159                                 data=line,
160                                 auth=(self.username, self.password),
161                                 timeout=self.timeout)
162             if res.status_code != 204:
163                 LOG.error('Test result posting finished with status code'
164                           ' %d.' % res.status_code)
165                 LOG.error(res.text)
166
167         except Exception as err:
168             LOG.exception('Failed to record result data: %s',
169                           err)
170             return -1
171         return 0
172
173     def flush_result_data(self):
174         LOG.debug('Test result all : %s' % json.dumps(self.raw_result))
175         return 0