703cfca62bb5e3d3356c48467f3879bc1f832de4
[yardstick.git] / yardstick / dispatcher / http.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 json
11 import logging
12 import requests
13
14 from oslo_config import cfg
15
16 from yardstick.dispatcher.base import Base as DispatchBase
17
18 LOG = logging.getLogger(__name__)
19
20 CONF = cfg.CONF
21 http_dispatcher_opts = [
22     cfg.StrOpt('target',
23                default='http://127.0.0.1:8000/results',
24                help='The target where the http request will be sent. '
25                     'If this is not set, no data will be posted. For '
26                     'example: target = http://hostname:1234/path'),
27     cfg.IntOpt('timeout',
28                default=5,
29                help='The max time in seconds to wait for a request to '
30                     'timeout.'),
31 ]
32
33 CONF.register_opts(http_dispatcher_opts, group="dispatcher_http")
34
35
36 class HttpDispatcher(DispatchBase):
37     """Dispatcher class for posting data into a http target.
38     """
39
40     __dispatcher_type__ = "Http"
41
42     def __init__(self, conf):
43         super(HttpDispatcher, self).__init__(conf)
44         self.headers = {'Content-type': 'application/json'}
45         self.timeout = CONF.dispatcher_http.timeout
46         self.target = CONF.dispatcher_http.target
47
48     def record_result_data(self, data):
49         if self.target == '':
50             # if the target was not set, do not do anything
51             LOG.error('Dispatcher target was not set, no data will'
52                       'be posted.')
53             return
54
55         # We may have receive only one counter on the wire
56         if not isinstance(data, list):
57             data = [data]
58
59         for result in data:
60             try:
61                 LOG.debug('Message : %s' % result)
62                 res = requests.post(self.target,
63                                     data=json.dumps(result),
64                                     headers=self.headers,
65                                     timeout=self.timeout)
66                 LOG.debug('Message posting finished with status code'
67                           '%d.' % res.status_code)
68             except Exception as err:
69                 LOG.exception('Failed to record result data: %s',
70                               err)