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