2 # SPDX-License-Identifier: GPL-2.0-only
4 # Copyright (c) 2019 Western Digital Corporation or its affiliates.
9 # Automate running of fio tests
12 # python3 run-fio-tests.py [-r fio-root] [-f fio-path] [-a artifact-root]
13 # [--skip # # #...] [--run-only # # #...]
17 # # git clone git://git.kernel.dk/fio.git
20 # # python3 t/run-fio-tests.py
24 # - Python 3.5 (subprocess.run)
25 # - Linux (libaio ioengine, zbd tests, etc)
26 # - The artifact directory must be on a file system that accepts 512-byte IO
27 # (t0002, t0003, t0004).
28 # - The artifact directory needs to be on an SSD. Otherwise tests that carry
29 # out file-based IO will trigger a timeout (t0006).
31 # - SciPy (steadystate_tests.py)
32 # - libzbc (zbd tests)
33 # - root privileges (zbd test)
34 # - kernel 4.19 or later for zoned null block devices (zbd tests)
35 # - CUnit support (unittests)
40 # TODO run multiple tests simultaneously
41 # TODO Add sgunmap tests (requires SAS SSD)
53 import multiprocessing
54 from pathlib import Path
57 class FioTest(object):
58 """Base for all fio tests."""
60 def __init__(self, exe_path, parameters, success):
61 self.exe_path = exe_path
62 self.parameters = parameters
63 self.success = success
65 self.artifact_root = None
69 self.failure_reason = ''
70 self.command_file = None
71 self.stdout_file = None
72 self.stderr_file = None
73 self.exitcode_file = None
75 def setup(self, artifact_root, testnum):
76 """Setup instance variables for test."""
78 self.artifact_root = artifact_root
79 self.testnum = testnum
80 self.test_dir = os.path.join(artifact_root, "{:04d}".format(testnum))
81 if not os.path.exists(self.test_dir):
82 os.mkdir(self.test_dir)
84 self.command_file = os.path.join(
86 "{0}.command".format(os.path.basename(self.exe_path)))
87 self.stdout_file = os.path.join(
89 "{0}.stdout".format(os.path.basename(self.exe_path)))
90 self.stderr_file = os.path.join(
92 "{0}.stderr".format(os.path.basename(self.exe_path)))
93 self.exitcode_file = os.path.join(
95 "{0}.exitcode".format(os.path.basename(self.exe_path)))
100 raise NotImplementedError()
102 def check_result(self):
103 """Check test results."""
105 raise NotImplementedError()
108 class FioExeTest(FioTest):
109 """Test consists of an executable binary or script"""
111 def __init__(self, exe_path, parameters, success):
112 """Construct a FioExeTest which is a FioTest consisting of an
113 executable binary or script.
115 exe_path: location of executable binary or script
116 parameters: list of parameters for executable
117 success: Definition of test success
120 FioTest.__init__(self, exe_path, parameters, success)
123 """Execute the binary or script described by this instance."""
126 command = [self.exe_path] + self.parameters
128 command = [self.exe_path]
129 command_file = open(self.command_file, "w+")
130 command_file.write("%s\n" % command)
133 stdout_file = open(self.stdout_file, "w+")
134 stderr_file = open(self.stderr_file, "w+")
135 exitcode_file = open(self.exitcode_file, "w+")
138 # Avoid using subprocess.run() here because when a timeout occurs,
139 # fio will be stopped with SIGKILL. This does not give fio a
140 # chance to clean up and means that child processes may continue
141 # running and submitting IO.
142 proc = subprocess.Popen(command,
146 universal_newlines=True)
147 proc.communicate(timeout=self.success['timeout'])
148 exitcode_file.write('{0}\n'.format(proc.returncode))
149 logging.debug("Test %d: return code: %d", self.testnum, proc.returncode)
150 self.output['proc'] = proc
151 except subprocess.TimeoutExpired:
155 self.output['failure'] = 'timeout'
161 self.output['failure'] = 'exception'
162 self.output['exc_info'] = sys.exc_info()
166 exitcode_file.close()
168 def check_result(self):
169 """Check results of test run."""
171 if 'proc' not in self.output:
172 if self.output['failure'] == 'timeout':
173 self.failure_reason = "{0} timeout,".format(self.failure_reason)
175 assert self.output['failure'] == 'exception'
176 self.failure_reason = '{0} exception: {1}, {2}'.format(
177 self.failure_reason, self.output['exc_info'][0],
178 self.output['exc_info'][1])
183 if 'zero_return' in self.success:
184 if self.success['zero_return']:
185 if self.output['proc'].returncode != 0:
187 self.failure_reason = "{0} non-zero return code,".format(self.failure_reason)
189 if self.output['proc'].returncode == 0:
190 self.failure_reason = "{0} zero return code,".format(self.failure_reason)
193 stderr_size = os.path.getsize(self.stderr_file)
194 if 'stderr_empty' in self.success:
195 if self.success['stderr_empty']:
197 self.failure_reason = "{0} stderr not empty,".format(self.failure_reason)
201 self.failure_reason = "{0} stderr empty,".format(self.failure_reason)
205 class FioJobTest(FioExeTest):
206 """Test consists of a fio job"""
208 def __init__(self, fio_path, fio_job, success, fio_pre_job=None,
209 fio_pre_success=None, output_format="normal"):
210 """Construct a FioJobTest which is a FioExeTest consisting of a
211 single fio job file with an optional setup step.
213 fio_path: location of fio executable
214 fio_job: location of fio job file
215 success: Definition of test success
216 fio_pre_job: fio job for preconditioning
217 fio_pre_success: Definition of test success for fio precon job
218 output_format: normal (default), json, jsonplus, or terse
221 self.fio_job = fio_job
222 self.fio_pre_job = fio_pre_job
223 self.fio_pre_success = fio_pre_success if fio_pre_success else success
224 self.output_format = output_format
225 self.precon_failed = False
226 self.json_data = None
227 self.fio_output = "{0}.output".format(os.path.basename(self.fio_job))
229 "--output-format={0}".format(self.output_format),
230 "--output={0}".format(self.fio_output),
233 FioExeTest.__init__(self, fio_path, self.fio_args, success)
235 def setup(self, artifact_root, testnum):
236 """Setup instance variables for fio job test."""
238 super(FioJobTest, self).setup(artifact_root, testnum)
240 self.command_file = os.path.join(
242 "{0}.command".format(os.path.basename(self.fio_job)))
243 self.stdout_file = os.path.join(
245 "{0}.stdout".format(os.path.basename(self.fio_job)))
246 self.stderr_file = os.path.join(
248 "{0}.stderr".format(os.path.basename(self.fio_job)))
249 self.exitcode_file = os.path.join(
251 "{0}.exitcode".format(os.path.basename(self.fio_job)))
253 def run_pre_job(self):
254 """Run fio job precondition step."""
256 precon = FioJobTest(self.exe_path, self.fio_pre_job,
257 self.fio_pre_success,
258 output_format=self.output_format)
259 precon.setup(self.artifact_root, self.testnum)
261 precon.check_result()
262 self.precon_failed = not precon.passed
263 self.failure_reason = precon.failure_reason
266 """Run fio job test."""
271 if not self.precon_failed:
272 super(FioJobTest, self).run()
274 logging.debug("Test %d: precondition step failed", self.testnum)
276 def check_result(self):
277 """Check fio job results."""
279 if self.precon_failed:
281 self.failure_reason = "{0} precondition step failed,".format(self.failure_reason)
284 super(FioJobTest, self).check_result()
289 if 'json' not in self.output_format:
293 with open(os.path.join(self.test_dir, self.fio_output), "r") as output_file:
294 file_data = output_file.read()
295 except EnvironmentError:
296 self.failure_reason = "{0} unable to open output file,".format(self.failure_reason)
301 # Sometimes fio informational messages are included at the top of the
302 # JSON output, especially under Windows. Try to decode output as JSON
303 # data, lopping off up to the first four lines
305 lines = file_data.splitlines()
307 file_data = '\n'.join(lines[i:])
309 self.json_data = json.loads(file_data)
310 except json.JSONDecodeError:
313 logging.debug("Test %d: skipped %d lines decoding JSON data", self.testnum, i)
316 self.failure_reason = "{0} unable to decode JSON data,".format(self.failure_reason)
320 class FioJobTest_t0005(FioJobTest):
321 """Test consists of fio test job t0005
322 Confirm that read['io_kbytes'] == write['io_kbytes'] == 102400"""
324 def check_result(self):
325 super(FioJobTest_t0005, self).check_result()
330 if self.json_data['jobs'][0]['read']['io_kbytes'] != 102400:
331 self.failure_reason = "{0} bytes read mismatch,".format(self.failure_reason)
333 if self.json_data['jobs'][0]['write']['io_kbytes'] != 102400:
334 self.failure_reason = "{0} bytes written mismatch,".format(self.failure_reason)
338 class FioJobTest_t0006(FioJobTest):
339 """Test consists of fio test job t0006
340 Confirm that read['io_kbytes'] ~ 2*write['io_kbytes']"""
342 def check_result(self):
343 super(FioJobTest_t0006, self).check_result()
348 ratio = self.json_data['jobs'][0]['read']['io_kbytes'] \
349 / self.json_data['jobs'][0]['write']['io_kbytes']
350 logging.debug("Test %d: ratio: %f", self.testnum, ratio)
351 if ratio < 1.99 or ratio > 2.01:
352 self.failure_reason = "{0} read/write ratio mismatch,".format(self.failure_reason)
356 class FioJobTest_t0007(FioJobTest):
357 """Test consists of fio test job t0007
358 Confirm that read['io_kbytes'] = 87040"""
360 def check_result(self):
361 super(FioJobTest_t0007, self).check_result()
366 if self.json_data['jobs'][0]['read']['io_kbytes'] != 87040:
367 self.failure_reason = "{0} bytes read mismatch,".format(self.failure_reason)
371 class FioJobTest_t0008(FioJobTest):
372 """Test consists of fio test job t0008
373 Confirm that read['io_kbytes'] = 32768 and that
374 write['io_kbytes'] ~ 16568
376 I did runs with fio-ae2fafc8 and saw write['io_kbytes'] values of
377 16585, 16588. With two runs of fio-3.16 I obtained 16568"""
379 def check_result(self):
380 super(FioJobTest_t0008, self).check_result()
385 ratio = self.json_data['jobs'][0]['write']['io_kbytes'] / 16568
386 logging.debug("Test %d: ratio: %f", self.testnum, ratio)
388 if ratio < 0.99 or ratio > 1.01:
389 self.failure_reason = "{0} bytes written mismatch,".format(self.failure_reason)
391 if self.json_data['jobs'][0]['read']['io_kbytes'] != 32768:
392 self.failure_reason = "{0} bytes read mismatch,".format(self.failure_reason)
396 class FioJobTest_t0009(FioJobTest):
397 """Test consists of fio test job t0009
398 Confirm that runtime >= 60s"""
400 def check_result(self):
401 super(FioJobTest_t0009, self).check_result()
406 logging.debug('Test %d: elapsed: %d', self.testnum, self.json_data['jobs'][0]['elapsed'])
408 if self.json_data['jobs'][0]['elapsed'] < 60:
409 self.failure_reason = "{0} elapsed time mismatch,".format(self.failure_reason)
413 class FioJobTest_t0011(FioJobTest):
414 """Test consists of fio test job t0009
415 Confirm that job0 iops == 1000
416 and that job1_iops / job0_iops ~ 8
417 With two runs of fio-3.16 I observed a ratio of 8.3"""
419 def check_result(self):
420 super(FioJobTest_t0011, self).check_result()
425 iops1 = self.json_data['jobs'][0]['read']['iops']
426 iops2 = self.json_data['jobs'][1]['read']['iops']
427 ratio = iops2 / iops1
428 logging.debug("Test %d: iops1: %f", self.testnum, iops1)
429 logging.debug("Test %d: ratio: %f", self.testnum, ratio)
431 if iops1 < 998 or iops1 > 1002:
432 self.failure_reason = "{0} iops value mismatch,".format(self.failure_reason)
435 if ratio < 7 or ratio > 9:
436 self.failure_reason = "{0} iops ratio mismatch,".format(self.failure_reason)
440 class Requirements(object):
441 """Requirements consists of multiple run environment characteristics.
442 These are to determine if a particular test can be run"""
454 def __init__(self, fio_root):
455 Requirements._not_macos = platform.system() != "Darwin"
456 Requirements._not_windows = platform.system() != "Windows"
457 Requirements._linux = platform.system() == "Linux"
459 if Requirements._linux:
461 config_file = os.path.join(fio_root, "config-host.h")
462 with open(config_file, "r") as config:
463 contents = config.read()
465 print("Unable to open {0} to check requirements".format(config_file))
466 Requirements._zbd = True
468 Requirements._zbd = "CONFIG_HAS_BLKZONED" in contents
469 Requirements._libaio = "CONFIG_LIBAIO" in contents
471 Requirements._root = (os.geteuid() == 0)
472 if Requirements._zbd and Requirements._root:
473 subprocess.run(["modprobe", "null_blk"],
474 stdout=subprocess.PIPE,
475 stderr=subprocess.PIPE)
476 if os.path.exists("/sys/module/null_blk/parameters/zoned"):
477 Requirements._zoned_nullb = True
479 if platform.system() == "Windows":
480 utest_exe = "unittest.exe"
482 utest_exe = "unittest"
483 unittest_path = os.path.join(fio_root, "unittests", utest_exe)
484 Requirements._unittests = os.path.exists(unittest_path)
486 Requirements._cpucount4 = multiprocessing.cpu_count() >= 4
488 req_list = [Requirements.linux,
492 Requirements.zoned_nullb,
493 Requirements.not_macos,
494 Requirements.not_windows,
495 Requirements.unittests,
496 Requirements.cpucount4]
499 logging.debug("Requirements: Requirement '%s' met? %s", desc, value)
503 """Are we running on Linux?"""
504 return Requirements._linux, "Linux required"
508 """Is libaio available?"""
509 return Requirements._libaio, "libaio required"
513 """Is ZBD support available?"""
514 return Requirements._zbd, "Zoned block device support required"
518 """Are we running as root?"""
519 return Requirements._root, "root required"
522 def zoned_nullb(cls):
523 """Are zoned null block devices available?"""
524 return Requirements._zoned_nullb, "Zoned null block device support required"
528 """Are we running on a platform other than macOS?"""
529 return Requirements._not_macos, "platform other than macOS required"
532 def not_windows(cls):
533 """Are we running on a platform other than Windws?"""
534 return Requirements._not_windows, "platform other than Windows required"
538 """Were unittests built?"""
539 return Requirements._unittests, "Unittests support required"
543 """Do we have at least 4 CPUs?"""
544 return Requirements._cpucount4, "4+ CPUs required"
549 'stderr_empty': True,
553 'zero_return': False,
554 'stderr_empty': False,
559 'stderr_empty': False,
565 'test_class': FioJobTest,
566 'job': 't0001-52c58027.fio',
567 'success': SUCCESS_DEFAULT,
574 'test_class': FioJobTest,
575 'job': 't0002-13af05ae-post.fio',
576 'success': SUCCESS_DEFAULT,
577 'pre_job': 't0002-13af05ae-pre.fio',
579 'requirements': [Requirements.linux, Requirements.libaio],
583 'test_class': FioJobTest,
584 'job': 't0003-0ae2c6e1-post.fio',
585 'success': SUCCESS_NONZERO,
586 'pre_job': 't0003-0ae2c6e1-pre.fio',
587 'pre_success': SUCCESS_DEFAULT,
588 'requirements': [Requirements.linux, Requirements.libaio],
592 'test_class': FioJobTest,
593 'job': 't0004-8a99fdf6.fio',
594 'success': SUCCESS_DEFAULT,
597 'requirements': [Requirements.linux, Requirements.libaio],
601 'test_class': FioJobTest_t0005,
602 'job': 't0005-f7078f7b.fio',
603 'success': SUCCESS_DEFAULT,
606 'output_format': 'json',
607 'requirements': [Requirements.not_windows],
611 'test_class': FioJobTest_t0006,
612 'job': 't0006-82af2a7c.fio',
613 'success': SUCCESS_DEFAULT,
616 'output_format': 'json',
617 'requirements': [Requirements.linux, Requirements.libaio],
621 'test_class': FioJobTest_t0007,
622 'job': 't0007-37cf9e3c.fio',
623 'success': SUCCESS_DEFAULT,
626 'output_format': 'json',
631 'test_class': FioJobTest_t0008,
632 'job': 't0008-ae2fafc8.fio',
633 'success': SUCCESS_DEFAULT,
636 'output_format': 'json',
641 'test_class': FioJobTest_t0009,
642 'job': 't0009-f8b0bd10.fio',
643 'success': SUCCESS_DEFAULT,
646 'output_format': 'json',
647 'requirements': [Requirements.not_macos,
648 Requirements.cpucount4],
649 # mac os does not support CPU affinity
653 'test_class': FioJobTest,
654 'job': 't0010-b7aae4ba.fio',
655 'success': SUCCESS_DEFAULT,
662 'test_class': FioJobTest_t0011,
663 'job': 't0011-5d2788d5.fio',
664 'success': SUCCESS_DEFAULT,
667 'output_format': 'json',
672 'test_class': FioExeTest,
675 'success': SUCCESS_DEFAULT,
680 'test_class': FioExeTest,
683 'success': SUCCESS_DEFAULT,
688 'test_class': FioExeTest,
689 'exe': 't/lfsr-test',
690 'parameters': ['0xFFFFFF', '0', '0', 'verify'],
691 'success': SUCCESS_STDERR,
696 'test_class': FioExeTest,
697 'exe': 't/readonly.py',
698 'parameters': ['-f', '{fio_path}'],
699 'success': SUCCESS_DEFAULT,
704 'test_class': FioExeTest,
705 'exe': 't/steadystate_tests.py',
706 'parameters': ['{fio_path}'],
707 'success': SUCCESS_DEFAULT,
712 'test_class': FioExeTest,
715 'success': SUCCESS_STDERR,
720 'test_class': FioExeTest,
721 'exe': 't/strided.py',
722 'parameters': ['{fio_path}'],
723 'success': SUCCESS_DEFAULT,
728 'test_class': FioExeTest,
729 'exe': 't/zbd/run-tests-against-regular-nullb',
731 'success': SUCCESS_DEFAULT,
732 'requirements': [Requirements.linux, Requirements.zbd,
737 'test_class': FioExeTest,
738 'exe': 't/zbd/run-tests-against-zoned-nullb',
740 'success': SUCCESS_DEFAULT,
741 'requirements': [Requirements.linux, Requirements.zbd,
742 Requirements.root, Requirements.zoned_nullb],
746 'test_class': FioExeTest,
747 'exe': 'unittests/unittest',
749 'success': SUCCESS_DEFAULT,
750 'requirements': [Requirements.unittests],
754 'test_class': FioExeTest,
755 'exe': 't/latency_percentiles.py',
756 'parameters': ['-f', '{fio_path}'],
757 'success': SUCCESS_DEFAULT,
762 'test_class': FioExeTest,
763 'exe': 't/jsonplus2csv_test.py',
764 'parameters': ['-f', '{fio_path}'],
765 'success': SUCCESS_DEFAULT,
772 """Parse command-line arguments."""
774 parser = argparse.ArgumentParser()
775 parser.add_argument('-r', '--fio-root',
776 help='fio root path')
777 parser.add_argument('-f', '--fio',
778 help='path to fio executable (e.g., ./fio)')
779 parser.add_argument('-a', '--artifact-root',
780 help='artifact root directory')
781 parser.add_argument('-s', '--skip', nargs='+', type=int,
782 help='list of test(s) to skip')
783 parser.add_argument('-o', '--run-only', nargs='+', type=int,
784 help='list of test(s) to run, skipping all others')
785 parser.add_argument('-d', '--debug', action='store_true',
786 help='provide debug output')
787 parser.add_argument('-k', '--skip-req', action='store_true',
788 help='skip requirements checking')
789 args = parser.parse_args()
799 logging.basicConfig(level=logging.DEBUG)
801 logging.basicConfig(level=logging.INFO)
804 fio_root = args.fio_root
806 fio_root = str(Path(__file__).absolute().parent.parent)
807 print("fio root is %s" % fio_root)
812 if platform.system() == "Windows":
816 fio_path = os.path.join(fio_root, fio_exe)
817 print("fio path is %s" % fio_path)
818 if not shutil.which(fio_path):
819 print("Warning: fio executable not found")
821 artifact_root = args.artifact_root if args.artifact_root else \
822 "fio-test-{0}".format(time.strftime("%Y%m%d-%H%M%S"))
823 os.mkdir(artifact_root)
824 print("Artifact directory is %s" % artifact_root)
826 if not args.skip_req:
827 req = Requirements(fio_root)
833 for config in TEST_LIST:
834 if (args.skip and config['test_id'] in args.skip) or \
835 (args.run_only and config['test_id'] not in args.run_only):
836 skipped = skipped + 1
837 print("Test {0} SKIPPED (User request)".format(config['test_id']))
840 if issubclass(config['test_class'], FioJobTest):
841 if config['pre_job']:
842 fio_pre_job = os.path.join(fio_root, 't', 'jobs',
846 if config['pre_success']:
847 fio_pre_success = config['pre_success']
849 fio_pre_success = None
850 if 'output_format' in config:
851 output_format = config['output_format']
853 output_format = 'normal'
854 test = config['test_class'](
856 os.path.join(fio_root, 't', 'jobs', config['job']),
858 fio_pre_job=fio_pre_job,
859 fio_pre_success=fio_pre_success,
860 output_format=output_format)
861 elif issubclass(config['test_class'], FioExeTest):
862 exe_path = os.path.join(fio_root, config['exe'])
863 if config['parameters']:
864 parameters = [p.format(fio_path=fio_path) for p in config['parameters']]
867 if Path(exe_path).suffix == '.py' and platform.system() == "Windows":
869 parameters.insert(0, exe_path)
871 parameters = [exe_path]
872 exe_path = "python.exe"
873 test = config['test_class'](exe_path, parameters,
876 print("Test {0} FAILED: unable to process test config".format(config['test_id']))
880 if not args.skip_req:
882 for req in config['requirements']:
883 reqs_met, reason = req()
884 logging.debug("Test %d: Requirement '%s' met? %s", config['test_id'], reason,
889 print("Test {0} SKIPPED ({1})".format(config['test_id'], reason))
890 skipped = skipped + 1
893 test.setup(artifact_root, config['test_id'])
900 result = "FAILED: {0}".format(test.failure_reason)
902 with open(test.stderr_file, "r") as stderr_file:
903 logging.debug("Test %d: stderr:\n%s", config['test_id'], stderr_file.read())
904 with open(test.stdout_file, "r") as stdout_file:
905 logging.debug("Test %d: stdout:\n%s", config['test_id'], stdout_file.read())
906 print("Test {0} {1}".format(config['test_id'], result))
908 print("{0} test(s) passed, {1} failed, {2} skipped".format(passed, failed, skipped))
913 if __name__ == '__main__':