-
Notifications
You must be signed in to change notification settings - Fork 52
/
ezfio.py
executable file
·1478 lines (1332 loc) · 58.6 KB
/
ezfio.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
"""ezfio 1.9
------------------------------------------------------------------------
ezfio is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
ezfio is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ezfio. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------
Usage: ./ezfio.py -d </dev/node> [-u <100..1>]
Example: ./ezfio.py -d /dev/nvme0n1 -u 100
This script requires root privileges so must be run as "root" or
via "sudo ./ezfio.py"
Please be sure to have FIO installed, or you will be prompted to install
and re-run the script."""
from __future__ import print_function
import argparse
import base64
from collections import OrderedDict
import datetime
import glob
import json
import os
import platform
import pwd
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import threading
import time
import zipfile
def AppendFile(text, filename):
"""Equivalent to >> in BASH, append a line to a text file."""
with open(filename, "a") as f:
f.write(text)
f.write("\n")
def Run(cmd):
"""Run a cmd[], return the exit code, stdout, and stderr."""
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out = proc.stdout.read()
err = proc.stderr.read()
code = proc.wait()
return int(code), out.decode('UTF-8'), err.decode('UTF-8')
def CheckAdmin():
"""Check that we have root privileges for disk access, abort if not."""
if os.geteuid() != 0:
sys.stderr.write("Root privileges are required for low-level disk ")
sys.stderr.write("access.\nPlease restart this script as root ")
sys.stderr.write("(sudo) to continue.\n")
sys.exit(1)
def FindFIO():
"""Try the path and the CWD for a FIO executable, return path or exit."""
# Determine if FIO is in path or CWD
try:
ret, out, err = Run(["fio", "-v"])
if ret == 0:
return "fio"
except:
try:
ret, out, err = Run(['./fio', '-v'])
if ret == 0:
return "./fio"
except:
sys.stderr.write("FIO is required to run IO tests.\n")
sys.stderr.write("The latest versions can be found at ")
sys.stderr.write("https://github.com/axboe/fio.\n")
sys.exit(1)
def CheckFIOVersion():
"""Check that we have a version of FIO installed that we can use."""
global fio, fioVerString, fioOutputFormat
code, out, err = Run([fio, '--version'])
try:
fioVerString = out.split('\n')[0].rstrip()
ver = out.split('\n')[0].rstrip().split('-')[1].split('.')[0]
if int(ver) < 2:
sys.stderr.write("ERROR: FIO version " + ver + " unsupported, ")
sys.stderr.write("version 2.0 or later required. Exiting.\n")
sys.exit(2)
except:
sys.stderr.write("ERROR: Unable to determine version of fio " +
"installed. Exiting.\n")
sys.exit(2)
# Now see if we can make exceedance charts
# Can't just try --output-format=json+ because the FIO in Ubuntu 16.04
# repo doesn't understand it and *silently ignores ir*. Instead, use
# the help output to see if "json+" exists at all...
try:
code, out, err = Run([fio, '--help'])
if (code == 0) and ("json+" in out):
fioOutputFormat = "json+"
except:
pass
def CheckAIOLimits():
"""Ensure kernel AIO max transactions is large enough to run test."""
global aioNeeded
# If anything fails, silently continue. FIO will give error if it
# can't run due to the AIO setting later on.
try:
code, out, err = Run(['cat', '/proc/sys/fs/aio-max-nr'])
if code == 0:
aiomaxnr = int(out.split("\n")[0].rstrip())
if aiomaxnr < int(aioNeeded):
sys.stderr.write(
"ERROR: The kernel's maximum outstanding async IO" +
"setting (aio-max-nr) is too\n")
sys.stderr.write(" low to complete the test run. Required value is " + str(
aioNeeded) + ", current is " + str(aiomaxnr) + "\n")
sys.stderr.write(
" To fix this temporarially, please execute the following command:\n")
sys.stderr.write(
" sudo sysctl -w fs.aio-max-nr=" + str(aioNeeded) + "\n")
sys.stderr.write("Unable to continue. Exiting.\n")
sys.exit(2)
except:
pass
def ParseArgs():
"""Parse command line options into globals."""
global physDrive, physDriveDict, physDriveTxt, utilization, nullio, isFile
global outputDest, offset, cluster, yes, quickie, verify, fastPrecond
global readOnly, compressPct
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="A tool to easily run FIO to benchmark sustained "
"performance of NVME\nand other types of SSD.",
epilog="""
Requirements:\n
* Root access (log in as root, or sudo {prog})
* No filesytems or data on target device
* FIO IO tester (available https://github.com/axboe/fio)
* sdparm to identify the NVME device and serial number
WARNING: All data on the target device will be DESTROYED by this test.""")
parser.add_argument("--cluster", dest="cluster", action='store_true',
help="Run the test on a cluster (--drive in "+
"host1:/dev/p1,host2:/dev/ps,...)", required=False)
parser.add_argument("--verify", dest="verify", action='store_true',
help="Have FIO perform data verifications on reads."+
" May impact performance", required=False)
parser.add_argument("--drive", "-d", dest="physDrive",
help="Device to test (ex: /dev/nvme0n1)", required=True)
parser.add_argument("--utilization", "-u", dest="utilization",
help="Amount of drive to test (in percent), 1...100",
default="100", type=int, required=False)
parser.add_argument("--offset", "-s", dest="offset",
help="offset from start (in percent), 0...99", default="0",
type=int, required=False)
parser.add_argument("--output", "-o", dest="outputDest",
help="Location where results should be saved", required=False)
parser.add_argument("--yes", dest="yes", action='store_true',
help="Skip the final warning prompt (for scripted tests)",
required=False)
parser.add_argument("--fast-precondition", dest='fastpre', action='store_true',
help="Only do a single sequential write to precondition drive",
required=False)
parser.add_argument("--quickie", dest="quickie", help=argparse.SUPPRESS,
action='store_true', required=False)
parser.add_argument("--file", dest="file", help="Test using a regular file, not a device",
action='store_true', required=False)
parser.add_argument("--nullio", dest="nullio", help=argparse.SUPPRESS,
action='store_true', required=False)
parser.add_argument("--readonly", dest="readonly", help="Only run read-only tests, don't write to device",
action='store_true', required=False)
parser.add_argument("--compress_percentage", dest="compresspct", help="Set the target data compressibility",
default="100", type=int, required=False)
args = parser.parse_args()
physDrive = args.physDrive
physDriveTxt = physDrive
utilization = args.utilization
outputDest = args.outputDest
offset = args.offset
yes = args.yes
quickie = args.quickie
nullio = args.nullio
verify = args.verify
fastPrecond = args.fastpre
cluster = args.cluster
isFile = args.file
readOnly = args.readonly
compressPct = args.compresspct
# For cluster mode, we add a new physDriveList dict and fake physDrive
if cluster:
nodes = physDrive.split(",")
for node in nodes:
physDriveDict[node.split(":")[0]] = node.split(":")[1]
physDrive = nodes[0].split(":")[1]
if (utilization < 1) or (utilization > 100):
print("ERROR: Utilization must be between 1...100")
parser.print_help()
sys.exit(1)
if (offset < 0) or (offset > 99) or (offset+utilization > 100):
print("ERROR: offset must be between 0...99 while offset + utilization <= 100")
parser.print_help()
sys.exit(1)
# Sanity check that the selected drive is not mounted by parsing mounts
# This is not guaranteed to catch all as there's just too many different
# naming conventions out there. Let's cover simple HDD/SSD/NVME patterns
pdispart = (re.match('.*p?[1-9][0-9]*$', physDrive) and
not re.match('.*/nvme[0-9]+n[1-9][0-9]*$', physDrive))
hit = ""
with open("/proc/mounts", "r") as f:
mounts = f.readlines()
for l in mounts:
dev = l.split()[0]
mnt = l.split()[1]
if dev == physDrive:
hit = dev + " on " + mnt # Obvious exact match
if pdispart:
chkdev = dev
else:
# /dev/sdp# is special case, don't remove the "p"
if re.match('^/dev/sdp.*$', dev):
chkdev = re.sub('[1-9][0-9]*$', '', dev)
else:
# Need to see if mounted partition is on a raw device being tested
chkdev = re.sub('p?[1-9][0-9]*$', '', dev)
if chkdev == physDrive:
hit = dev + " on " + mnt
if hit != "":
print("ERROR: Mounted volume '" + str(hit) + "' is on same device" +
"as tested device '" + str(physDrive) + "'. ABORTING.")
sys.exit(2)
def grep(inlist, regex):
"""Implement grep in a non-Pythonic way to make it comprehensible to humans"""
out = []
for i in inlist:
if re.search(regex, i):
out = out + [i]
return out
def CollectSystemInfo():
"""Collect some OS and CPU information."""
global cpu, cpuCores, cpuFreqMHz, uname
uname = " ".join(platform.uname())
code, cpuinfo, err = Run(['cat', '/proc/cpuinfo'])
cpuinfo = cpuinfo.split("\n")
if 'aarch64' in uname:
code, cpuinfo, err = Run(['lscpu'])
cpuinfo = cpuinfo.split("\n")
cpu = grep(cpuinfo, r'Model name')[0].split(':')[1].lstrip()
cpuCores = grep(cpuinfo, r'CPU')[1].split(':')[1].lstrip()
try:
code, dmidecode, err = Run(['dmidecode', '--type', 'processor'])
cpuFreqMHz = int(round(float(grep(dmidecode.split("\n"), r'Current Speed')[0].rstrip().lstrip().split(" ")[2])))
except:
cpuFreqMHz = grep(cpuinfo, r'max')[0].split(':')[1].lstrip()
elif 'ppc64' in uname:
# Implement grep and sed in Python...
cpu = grep(cpuinfo, r'model')[0].split(': ')[1].replace('(R)', '').replace('(TM)', '')
cpuCores = len(grep(cpuinfo, r'processor'))
try:
code, dmidecode, err = Run(['dmidecode', '--type', 'processor'])
cpuFreqMHz = int(round(float(grep(dmidecode.split("\n"), r'Current Speed')[0].rstrip().lstrip().split(" ")[2])))
except:
cpuFreqMHz = int(round(float(grep(cpuinfo, r'clock')[0].split(': ')[1][:-3])))
else:
model_names = grep(cpuinfo, r'model name')
cpu = model_names[0].split(': ')[1].replace('(R)', '').replace('(TM)', '')
cpuCores = len(model_names)
try:
code, dmidecode, err = Run(['dmidecode', '--type', 'processor'])
cpuFreqMHz = int(round(float(grep(dmidecode.split("\n"), r'Current Speed')[0].rstrip().lstrip().split(" ")[2])))
except:
cpuFreqMHz = int(round(float(grep(cpuinfo, r'cpu MHz')[0].split(': ')[1])))
def VerifyContinue():
"""User's last chance to abort the test. Exit if they don't agree."""
if not yes:
print("-" * 75)
print("WARNING! " * 9)
print("THIS TEST WILL DESTROY ANY DATA AND FILESYSTEMS ON " + physDrive)
cont = input("Please type the word \"yes\" and hit return to " +
"continue, or anything else to abort.")
print("-" * 75 + "\n")
if cont != "yes":
print("Performance test aborted, drive is untouched.")
sys.exit(1)
def CollectDriveInfo():
"""Get important device information, exit if not possible."""
global physDriveGiB, physDriveGB, physDriveBase, testcapacity, testoffset
global model, serial, physDrive, isFile
# We absolutely need this information
pd = physDrive.split(',')[0]
try:
if isFile:
physDriveBase = os.path.basename(pd)
physDriveBytes = str(os.stat(pd).st_size) + "\n"
else:
physDriveBase = os.path.basename(pd)
code, physDriveBytes, err = Run(['blockdev', '--getsize64', pd])
if code != 0:
raise Exception("Can't get drive size for " + pd)
physDriveBytes = physDriveBytes.split('\n')[0]
physDriveBytes = int(physDriveBytes)
physDriveGB = int(physDriveBytes / (1000 * 1000 * 1000))
physDriveGiB = int(physDriveBytes / (1024 * 1024 * 1024))
testcapacity = int((physDriveGiB * utilization) / 100)
testoffset = int((physDriveGiB * offset) / 100)
except:
print("ERROR: Can't get '" + pd + "' size. Incorrect device name?")
sys.exit(1)
# These are nice to have, but we can run without it
model = "UNKNOWN"
serial = "UNKNOWN"
try:
nvmeclicmd = ['nvme', 'list', '--output-format=json']
code, nvmecli, err = Run(nvmeclicmd)
if code == 0:
j = json.loads(nvmecli)
for drive in j['Devices']:
if drive['DevicePath'] == pd:
model = drive['ModelNumber']
serial = drive['SerialNumber']
return
except:
pass # An error in nvme is not a problem
try:
sdparmcmd = ['sdparm', '--page', 'sn', '--inquiry', '--long', pd]
code, sdparm, err = Run(sdparmcmd)
lines = sdparm.split("\n")
if len(lines) == 4:
model = re.sub(
r'\s+', " ", lines[0].split(":")[1].lstrip().rstrip())
serial = re.sub(r'\s+', " ", lines[2].lstrip().rstrip())
else:
print("Unable to identify drive using sdparm. Continuing.")
except:
print("Install sdparm to allow model/serial extraction. Continuing.")
def CSVInfoHeader(f):
"""Headers to the CSV file (ending up in the ODS at the test end)."""
global physDriveTxt, model, serial, physDriveGiB, testcapacity, testoffset
global cpu, cpuCores, cpuFreqMHz, uname, quickie, fastPrecond
if quickie:
prefix = "QUICKIE-INVALID-RESULTS-"
else:
prefix = ""
if fastPrecond:
prefix = "FASTPRECOND-" + prefix
AppendFile("Drive," + prefix + str(physDriveTxt).replace(",", " "), f)
AppendFile("Model," + prefix + str(model), f)
AppendFile("Serial," + prefix + str(serial), f)
AppendFile("AvailCapacity," + prefix + str(physDriveGiB) + ",GiB", f)
if offset == 0:
testcap = str(testcapacity)
else:
testcap = str(testcapacity) + " @ " + str(testoffset)
AppendFile("TestedCapacity," + prefix + str(testcap) + ",GiB", f)
AppendFile("CPU," + prefix + str(cpu), f)
AppendFile("Cores," + prefix + str(cpuCores), f)
AppendFile("Frequency," + prefix + str(cpuFreqMHz), f)
AppendFile("OS," + prefix + str(uname), f)
AppendFile("FIOVersion," + prefix + str(fioVerString), f)
def SetupFiles():
"""Set up names for all output/input files, place headers on CSVs."""
global ds, details, testcsv, timeseriescsv, odssrc, odsdest
global physDriveBase, fioVerString, outputDest, timeseriesclatcsv
global timeseriesslatcsv
# Datestamp for run output files
ds = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
# The unique suffix we generate for all output files
suffix = str(physDriveGB) + "GB_" + str(cpuCores) + "cores_"
suffix += str(cpuFreqMHz) + "MHz_" + physDriveBase + "_"
suffix += socket.gethostname() + "_" + ds
if not outputDest:
outputDest = os.getcwd()
# The "details" directory contains the raw output of each FIO run
details = outputDest + "/details_" + suffix
if os.path.exists(details):
shutil.rmtree(details)
os.makedirs(details)
# Copy this script into it for posterity
shutil.copyfile(__file__, details + "/" + os.path.basename(__file__))
# Files we're going to generate, encode some system info in the names
# If the output files already exist, erase them
testcsv = details + "/ezfio_tests_"+suffix+".csv"
if os.path.exists(testcsv):
os.unlink(testcsv)
CSVInfoHeader(testcsv)
AppendFile("Type,Write %,Block Size,Threads,Queue Depth/Thread,IOPS," +
"Bandwidth (MB/s),Read Latency (us),Write Latency (us)," +
"System CPU,User CPU", testcsv)
timeseriescsv = details + "/ezfio_timeseries_"+suffix+".csv"
timeseriesclatcsv = details + "/ezfio_timeseriesclat_"+suffix+".csv"
timeseriesslatcsv = details + "/ezfio_timeseriesslat_"+suffix+".csv"
for f in [timeseriescsv, timeseriesclatcsv, timeseriesslatcsv]:
if os.path.exists(f):
os.unlink(f)
CSVInfoHeader(f)
AppendFile(",".join(["IOPS"] + list(physDriveDict.keys())),
timeseriescsv) # Add IOPS header
hdr = ""
for host in physDriveDict.keys():
hdr = hdr + ',' + host + "-read"
hdr = hdr + ',' + host + "-write"
AppendFile('CLAT-read,CLAT-write' + hdr,
timeseriesclatcsv) # Add IOPS header
AppendFile('SLAT-read,SLAT-write' + hdr,
timeseriesslatcsv) # Add IOPS header
# ODS input and output files
odssrc = os.path.dirname(os.path.realpath(__file__)) + "/original.ods"
if not os.path.exists(odssrc):
print("ERROR: Can't find original ODS spreadsheet '" + odssrc + "'.")
sys.exit(1)
odsdest = outputDest + "/ezfio_results_"+suffix+".ods"
if os.path.exists(odsdest):
os.unlink(odsdest)
class FIOError(Exception):
"""Exception generated when FIO returns a non-success value
Attributes:
cmdline -- The FIO command that was executed
code -- Error code FIO returned
stderr -- STDERR output from FIO
stdout -- STDOUT output from FIO
"""
def __init__(self, cmdline, code, stderr, stdout):
super(FIOError, self).__init__()
self.cmdline = cmdline
self.code = code
self.stderr = stderr
self.stdout = stdout
def TestName(seqrand, wmix, bs, threads, iodepth):
"""Return full path and filename prefix for test of specified params"""
global details, physDriveBase
testfile = str(details) + "/Test" + str(seqrand) + "_w" + str(wmix)
testfile += "_bs" + str(bs) + "_threads" + str(threads) + "_iodepth"
testfile += str(iodepth) + "_" + str(physDriveBase) + ".out"
return testfile
def SequentialConditioning():
"""Sequentially fill the complete capacity of the drive once."""
global quickie, fastPrecond, nullio, readOnly, compressPct
def GenerateJobfile(drive, testcapacity, testoffset):
"""Write the sequential jobfile for a single server"""
jobfile = tempfile.NamedTemporaryFile(delete=False, mode='w')
for dr in drive.split(','):
jobfile.write("[SeqCond-" + dr + "]\n")
# Note that we can't use regular test runner because this test needs
# to run for a specified # of bytes, not a specified # of seconds.
jobfile.write("readwrite=write\n")
jobfile.write("bs=128k\n")
if nullio:
jobfile.write("ioengine=null\n")
else:
jobfile.write("ioengine=libaio\n")
jobfile.write("iodepth=64\n")
jobfile.write("direct=1\n")
jobfile.write("filename=" + str(dr) + "\n")
if quickie:
jobfile.write("size=1G\n")
else:
jobfile.write("size=" + str(testcapacity) + "G\n")
jobfile.write("thread=1\n")
jobfile.write("offset=" + str(testoffset) + "G\n")
if compressPct != 100:
jobfile.write("buffer_compress_percentage=" + str(compressPct) + "\n")
jobfile.close()
return jobfile
cmdline = [fio]
if not cluster:
jobfile = GenerateJobfile(physDrive, testcapacity, testoffset)
cmdline = cmdline + [jobfile.name]
else:
jobfile = []
for host in physDriveDict.keys():
newjob = GenerateJobfile(
physDriveDict[host], testcapacity, testoffset)
cmdline = cmdline + ['--client=' + str(host), str(newjob.name)]
jobfile = jobfile + [newjob]
cmdline = cmdline + ['--output-format=' + str(fioOutputFormat)]
if not readOnly:
code, out, err = Run(cmdline)
else:
code = 0
if cluster:
for job in jobfile:
os.unlink(job.name)
else:
os.unlink(jobfile.name)
if code != 0:
raise FIOError(" ".join(cmdline), code, err, out)
else:
return "DONE", "DONE", "DONE"
def RandomConditioning():
"""Randomly write entire device for the full capacity"""
global quickie, nullio, readOnly, compressPct
def GenerateJobfile(drive, testcapacity, testoffset):
"""Write the random jobfile"""
jobfile = tempfile.NamedTemporaryFile(delete=False, mode='w')
for dr in drive.split(','):
jobfile.write("[RandCond-" + dr + "]\n")
# Note that we can't use regular test runner because this test needs
# to run for a specified # of bytes, not a specified # of seconds.
jobfile.write("readwrite=randwrite\n")
jobfile.write("bs=4k\n")
jobfile.write("invalidate=1\n")
jobfile.write("end_fsync=0\n")
jobfile.write("group_reporting=1\n")
jobfile.write("direct=1\n")
jobfile.write("filename=" + str(dr) + "\n")
if quickie:
jobfile.write("size=1G\n")
else:
jobfile.write("size=" + str(testcapacity) + "G\n")
if nullio:
jobfile.write("ioengine=null\n")
else:
jobfile.write("ioengine=libaio\n")
jobfile.write("iodepth=256\n")
jobfile.write("norandommap\n")
jobfile.write("randrepeat=0\n")
jobfile.write("thread=1\n")
jobfile.write("offset=" + str(testoffset) + "G\n")
if compressPct != 100:
jobfile.write("buffer_compress_percentage=" + str(compressPct) + "\n")
jobfile.close()
return jobfile
cmdline = [fio]
if not cluster:
jobfile = GenerateJobfile(physDrive, testcapacity, testoffset)
cmdline = cmdline + [jobfile.name]
else:
jobfile = []
for host in physDriveDict.keys():
newjob = GenerateJobfile(
physDriveDict[host], testcapacity, testoffset)
cmdline = cmdline + ['--client=' + str(host), str(newjob.name)]
jobfile = jobfile + [newjob]
cmdline = cmdline + ['--output-format=' + str(fioOutputFormat)]
if not readOnly:
code, out, err = Run(cmdline)
else:
code = 0
if cluster:
for job in jobfile:
os.unlink(job.name)
else:
os.unlink(jobfile.name)
if code != 0:
raise FIOError(" ".join(cmdline), code, err, out)
else:
return "DONE", "DONE", "DONE"
def RunTest(iops_log, seqrand, wmix, bs, threads, iodepth, runtime):
"""Runs the specified test, generates output CSV lines."""
global cluster, physDriveDict, compressPct
# Taken from fio_latency2csv.py - needed to convert funky semi-log to normal latencies
def plat_idx_to_val(idx, FIO_IO_U_PLAT_BITS=6, FIO_IO_U_PLAT_VAL=64):
"""Convert from lat bucket to real value, for obsolete FIO revisions"""
# MSB <= (FIO_IO_U_PLAT_BITS-1), cannot be rounded off. Use
# all bits of the sample as index
if idx < (FIO_IO_U_PLAT_VAL << 1):
return idx
# Find the group and compute the minimum value of that group
error_bits = (idx >> FIO_IO_U_PLAT_BITS) - 1
base = 1 << (error_bits + FIO_IO_U_PLAT_BITS)
# Find its bucket number of the group
k = idx % FIO_IO_U_PLAT_VAL
# Return the mean of the range of the bucket
return base + ((k + 0.5) * (1 << error_bits))
def WriteExceedance(j, rdwr, outfile):
"""Generate an exceedance CSV for read or write from JSON output."""
global fioOutputFormat
if fioOutputFormat == "json":
return # This data not present in JSON format, only JSON+
# Generate a dict of combined bins, either for jobs[0] or client_stats[]
bins = {}
ios = 0
try:
# Non-cluster case will have jobs, only a single one needed
ios = j['jobs'][0][rdwr]['total_ios']
if ('N' in j['jobs'][0][rdwr]['clat_ns']) and (j['jobs'][0][rdwr]['clat_ns']['N'] > 0):
bins = j['jobs'][0][rdwr]['clat_ns']['bins']
else:
bins = {}
except:
# Cluster case will have client_stats to combine
for client_stats in j['client_stats']:
if client_stats['jobname'] == 'All clients':
# Don't bother looking at combined, bins doesn't exist there
continue
if client_stats[rdwr]['total_ios']:
ios = ios + client_stats[rdwr]['total_ios']
for k in client_stats[rdwr]['clat_ns']['bins'].keys():
try:
bins[k] = bins[k] + client_stats[rdwr]['clat_ns']['bins'][k]
except:
bins[k] = client_stats[rdwr]['clat_ns']['bins'][k]
#ios = client[rdwr]['total_ios']
#bins = client[rdwr]['clat_ns']['bins']
if ios:
runttl = 0
# This was changed in 2.99 to be in nanoseconds and to discard the crazy _bits magic
if float(fioVerString.split('-')[1]) >= 2.99:
lat_ns = []
# JSON dict has keys of type string, need a sorted integer list for our work...
for entry in bins:
lat_ns.append(int(entry))
for entry in sorted(lat_ns):
lat_us = float(entry) / 1000.0
cnt = int(bins[str(entry)])
runttl += cnt
pctile = 1.0 - float(runttl) / float(ios)
if cnt > 0:
AppendFile(
",".join((str(lat_us), str(pctile))), outfile)
else:
plat_bits = client[rdwr]['clat']['bins']['FIO_IO_U_PLAT_BITS']
plat_val = client[rdwr]['clat']['bins']['FIO_IO_U_PLAT_VAL']
for b in range(0, int(client[rdwr]['clat']['bins']['FIO_IO_U_PLAT_NR'])):
cnt = int(client[rdwr]['clat']['bins'][str(b)])
runttl += cnt
pctile = 1.0 - float(runttl) / float(ios)
if cnt > 0:
AppendFile(
",".join((str(plat_idx_to_val(b, plat_bits, plat_val)),
str(pctile))), outfile)
def GenerateJobfile(rw, wmix, bs, drive, testcapacity, runtime, threads, iodepth, testoffset):
"""Make a jobfile for the specified test parameters"""
global verify, nullio
jobfile = tempfile.NamedTemporaryFile(delete=False, mode='w')
for dr in drive.split(","):
jobfile.write("[test-" + dr + "]\n")
jobfile.write("readwrite=" + str(rw) + "\n")
jobfile.write("rwmixwrite=" + str(wmix) + "\n")
jobfile.write("bs=" + str(bs) + "\n")
jobfile.write("invalidate=1\n")
jobfile.write("end_fsync=0\n")
jobfile.write("group_reporting=1\n")
jobfile.write("direct=1\n")
jobfile.write("filename=" + str(dr) + "\n")
jobfile.write("size=" + str(testcapacity) + "G\n")
jobfile.write("time_based=1\n")
jobfile.write("runtime=" + str(runtime) + "\n")
if nullio:
jobfile.write("ioengine=null\n")
else:
jobfile.write("ioengine=libaio\n")
jobfile.write("numjobs=" + str(threads) + "\n")
jobfile.write("iodepth=" + str(iodepth) + "\n")
jobfile.write("norandommap=1\n")
jobfile.write("randrepeat=0\n")
jobfile.write("thread=1\n")
jobfile.write("exitall=1\n")
if verify:
jobfile.write("verify=crc32c\n")
jobfile.write("random_generator=lfsr\n")
jobfile.write("offset=" + str(testoffset) + "G\n")
if compressPct != 100:
jobfile.write("buffer_compress_percentage=" + str(compressPct) + "\n")
jobfile.close()
return jobfile
def CombineThreadOutputs(suffix, outcsv, lat):
"""Merge all FIO iops/lat logs across all servers"""
# The lists may be called "iops" but the same works for clat/slat
iops = [0] * (runtime + extra_runtime)
# For latencies, need to keep the _w and _r separate
iops_w = [0] * (runtime + extra_runtime)
host_iops = OrderedDict()
host_iops_w = OrderedDict()
filecnt = 0
if not cluster:
pdd = OrderedDict()
pdd['localhost'] = 1 # Just the single host, faked here
else:
pdd = physDriveDict
for host in pdd.keys():
host_iops[host] = [0] * (runtime + extra_runtime)
host_iops_w[host] = [0] * (runtime + extra_runtime)
if not cluster:
fileglob = testfile + str(suffix) + '.*log'
else:
fileglob = testfile + str(suffix) + '.*.log.' + host
for filename in glob.glob(fileglob):
filecnt = filecnt + 1
catcmdline = ['cat', filename]
catcode, catout, caterr = Run(catcmdline)
if catcode != 0:
AppendFile("ERROR", testcsv)
raise FIOError(" ".join(catcmdline),
catcode, caterr, catout)
lines = catout.split("\n")
# Set time 0 IOPS to first values
riops = 0
wiops = 0
nexttime = 0
for x in range(0, runtime + extra_runtime):
if not lat:
iops[x] = iops[x] + riops + wiops
host_iops[host][x] = host_iops[host][x] + riops + wiops
else:
iops[x] = iops[x] + riops
iops_w[x] = iops_w[x] + wiops
host_iops[host][x] = host_iops[host][x] + riops
host_iops_w[host][x] = host_iops_w[host][x] + wiops
while len(lines) > 1 and (nexttime < x):
parts = lines[0].split(",")
nexttime = float(parts[0]) / 1000.0
if int(lines[0].split(",")[2]) == 1:
wiops = int(parts[1])
else:
riops = int(parts[1])
lines = lines[1:]
# Generate the combined CSV
with open(outcsv, 'a') as f:
for cnt in range(int(extra_runtime/2), runtime + extra_runtime):
if filecnt > 0 and lat:
line = str(float(iops[cnt])/float(filecnt))
line = line + ',' + str(float(iops_w[cnt])/float(filecnt))
else:
line = str(iops[cnt])
if len(pdd.keys()) > 1:
for host in pdd.keys():
if filecnt > 0 and lat:
line = line + ',' + \
str(float(host_iops[host][cnt])/float(filecnt))
line = line + ',' + \
str(float(host_iops_w[host]
[cnt])/float(filecnt))
else:
line = line + "," + str(host_iops[host][cnt])
f.write(line + "\n")
# Output file names
testfile = TestName(seqrand, wmix, bs, threads, iodepth)
if seqrand == "Seq":
rw = "rw"
else:
rw = "randrw"
if iops_log:
extra_runtime = 10
else:
extra_runtime = 0
cmdline = [fio]
if not cluster:
jobfile = GenerateJobfile(rw, wmix, bs, physDrive, testcapacity,
runtime + extra_runtime, threads, iodepth, testoffset)
cmdline = cmdline + [jobfile.name]
AppendFile("[JOBFILE]", testfile)
with open(jobfile.name, 'r') as of:
txt = of.read()
AppendFile(txt, testfile)
if iops_log:
AppendFile("write_iops_log=" + testfile, jobfile.name)
AppendFile("write_lat_log=" + testfile, jobfile.name)
AppendFile("log_avg_msec=1000", jobfile.name)
AppendFile("log_unix_epoch=0", jobfile.name)
else:
jobfile = []
for host in physDriveDict.keys():
newjob = GenerateJobfile(rw, wmix, bs, physDriveDict[host], testcapacity,
runtime + extra_runtime, threads, iodepth, testoffset)
cmdline = cmdline + ['--client=' + str(host), str(newjob.name)]
AppendFile('[JOBFILE-' + str(host) + "]", testfile)
with open(newjob.name, 'r') as of:
txt = of.read()
AppendFile(txt, testfile)
jobfile = jobfile + [newjob]
if iops_log:
AppendFile("write_iops_log=" + testfile, newjob.name)
AppendFile("write_lat_log=" + testfile, newjob.name)
AppendFile("log_avg_msec=1000", newjob.name)
AppendFile("log_unix_epoch=0", newjob.name)
cmdline = cmdline + ['--output-format=' + str(fioOutputFormat)]
# There are some NVME drives with 4k physical and logical out there.
# Check that we can actually do this size IO, OTW return 0 for all
skiptest = False
code, out, err = Run(['blockdev', '--getpbsz', str(physDrive.split(',')[0])])
if code == 0:
iomin = int(out.split("\n")[0])
if int(bs) < iomin:
skiptest = True
if readOnly and wmix != 0:
skiptest = True
# Silently ignore failure to return min block size, FIO will fail and
# we'll catch that a little later.
if skiptest:
code = 0
out = "Test not run because block size " + str(bs)
out += " below iominsize " + str(iomin) + "\n"
out += "3;" + "0;" * 100 + "\n" # Bogus 0-filled resulte line
err = ""
else:
code, out, err = Run(cmdline)
AppendFile("[STDOUT]", testfile)
AppendFile(out, testfile)
AppendFile("[STDERR]", testfile)
AppendFile(err, testfile)
if cluster:
for job in jobfile:
os.unlink(job.name)
else:
os.unlink(jobfile.name)
# Make sure we had successful completion, else note and abort run
if code != 0:
AppendFile("ERROR", testcsv)
raise FIOError(" ".join(cmdline), code, err, out)
if iops_log:
CombineThreadOutputs('_iops', timeseriescsv, False)
CombineThreadOutputs('_clat', timeseriesclatcsv, True)
CombineThreadOutputs('_slat', timeseriesslatcsv, True)
rdiops = 0
wriops = 0
rlat = 0
wlat = 0
syscpu = 0
usrcpu = 0
if not skiptest:
# Chomp anything before the json.
for i in range(0, len(out)):
if out[i] == '{':
out = out[i:]
break
j = json.loads(out)
if cluster and len(physDriveDict.keys()) == 1:
client = j['client_stats'][0]
elif cluster:
for res in j['client_stats']:
if res['jobname'] == "All clients":
client = res
break
else:
client = j['jobs'][0]
syscpu = float(client['sys_cpu'])
usrcpu = float(client['usr_cpu'])
rdiops = float(client['read']['iops'])
wriops = float(client['write']['iops'])
# 'lat' goes to 'lat_ns' in newest FIO JSON formats...ugh
try:
rlat = float(client['read']['lat_ns']['mean']) / 1000 # ns->us
except:
rlat = float(client['read']['lat']['mean'])
try:
wlat = float(client['write']['lat_ns']['mean']) / 1000 # ns->us
except:
wlat = float(client['write']['lat']['mean'])
iops = "{0:0.0f}".format(rdiops + wriops)
mbps = "{0:0.2f}".format((float((rdiops+wriops) * bs) /
(1024.0 * 1024.0)))
lat = "{0:0.1f}".format(max(rlat, wlat))
AppendFile(",".join((str(seqrand), str(wmix), str(bs), str(threads),
str(iodepth), str(iops), str(mbps), str(rlat),
str(wlat), str(syscpu), str(usrcpu))), testcsv)
if skiptest:
AppendFile("1,1\n", testfile + ".exc.read.csv")
AppendFile("1,1\n", testfile + ".exc.write.csv")
else:
WriteExceedance(j, 'read', testfile + ".exc.read.csv")
WriteExceedance(j, 'write', testfile + ".exc.write.csv")
return iops, mbps, lat
def DefineTests():
"""Generate the work list for the main worker into OC."""
global oc, quickie, fastPrecond
# What we're shmoo-ing across
bslist = (512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072)
qdlist = (1, 2, 4, 8, 16, 32, 64, 128, 256)
threadslist = (1, 2, 4, 8, 16, 32, 64, 128, 256)
shorttime = 120 # Runtime of point tests
longtime = 1200 # Runtime of long-running tests
if quickie:
shorttime = int(shorttime / 10)
longtime = int(longtime / 10)
def AddTest(name, seqrand, writepct, blocksize, threads, qdperthread,
iops_log, runtime, desc, cmdline):
"""Bare usage add a test to the list to execute"""
if threads != "":
qd = int(threads) * int(qdperthread)
else:
qd = 0
dat = {}
dat['name'] = name
dat['seqrand'] = seqrand
dat['wmix'] = writepct
dat['bs'] = blocksize
dat['qd'] = qd
dat['qdperthread'] = qdperthread
dat['threads'] = threads
dat['bw'] = ''
dat['iops'] = ''
dat['lat'] = ''
dat['desc'] = desc
dat['iops_log'] = iops_log
dat['runtime'] = runtime
dat['cmdline'] = cmdline
oc.append(dat)
def DoAddTest(testname, seqrand, wmix, bs, threads, iodepth, desc,
iops_log, runtime):
"""Add an individual run to the list of tests to execute"""
AddTest(testname, seqrand, wmix, bs, threads, iodepth, iops_log,
runtime, desc, lambda o: {RunTest(o['iops_log'],
o['seqrand'], o['wmix'],
o['bs'], o['threads'],
o['qdperthread'],
o['runtime'])})
def AddTestBSShmoo():
"""Add a sequence of tests varying the block size"""
AddTest(testname, 'Preparation', '', '', '', '', '', '', '',
lambda o: {AppendFile(o['name'], testcsv)})
for bs in bslist:
desc = testname + ", BS=" + str(bs)