Merge "Bugfix: KeyError when using http dispatcher"
[yardstick.git] / yardstick / dispatcher / http.py
1 # Copyright 2013 IBM Corp
2 # All Rights Reserved.
3 #
4 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
5 #    not use this file except in compliance with the License. You may obtain
6 #    a copy of the License at
7 #
8 #         http://www.apache.org/licenses/LICENSE-2.0
9 #
10 #    Unless required by applicable law or agreed to in writing, software
11 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 #    License for the specific language governing permissions and limitations
14 #    under the License.
15
16 # yardstick comment: this is a modified copy of
17 # ceilometer/ceilometer/dispatcher/http.py
18
19 from __future__ import absolute_import
20
21 import logging
22 import os
23
24 from oslo_serialization import jsonutils
25 import requests
26 from oslo_config import cfg
27
28 from yardstick.dispatcher.base import Base as DispatchBase
29
30 LOG = logging.getLogger(__name__)
31
32 CONF = cfg.CONF
33 http_dispatcher_opts = [
34     cfg.StrOpt('target',
35                default=os.getenv('TARGET', 'http://127.0.0.1:8000/results'),
36                help='The target where the http request will be sent. '
37                     'If this is not set, no data will be posted. For '
38                     'example: target = http://hostname:1234/path'),
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(http_dispatcher_opts, group="dispatcher_http")
46
47
48 class HttpDispatcher(DispatchBase):
49     """Dispatcher class for posting data into a http target.
50     """
51
52     __dispatcher_type__ = "Http"
53
54     def __init__(self, conf, config):
55         super(HttpDispatcher, self).__init__(conf)
56         self.headers = {'Content-type': 'application/json'}
57         self.timeout = CONF.dispatcher_http.timeout
58         self.target = CONF.dispatcher_http.target
59         self.raw_result = []
60         self.result = {
61             "project_name": "yardstick",
62             "description": "yardstick test cases result",
63             "pod_name": os.environ.get('NODE_NAME', 'unknown'),
64             "installer": os.environ.get('INSTALLER_TYPE', 'unknown'),
65             "version": os.environ.get('YARDSTICK_VERSION', 'unknown'),
66             "build_tag": os.environ.get('BUILD_TAG')
67         }
68
69     def record_result_data(self, data):
70         self.raw_result.append(data)
71
72     def flush_result_data(self):
73         if self.target == '':
74             # if the target was not set, do not do anything
75             LOG.error('Dispatcher target was not set, no data will'
76                       'be posted.')
77             return
78
79         self.result["details"] = {'results': self.raw_result}
80
81         case_name = ""
82         for v in self.raw_result:
83             if isinstance(v, dict) and "scenario_cfg" in v:
84                 case_name = v["scenario_cfg"]["tc"]
85                 break
86         if case_name == "":
87             LOG.error('Test result : %s',
88                       jsonutils.dump_as_bytes(self.result))
89             LOG.error('The case_name cannot be found, no data will be posted.')
90             return
91
92         self.result["case_name"] = case_name
93
94         try:
95             LOG.debug('Test result : %s',
96                       jsonutils.dump_as_bytes(self.result))
97             res = requests.post(self.target,
98                                 data=jsonutils.dump_as_bytes(self.result),
99                                 headers=self.headers,
100                                 timeout=self.timeout)
101             LOG.debug('Test result posting finished with status code'
102                       ' %d.' % res.status_code)
103         except Exception as err:
104             LOG.exception('Failed to record result data: %s',
105                           err)