Ping: Fix TypeError without SLA in timeout scenario
[yardstick.git] / yardstick / benchmark / scenarios / networking / ping.py
1 ##############################################################################
2 # Copyright (c) 2015 Ericsson AB 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 # ping scenario
11
12 from __future__ import print_function
13 from __future__ import absolute_import
14 import pkg_resources
15 import logging
16
17 import yardstick.ssh as ssh
18 from yardstick.common import utils
19 from yardstick.benchmark.scenarios import base
20
21 LOG = logging.getLogger(__name__)
22
23
24 class Ping(base.Scenario):
25     """Execute ping between two hosts
26
27     If ping error, RTT will be set to 999999
28
29   Parameters
30     packetsize - number of data bytes to send
31         type:    int
32         unit:    bytes
33         default: 56
34     """
35
36     __scenario_type__ = "Ping"
37
38     PING_ERROR_RTT = 999999
39
40     TARGET_SCRIPT = 'ping_benchmark.bash'
41
42     def __init__(self, scenario_cfg, context_cfg):
43         self.scenario_cfg = scenario_cfg
44         self.context_cfg = context_cfg
45         self.target_script = pkg_resources.resource_filename(
46             'yardstick.benchmark.scenarios.networking', Ping.TARGET_SCRIPT)
47         host = self.context_cfg['host']
48
49         self.connection = ssh.SSH.from_node(host, defaults={"user": "ubuntu"})
50
51         self.connection.wait(timeout=600)
52
53     def run(self, result):
54         """execute the benchmark"""
55
56         if "options" in self.scenario_cfg:
57             options = "-s %s" % \
58                 self.scenario_cfg['options'].get("packetsize", '56')
59         else:
60             options = ""
61
62         destination = self.context_cfg['target'].get('ipaddr', '127.0.0.1')
63         dest_list = [s.strip() for s in destination.split(',')]
64
65         rtt_result = {}
66         ping_result = {"rtt": rtt_result}
67         sla_max_rtt = self.scenario_cfg.get("sla", {}).get("max_rtt")
68
69         for pos, dest in enumerate(dest_list):
70             if 'targets' in self.scenario_cfg:
71                 target_vm = self.scenario_cfg['targets'][pos]
72             else:
73                 target_vm = self.scenario_cfg['target']
74
75             LOG.debug("ping %s %s", options, dest)
76             with open(self.target_script, "r") as stdin_file:
77                 exit_status, stdout, stderr = self.connection.execute(
78                     "/bin/sh -s {0} {1}".format(dest, options),
79                     stdin=stdin_file)
80
81             if exit_status != 0:
82                 raise RuntimeError(stderr)
83
84             if isinstance(target_vm, dict):
85                 target_vm_name = target_vm.get("name")
86             else:
87                 target_vm_name = target_vm.split('.')[0]
88             if stdout:
89                 rtt_result[target_vm_name] = float(stdout.strip())
90                 # store result before potential AssertionError
91                 result.update(utils.flatten_dict_key(ping_result))
92                 if sla_max_rtt is not None:
93                     sla_max_rtt = float(sla_max_rtt)
94                     self.verify_SLA(
95                         rtt_result[target_vm_name] <= sla_max_rtt,
96                         "rtt %f > sla: max_rtt(%f); "
97                         % (rtt_result[target_vm_name], sla_max_rtt))
98             else:
99                 LOG.error("ping '%s' '%s' timeout", options, target_vm)
100                 # we need to specify a result to satisfy influxdb schema
101                 # choose a very large number to inidcate timeout
102                 # in this case choose an order of magnitude greater than the SLA
103                 rtt_result[target_vm_name] = float(self.PING_ERROR_RTT)
104                 # store result before potential AssertionError
105                 result.update(utils.flatten_dict_key(ping_result))
106                 if sla_max_rtt is not None:
107                     self.verify_SLA(rtt_result[target_vm_name] <= sla_max_rtt,
108                                     "packet dropped rtt %f > sla: max_rtt(%f)"
109                                     % (rtt_result[target_vm_name], sla_max_rtt))
110                 else:
111                     self.verify_SLA(False,
112                                     "packet dropped rtt %f"
113                                     % (rtt_result[target_vm_name]))
114
115
116 def _test():    # pragma: no cover
117     """internal test function"""
118     key_filename = pkg_resources.resource_filename("yardstick.resources",
119                                                    "files/yardstick_key")
120     ctx = {
121         "host": {
122             "ip": "10.229.47.137",
123             "user": "root",
124             "key_filename": key_filename
125         },
126         "target": {
127             "ipaddr": "10.229.17.105",
128         }
129     }
130
131     logger = logging.getLogger("yardstick")
132     logger.setLevel(logging.DEBUG)
133
134     args = {}
135     result = {}
136
137     p = Ping(args, ctx)
138     p.run(result)
139     print(result)
140
141
142 if __name__ == '__main__':    # pragma: no cover
143     _test()