af90b070316750079f21a84faa4af0181ed904e0
[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/ec2-user/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, context):
52         self.context = context
53         self.setup_done = False
54
55     def setup(self):
56         '''scenario setup'''
57         self.target_script = pkg_resources.resource_filename(
58             "yardstick.benchmark.scenarios.storage",
59             Fio.TARGET_SCRIPT)
60         user = self.context.get("user", "root")
61         host = self.context.get("host", None)
62         key_filename = self.context.get("key_filename", "~/.ssh/id_rsa")
63
64         LOG.info("user:%s, host:%s", user, host)
65         self.client = ssh.SSH(user, host, key_filename=key_filename)
66         self.client.wait(timeout=600)
67
68         # copy script to host
69         self.client.run("cat > ~/fio.sh",
70                         stdin=open(self.target_script, "rb"))
71
72         self.setup_done = True
73
74     def run(self, args, result):
75         """execute the benchmark"""
76         default_args = "-ioengine=libaio -direct=1 -group_reporting " \
77             "-numjobs=1 -time_based --output-format=json"
78
79         if not self.setup_done:
80             self.setup()
81
82         options = args["options"]
83         filename = options.get("filename", "/home/ec2-user/data.raw")
84         bs = options.get("bs", "4k")
85         iodepth = options.get("iodepth", "1")
86         rw = options.get("rw", "write")
87         ramp_time = options.get("ramp_time", 20)
88         name = "yardstick-fio"
89         # if run by a duration runner
90         duration_time = self.context.get("duration", None)
91         # if run by an arithmetic runner
92         arithmetic_time = options.get("duration", None)
93         if duration_time:
94             runtime = duration_time
95         elif arithmetic_time:
96             runtime = arithmetic_time
97         else:
98             runtime = 30
99
100         cmd_args = "-filename=%s -bs=%s -iodepth=%s -rw=%s -ramp_time=%s " \
101                    "-runtime=%s -name=%s %s" \
102                    % (filename, bs, iodepth, rw, ramp_time, runtime, name,
103                       default_args)
104         cmd = "sudo bash fio.sh %s %s" % (filename, cmd_args)
105         LOG.debug("Executing command: %s", cmd)
106         # Set timeout, so that the cmd execution does not exit incorrectly
107         # when the test run time is last long
108         timeout = int(ramp_time) + int(runtime) + 600
109         status, stdout, stderr = self.client.execute(cmd, timeout=timeout)
110         if status:
111             raise RuntimeError(stderr)
112
113         raw_data = json.loads(stdout)
114
115         # The bandwidth unit is KB/s, and latency unit is us
116         if rw in ["read", "randread", "rw", "randrw"]:
117             result["read_bw"] = raw_data["jobs"][0]["read"]["bw"]
118             result["read_iops"] = raw_data["jobs"][0]["read"]["iops"]
119             result["read_lat"] = raw_data["jobs"][0]["read"]["lat"]["mean"]
120         if rw in ["write", "randwrite", "rw", "randrw"]:
121             result["write_bw"] = raw_data["jobs"][0]["write"]["bw"]
122             result["write_iops"] = raw_data["jobs"][0]["write"]["iops"]
123             result["write_lat"] = raw_data["jobs"][0]["write"]["lat"]["mean"]
124
125         if "sla" in args:
126             sla_error = ""
127             for k, v in result.items():
128                 if k not in args['sla']:
129                     continue
130
131                 if "lat" in k:
132                     # For lattency small value is better
133                     max_v = float(args['sla'][k])
134                     if v > max_v:
135                         sla_error += "%s %f > sla:%s(%f); " % (k, v, k, max_v)
136                 else:
137                     # For bandwidth and iops big value is better
138                     min_v = int(args['sla'][k])
139                     if v < min_v:
140                         sla_error += "%s %d < " \
141                             "sla:%s(%d); " % (k, v, k, min_v)
142
143             assert sla_error == "", sla_error
144
145
146 def _test():
147     '''internal test function'''
148     key_filename = pkg_resources.resource_filename("yardstick.resources",
149                                                    "files/yardstick_key")
150     ctx = {
151         "host": "10.0.0.101",
152         "user": "ec2-user",
153         "key_filename": key_filename
154     }
155
156     logger = logging.getLogger("yardstick")
157     logger.setLevel(logging.DEBUG)
158
159     fio = Fio(ctx)
160
161     options = {
162         "filename": "/home/ec2-user/data.raw",
163         "bs": "4k",
164         "iodepth": "1",
165         "rw": "rw",
166         "ramp_time": 1,
167         "duration": 10
168     }
169     args = {"options": options}
170
171     result = fio.run(args)
172     print result
173
174 if __name__ == '__main__':
175     _test()