Add support for Python 3
[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.benchmark.scenarios import base
19
20 LOG = logging.getLogger(__name__)
21
22
23 class Ping(base.Scenario):
24     """Execute ping between two hosts
25
26   Parameters
27     packetsize - number of data bytes to send
28         type:    int
29         unit:    bytes
30         default: 56
31     """
32
33     __scenario_type__ = "Ping"
34
35     TARGET_SCRIPT = 'ping_benchmark.bash'
36
37     def __init__(self, scenario_cfg, context_cfg):
38         self.scenario_cfg = scenario_cfg
39         self.context_cfg = context_cfg
40         self.target_script = pkg_resources.resource_filename(
41             'yardstick.benchmark.scenarios.networking', Ping.TARGET_SCRIPT)
42         host = self.context_cfg['host']
43         user = host.get('user', 'ubuntu')
44         ssh_port = host.get("ssh_port", ssh.DEFAULT_PORT)
45         ip = host.get('ip', None)
46         key_filename = host.get('key_filename', '/root/.ssh/id_rsa')
47         password = host.get('password', None)
48
49         if password is not None:
50             LOG.info("Log in via pw, user:%s, host:%s, pw:%s",
51                      user, ip, password)
52             self.connection = ssh.SSH(user, ip, password=password,
53                                       port=ssh_port)
54         else:
55             LOG.info("Log in via key, user:%s, host:%s, key_filename:%s",
56                      user, ip, key_filename)
57             self.connection = ssh.SSH(user, ip, key_filename=key_filename,
58                                       port=ssh_port)
59
60         self.connection.wait(timeout=600)
61
62     def run(self, result):
63         """execute the benchmark"""
64
65         if "options" in self.scenario_cfg:
66             options = "-s %s" % \
67                 self.scenario_cfg['options'].get("packetsize", '56')
68         else:
69             options = ""
70
71         destination = self.context_cfg['target'].get('ipaddr', '127.0.0.1')
72         dest_list = [s.strip() for s in destination.split(',')]
73
74         result["rtt"] = {}
75         rtt_result = result["rtt"]
76
77         for pos, dest in enumerate(dest_list):
78             if 'targets' in self.scenario_cfg:
79                 target_vm = self.scenario_cfg['targets'][pos]
80             else:
81                 target_vm = self.scenario_cfg['target']
82
83             LOG.debug("ping '%s' '%s'", options, dest)
84             with open(self.target_script, "r") as stdin_file:
85                 exit_status, stdout, stderr = self.connection.execute(
86                     "/bin/sh -s {0} {1}".format(dest, options),
87                     stdin=stdin_file)
88
89             if exit_status != 0:
90                 raise RuntimeError(stderr)
91
92             if stdout:
93                 target_vm_name = target_vm.split('.')[0]
94                 rtt_result[target_vm_name] = float(stdout)
95                 if "sla" in self.scenario_cfg:
96                     sla_max_rtt = int(self.scenario_cfg["sla"]["max_rtt"])
97                     assert rtt_result[target_vm_name] <= sla_max_rtt,\
98                         "rtt %f > sla: max_rtt(%f); " % \
99                         (rtt_result[target_vm_name], sla_max_rtt)
100             else:
101                 LOG.error("ping '%s' '%s' timeout", options, target_vm)
102
103
104 def _test():    # pragma: no cover
105     '''internal test function'''
106     key_filename = pkg_resources.resource_filename("yardstick.resources",
107                                                    "files/yardstick_key")
108     ctx = {
109         "host": {
110             "ip": "10.229.47.137",
111             "user": "root",
112             "key_filename": key_filename
113         },
114         "target": {
115             "ipaddr": "10.229.17.105",
116         }
117     }
118
119     logger = logging.getLogger("yardstick")
120     logger.setLevel(logging.DEBUG)
121
122     args = {}
123     result = {}
124
125     p = Ping(args, ctx)
126     p.run(result)
127     print(result)
128
129
130 if __name__ == '__main__':    # pragma: no cover
131     _test()