Merge "Adding python package requirement for VNF testing."
[yardstick.git] / yardstick / benchmark / scenarios / storage / fio.py
1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd.
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 from __future__ import absolute_import
10 from __future__ import print_function
11
12 import logging
13
14 import pkg_resources
15 from oslo_serialization import jsonutils
16
17 import yardstick.ssh as ssh
18 from yardstick.benchmark.scenarios import base
19
20 LOG = logging.getLogger(__name__)
21
22
23 class Fio(base.Scenario):
24     """Execute fio benchmark in a host
25
26   Parameters
27     filename - file name for fio workload
28         type:    string
29         unit:    na
30         default: /home/ubuntu/data.raw
31     bs - block size used for the io units
32         type:    int
33         unit:    bytes
34         default: 4k
35     iodepth - number of iobuffers to keep in flight
36         type:    int
37         unit:    na
38         default: 1
39     rw - type of io pattern [read, write, randwrite, randread, rw, randrw]
40         type:    string
41         unit:    na
42         default: write
43     ramp_time - run time before logging any performance
44         type:    int
45         unit:    seconds
46         default: 20
47
48     Read link below for more fio args description:
49         http://www.bluestop.org/fio/HOWTO.txt
50     """
51     __scenario_type__ = "Fio"
52
53     TARGET_SCRIPT = "fio_benchmark.bash"
54
55     def __init__(self, scenario_cfg, context_cfg):
56         self.scenario_cfg = scenario_cfg
57         self.context_cfg = context_cfg
58         self.setup_done = False
59
60     def setup(self):
61         '''scenario setup'''
62         self.target_script = pkg_resources.resource_filename(
63             "yardstick.benchmark.scenarios.storage",
64             Fio.TARGET_SCRIPT)
65         host = self.context_cfg["host"]
66         user = host.get("user", "root")
67         ssh_port = host.get("ssh_port", ssh.DEFAULT_PORT)
68         ip = host.get("ip", None)
69         key_filename = host.get("key_filename", "~/.ssh/id_rsa")
70
71         LOG.info("user:%s, host:%s", user, ip)
72         self.client = ssh.SSH(user, ip, key_filename=key_filename,
73                               port=ssh_port)
74         self.client.wait(timeout=600)
75
76         # copy script to host
77         self.client._put_file_shell(self.target_script, '~/fio.sh')
78
79         self.setup_done = True
80
81     def run(self, result):
82         """execute the benchmark"""
83         default_args = "-ioengine=libaio -direct=1 -group_reporting " \
84             "-numjobs=1 -time_based --output-format=json"
85
86         if not self.setup_done:
87             self.setup()
88
89         options = self.scenario_cfg["options"]
90         filename = options.get("filename", "/home/ubuntu/data.raw")
91         bs = options.get("bs", "4k")
92         iodepth = options.get("iodepth", "1")
93         rw = options.get("rw", "write")
94         ramp_time = options.get("ramp_time", 20)
95         name = "yardstick-fio"
96         # if run by a duration runner
97         duration_time = self.scenario_cfg["runner"].get("duration", None) \
98             if "runner" in self.scenario_cfg else None
99         # if run by an arithmetic runner
100         arithmetic_time = options.get("duration", None)
101         if duration_time:
102             runtime = duration_time
103         elif arithmetic_time:
104             runtime = arithmetic_time
105         else:
106             runtime = 30
107
108         cmd_args = "-filename=%s -bs=%s -iodepth=%s -rw=%s -ramp_time=%s " \
109                    "-runtime=%s -name=%s %s" \
110                    % (filename, bs, iodepth, rw, ramp_time, runtime, name,
111                       default_args)
112         cmd = "sudo bash fio.sh %s %s" % (filename, cmd_args)
113         LOG.debug("Executing command: %s", cmd)
114         # Set timeout, so that the cmd execution does not exit incorrectly
115         # when the test run time is last long
116         timeout = int(ramp_time) + int(runtime) + 600
117         status, stdout, stderr = self.client.execute(cmd, timeout=timeout)
118         if status:
119             raise RuntimeError(stderr)
120
121         raw_data = jsonutils.loads(stdout)
122
123         # The bandwidth unit is KB/s, and latency unit is us
124         if rw in ["read", "randread", "rw", "randrw"]:
125             result["read_bw"] = raw_data["jobs"][0]["read"]["bw"]
126             result["read_iops"] = raw_data["jobs"][0]["read"]["iops"]
127             result["read_lat"] = raw_data["jobs"][0]["read"]["lat"]["mean"]
128         if rw in ["write", "randwrite", "rw", "randrw"]:
129             result["write_bw"] = raw_data["jobs"][0]["write"]["bw"]
130             result["write_iops"] = raw_data["jobs"][0]["write"]["iops"]
131             result["write_lat"] = raw_data["jobs"][0]["write"]["lat"]["mean"]
132
133         if "sla" in self.scenario_cfg:
134             sla_error = ""
135             for k, v in result.items():
136                 if k not in self.scenario_cfg['sla']:
137                     continue
138
139                 if "lat" in k:
140                     # For lattency small value is better
141                     max_v = float(self.scenario_cfg['sla'][k])
142                     if v > max_v:
143                         sla_error += "%s %f > sla:%s(%f); " % (k, v, k, max_v)
144                 else:
145                     # For bandwidth and iops big value is better
146                     min_v = int(self.scenario_cfg['sla'][k])
147                     if v < min_v:
148                         sla_error += "%s %d < " \
149                             "sla:%s(%d); " % (k, v, k, min_v)
150
151             assert sla_error == "", sla_error
152
153
154 def _test():
155     '''internal test function'''
156     key_filename = pkg_resources.resource_filename("yardstick.resources",
157                                                    "files/yardstick_key")
158     ctx = {
159         "host": {
160             "ip": "10.229.47.137",
161             "user": "root",
162             "key_filename": key_filename
163         }
164     }
165
166     logger = logging.getLogger("yardstick")
167     logger.setLevel(logging.DEBUG)
168
169     options = {
170         "filename": "/home/ubuntu/data.raw",
171         "bs": "4k",
172         "iodepth": "1",
173         "rw": "rw",
174         "ramp_time": 1,
175         "duration": 10
176     }
177     result = {}
178     args = {"options": options}
179
180     fio = Fio(args, ctx)
181     fio.run(result)
182     print(result)
183
184
185 if __name__ == '__main__':
186     _test()