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