add yardstick iruya 9.0.0 release notes
[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     job_file - fio job configuration file
32         type:    string
33         unit:    na
34         default: None
35     job_file_config - content of job configuration file
36         type:    list
37         unit:    na
38         default: None
39     directory - mount directoey for test volume
40         type:    string
41         unit:    na
42         default: None
43     bs - block size used for the io units
44         type:    int
45         unit:    bytes
46         default: 4k
47     iodepth - number of iobuffers to keep in flight
48         type:    int
49         unit:    na
50         default: 1
51     rw - type of io pattern [read, write, randwrite, randread, rw, randrw]
52         type:    string
53         unit:    na
54         default: write
55     rwmixwrite - percentage of a mixed workload that should be writes
56         type: int
57         unit: percentage
58         default: 50
59     ramp_time - run time before logging any performance
60         type:    int
61         unit:    seconds
62         default: 20
63     direct - whether use non-buffered I/O or not
64         type:    boolean
65         unit:    na
66         default: 1
67     size - total size of I/O for this job.
68         type:    string
69         unit:    na
70         default: 1g
71     numjobs - number of clones (processes/threads performing the same workload) of this job
72         type:    int
73         unit:    na
74         default: 1
75
76     Read link below for more fio args description:
77         http://www.bluestop.org/fio/HOWTO.txt
78     """
79     __scenario_type__ = "Fio"
80
81     TARGET_SCRIPT = "fio_benchmark.bash"
82
83     def __init__(self, scenario_cfg, context_cfg):
84         self.scenario_cfg = scenario_cfg
85         self.context_cfg = context_cfg
86         self.options = self.scenario_cfg["options"]
87         self.setup_done = False
88
89     def setup(self):
90         """scenario setup"""
91         host = self.context_cfg["host"]
92
93         self.client = ssh.SSH.from_node(host, defaults={"user": "root"})
94         self.client.wait(timeout=600)
95
96         self.job_file = self.options.get("job_file", None)
97         config_lines = self.options.get("job_file_config", None)
98
99         if self.job_file:
100             self.job_file_script = pkg_resources.resource_filename(
101                 "yardstick.resources", 'files/' + self.job_file)
102
103             # copy job file to host
104             self.client._put_file_shell(self.job_file_script, '~/job_file.ini')
105         elif config_lines:
106             LOG.debug("Job file configuration received, Fio job file will be created.")
107             self.job_file = 'tmp_job_file.ini'
108             self.job_file_script = pkg_resources.resource_filename(
109                 "yardstick.resources", 'files/' + self.job_file)
110             with open(self.job_file_script, 'w') as f:
111                 f.write('\n'.join(str(line) for line in config_lines))
112
113             # copy job file to host
114             self.client._put_file_shell(self.job_file_script, '~/job_file.ini')
115         else:
116             LOG.debug("No job file configuration received, Fio will use parameters.")
117             self.target_script = pkg_resources.resource_filename(
118                 "yardstick.benchmark.scenarios.storage", Fio.TARGET_SCRIPT)
119
120             # copy script to host
121             self.client._put_file_shell(self.target_script, '~/fio.sh')
122
123         mount_dir = self.options.get("directory", None)
124
125         if mount_dir:
126             LOG.debug("Formating volume...")
127             _, stdout, _ = self.client.execute(
128                 "lsblk -dps | grep -m 1 disk | awk '{print $1}'")
129             block_device = stdout.strip()
130             if block_device:
131                  self.client.execute("sudo mkfs.ext4 %s" % block_device)
132                  cmd = "sudo mkdir %s" % mount_dir
133                  self.client.execute(cmd)
134                  LOG.debug("Mounting volume at: %s", mount_dir)
135                  cmd = "sudo mount %s %s" % (block_device, mount_dir)
136                  self.client.execute(cmd)
137
138         self.setup_done = True
139
140     def run(self, result):
141         """execute the benchmark"""
142         default_args = "-ioengine=libaio -group_reporting -time_based -time_based " \
143             "--output-format=json"
144         timeout = 3600
145
146         if not self.setup_done:
147             self.setup()
148
149         if self.job_file:
150             cmd = "sudo fio job_file.ini --output-format=json"
151         else:
152             filename = self.options.get("filename", "/home/ubuntu/data.raw")
153             bs = self.options.get("bs", "4k")
154             iodepth = self.options.get("iodepth", "1")
155             rw = self.options.get("rw", "write")
156             ramp_time = self.options.get("ramp_time", 20)
157             size = self.options.get("size", "1g")
158             direct = self.options.get("direct", "1")
159             numjobs = self.options.get("numjobs", "1")
160             rwmixwrite = self.options.get("rwmixwrite", 50)
161             name = "yardstick-fio"
162             # if run by a duration runner
163             duration_time = self.scenario_cfg["runner"].get("duration", None) \
164                 if "runner" in self.scenario_cfg else None
165             # if run by an arithmetic runner
166             arithmetic_time = self.options.get("duration", None)
167             if duration_time:
168                 runtime = duration_time
169             elif arithmetic_time:
170                 runtime = arithmetic_time
171             else:
172                 runtime = 30
173             # Set timeout, so that the cmd execution does not exit incorrectly
174             # when the test run time is last long
175             timeout = int(ramp_time) + int(runtime) + 600
176
177             cmd_args = "-filename=%s -direct=%s -bs=%s -iodepth=%s -rw=%s -rwmixwrite=%s " \
178                        "-size=%s -ramp_time=%s -numjobs=%s -runtime=%s -name=%s %s" \
179                        % (filename, direct, bs, iodepth, rw, rwmixwrite, size, ramp_time, numjobs,
180                           runtime, name, default_args)
181             cmd = "sudo bash fio.sh %s %s" % (filename, cmd_args)
182
183         LOG.debug("Executing command: %s", cmd)
184         status, stdout, stderr = self.client.execute(cmd, timeout=timeout)
185         if status:
186             raise RuntimeError(stderr)
187
188         raw_data = jsonutils.loads(stdout)
189
190         if self.job_file:
191             result["read_bw"] = raw_data["jobs"][0]["read"]["bw"]
192             result["read_iops"] = raw_data["jobs"][0]["read"]["iops"]
193             result["read_lat"] = raw_data["jobs"][0]["read"]["lat"]["mean"]
194             result["write_bw"] = raw_data["jobs"][0]["write"]["bw"]
195             result["write_iops"] = raw_data["jobs"][0]["write"]["iops"]
196             result["write_lat"] = raw_data["jobs"][0]["write"]["lat"]["mean"]
197         else:
198             # The bandwidth unit is KB/s, and latency unit is us
199             if rw in ["read", "randread", "rw", "randrw"]:
200                 result["read_bw"] = raw_data["jobs"][0]["read"]["bw"]
201                 result["read_iops"] = raw_data["jobs"][0]["read"]["iops"]
202                 result["read_lat"] = raw_data["jobs"][0]["read"]["lat"]["mean"]
203             if rw in ["write", "randwrite", "rw", "randrw"]:
204                 result["write_bw"] = raw_data["jobs"][0]["write"]["bw"]
205                 result["write_iops"] = raw_data["jobs"][0]["write"]["iops"]
206                 result["write_lat"] = raw_data["jobs"][0]["write"]["lat"]["mean"]
207
208         if "sla" in self.scenario_cfg:
209             sla_error = ""
210             for k, v in result.items():
211                 if k not in self.scenario_cfg['sla']:
212                     continue
213
214                 if "lat" in k:
215                     # For lattency small value is better
216                     max_v = float(self.scenario_cfg['sla'][k])
217                     if v > max_v:
218                         sla_error += "%s %f > sla:%s(%f); " % (k, v, k, max_v)
219                 else:
220                     # For bandwidth and iops big value is better
221                     min_v = int(self.scenario_cfg['sla'][k])
222                     if v < min_v:
223                         sla_error += "%s %d < " \
224                             "sla:%s(%d); " % (k, v, k, min_v)
225
226             self.verify_SLA(sla_error == "", sla_error)
227
228
229 def _test():
230     """internal test function"""
231     key_filename = pkg_resources.resource_filename("yardstick.resources",
232                                                    "files/yardstick_key")
233     ctx = {
234         "host": {
235             "ip": "10.229.47.137",
236             "user": "root",
237             "key_filename": key_filename
238         }
239     }
240
241     logger = logging.getLogger("yardstick")
242     logger.setLevel(logging.DEBUG)
243
244     options = {
245         "filename": "/home/ubuntu/data.raw",
246         "bs": "4k",
247         "iodepth": "1",
248         "rw": "rw",
249         "ramp_time": 1,
250         "duration": 10
251     }
252     result = {}
253     args = {"options": options}
254
255     fio = Fio(args, ctx)
256     fio.run(result)
257     print(result)
258
259
260 if __name__ == '__main__':
261     _test()