-
Notifications
You must be signed in to change notification settings - Fork 0
/
iobs.py
1663 lines (1247 loc) · 53.4 KB
/
iobs.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
# Linux I/O Benchmark for Schedulers
# Copyright (c) 2018, UofL Computer Systems Lab.
#
# This program 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 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without event 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 this program. If not, see <http://www.gnu.org/licenses/>.
__author__ = 'Jared Gillespie, Martin Heil'
__version__ = '0.3.1'
from collections import defaultdict
from functools import wraps
from getopt import getopt, GetoptError
from time import strftime, localtime
import configparser
import json
import logging
import os
import platform
import multiprocessing
import re
import stat
import shlex
import signal
import subprocess
import sys
import time
# region termination
def sig_handler(signal, frame):
if Mem.current_processes:
kill_processes(Mem.current_processes)
Mem.current_processes.clear()
sys.exit(0)
# endregion
# region utils
def adjusted_workload(command: str, workload: str):
"""Adjusts a command by adding extra flags, etc.
:param command: The command.
:param workload: The workload.
:return: The adjusted workload command.
"""
if workload == 'fio':
return '%s %s' % (command, '--output-format=json')
return command
def ignore_exception(exception=Exception, default_val=None, should_log=True):
"""A decorator function that ignores the exception raised, and instead returns a default value.
:param exception: The exception to catch.
:param default_val: The default value.
:param should_log: Whether the exception should be logged.
:return: The decorated function.
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exception as e:
log(str(e))
return default_val
return wrapper
return decorator
def log_around(before_message: str=None, after_message: str=None, exception_message: str=None, ret_validity: bool=False):
"""Logs messages around a function.
:param before_message: The message to log before.
:param after_message: The message to log after.
:param exception_message: The message to log when an exception occurs.
:param ret_validity: If true, if the function returns False or None, the exception message is printed.
:return: The decorated function.
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if before_message:
log(before_message)
try:
out = func(*args, **kwargs)
if ret_validity:
if out is False or out is None:
if exception_message:
log(exception_message)
return out
elif after_message:
log(after_message)
elif after_message:
log(after_message)
return out
except Exception as e:
log(e)
if exception_message:
log(exception_message)
raise
return wrapper
return decorator
def log(*args, **kwargs):
"""Logs a message if logging is enabled.
:param args: The arguments.
:param kwargs: The keyword arguments.
"""
if Mem.log:
if args:
args_rem = [a.strip() if isinstance(a, str) else a for a in args][1:]
message = args[0]
for line in str(message).split('\n'):
logging.debug(line, *args_rem, **kwargs)
else:
logging.debug(*args, **kwargs)
def print_and_log(*args, **kwargs):
"""Prints a message, and logs if logging is enabled.
:param args: The arguments.
:param kwargs: The keyword arguments.
"""
log(*args, **kwargs)
args = [a.strip() if isinstance(a, str) else a for a in args]
print(*args, **kwargs)
def print_detailed(*args, **kwargs):
"""Prints a message if verbose is enabled, and logs if logging is enabled.
:param args: The arguments.
:param kwargs: The keyword arguments.
"""
log(*args, **kwargs)
print_verbose(*args, **kwargs)
def print_verbose(*args, **kwargs):
"""Prints a message if verbose is enabled.
:param args: The arguments.
:param kwargs: The keyword arguments.
"""
if Mem.verbose:
args = [a.strip() if isinstance(a, str) else a for a in args]
print(*args, **kwargs)
def try_split(s: str, delimiter) -> list:
"""Tries to split a string by the given delimiter(s).
:param s: The string to split.
:param delimiter: Either a single string, or a tuple of strings (i.e. (',', ';').
:return: Returns the string split into a list.
"""
if isinstance(delimiter, tuple):
for d in delimiter:
if d in s:
return [i.strip() for i in s.split(d)]
elif delimiter in s:
return s.split(delimiter)
return [s]
# endregion
# region classes
class Mem:
"""A simple data-store for persisting and keeping track of global data."""
def __init__(self):
# Constants
self.GLOBAL_HEADER = 'global'
# Settings
self.cleanup = False
self.config_file = None
self.continue_on_failure = False
self.jobs = []
self.log = False
self.output_file = None
self.retry = 1
self.verbose = False
# Global Job Settings
self._command = None
self._delay = 0
self._device = None
self._repetition = 1
self._runtime = None
self._schedulers = None
self._workload = None
# Formatters
self.format_blktrace = 'blktrace -d %s -o %s -w %s -b 16384 -n 8' # device, file prefix, runtime
self.format_blkparse = "blkparse -i %s -d %s.blkparse.bin -q -O -M" # file prefix, file prefix
self.format_btt = 'btt -i %s.blkparse.bin' # file prefix
self.format_blkrawverify = 'blkrawverify %s' # file prefix
# Regex
self.re_blkparse_throughput_read = re.compile(r'Throughput \(R/W\): (\d+)[a-zA-Z]+/s')
self.re_blkparse_throughput_write = re.compile(r'Throughput \(R/W\): (?:\d+)[a-zA-Z]+/s / (\d+)[a-zA-z]+/s')
self.re_btt_d2c = re.compile(r'D2C\s*(?:\d+.\d+)\s*(\d+.\d+)\s*(?:\d+.\d+)\s*(?:\d+)')
self.re_btt_q2c = re.compile(r'Q2C\s*(?:\d+.\d+)\s*(\d+.\d+)\s*(?:\d+.\d+)\s*(?:\d+)')
self.re_device = re.compile(r'/dev/(.*)')
# Validity
self.valid_global_settings = {'command', 'delay', 'device', 'schedulers', 'repetition', 'runtime', 'workload'}
self.valid_job_settings = {'command', 'delay', 'device', 'schedulers', 'repetition', 'runtime', 'workload'}
self.valid_workloads = {'fio'}
# Other
self.current_processes = set() # Keep track of current processes for killing purposes
self.output_column_order = ['device',
'io-depth',
'workload',
'scheduler',
'slat-read', 'slat-write',
'clat-read', 'clat-write',
'lat-read', 'lat-write',
'q2c',
'd2c',
'fslat-read', 'fslat-write',
'bslat',
'iops-read', 'iops-write',
'throughput-read', 'throughput-write',
'io-kbytes',
'start-time', 'stop-time']
@property
def command(self) -> str:
return self._command
@command.setter
def command(self, value: str):
self._command = value
@property
def delay(self) -> int:
return self._delay
@delay.setter
def delay(self, value: int):
conv_value = ignore_exception(ValueError, -1)(int)(value)
if conv_value < 1:
raise ValueError('Delay given is < 0: %s' % value)
self._delay = conv_value
@property
def device(self) -> str:
return self._device
@device.setter
def device(self, value: str):
self._device = value
@property
def repetition(self) -> int:
return self._repetition
@repetition.setter
def repetition(self, value: int):
conv_value = ignore_exception(ValueError, 0)(int)(value)
if conv_value < 1:
raise ValueError('Repetition given is < 1: %s' % value)
self._repetition = conv_value
@property
def runtime(self):
return self._runtime
@runtime.setter
def runtime(self, value: int):
conv_value = ignore_exception(ValueError, 0)(int)(value)
if conv_value < 1:
raise ValueError('Runtime given is < 1: %s' % value)
self._runtime = conv_value
@property
def schedulers(self) -> set:
return self._schedulers
@schedulers.setter
def schedulers(self, value):
self._schedulers = set(try_split(value, ','))
@property
def workload(self) -> str:
return self._workload
@workload.setter
def workload(self, value: str):
self._workload = value
@log_around('Processing jobs', 'Processed jobs successfully', 'Failed to process all jobs', True)
def process_jobs(self) -> bool:
"""Executes each job.
:return: Returns True if successful, else False.
"""
for job in self.jobs:
if not job.execute():
if not self.continue_on_failure:
return False
return True
# Turns the class into a singleton (this is some sneaky stuff)
Mem = Mem()
class Job:
"""A single job, which is representative of a single workload to be run."""
def __init__(self, name: str):
self._name = name
self._command = None
self._delay = None
self._device = None
self._repetition = None
self._runtime = None
self._schedulers = None
self._workload = None
@property
def name(self) -> str:
return self._name
@property
def command(self) -> str:
return self._command
@command.setter
def command(self, value: str):
self._command = value
@property
def delay(self) -> int:
return self._delay
@delay.setter
def delay(self, value: int):
conv_value = ignore_exception(ValueError, -1)(int)(value)
if conv_value < 1:
raise ValueError('Delay given is < 0: %s' % value)
self._delay = conv_value
@property
def device(self) -> str:
return self._device
@device.setter
def device(self, value):
self._device = value
@property
def repetition(self) -> int:
return self._repetition
@repetition.setter
def repetition(self, value: int):
conv_value = ignore_exception(ValueError, 0)(int)(value)
if conv_value < 1:
raise ValueError('Repetition given is < 1: %s' % value)
self._repetition = conv_value
@property
def runtime(self) -> int:
return self._runtime
@runtime.setter
def runtime(self, value: int):
conv_value = ignore_exception(ValueError, 0)(int)(value)
if conv_value < 1:
raise ValueError('Runtime given is < 1: %s' % value)
self._runtime = conv_value
@property
def schedulers(self) -> set:
return self._schedulers
@schedulers.setter
def schedulers(self, value):
self._schedulers = set(try_split(value, ','))
@property
def workload(self) -> str:
return self._workload
@workload.setter
def workload(self, value):
self._workload = value
@log_around(after_message='Job executed successfully', exception_message='Job failed', ret_validity=True)
def execute(self) -> bool:
"""Executes a single job.
:return: Returns True if successful, else False.
"""
log('Executing job %s' % self.name)
metrics_store = MetricsStore()
for scheduler in self.schedulers:
if not change_scheduler(scheduler, self.device):
print_detailed('Unable to change scheduler %s for device %s' % (scheduler, self.device))
return False
start_time, stop_time, metrics = self._execute_workload()
metrics = defaultdict(int, metrics)
metrics['fslat-read'] = metrics['clat-read'] - metrics['q2c']
metrics['fslat-write'] = metrics['clat-write'] - metrics['q2c']
metrics['bslat'] = metrics['q2c'] - metrics['d2c']
metrics['workload'] = self.name
metrics['device'] = self.device
metrics['scheduler'] = scheduler
metrics['start-time'] = start_time
metrics['stop-time'] = stop_time
Metrics.print(self.name, self.workload, scheduler, self.device, metrics)
Metrics.output(metrics)
device_short = Mem.re_device.findall(self.device)[0]
metrics_store.add(self.workload, device_short, scheduler, metrics)
return True
def fill_missing(self, o):
"""Fills in missing values from object.
:param o: The object.
"""
if self._delay is None:
self._delay = ignore_exception(AttributeError)(getattr)(o, 'delay')
if self._device is None:
self._device = ignore_exception(AttributeError)(getattr)(o, 'device')
if self._repetition is None:
self._repetition = ignore_exception(AttributeError)(getattr)(o, 'repetition')
if self._runtime is None:
self._runtime = ignore_exception(AttributeError)(getattr)(o, 'runtime')
if self._schedulers is None:
self._schedulers = ignore_exception(AttributeError)(getattr)(o, 'schedulers')
if self._workload is None:
self._workload = ignore_exception(AttributeError)(getattr)(o, 'workload')
def get_invalid_props(self) -> list:
"""Returns the properties that are invalid.
:return: A list of properties.
"""
invalid_props = []
if self._delay is None:
invalid_props.append('delay')
if self._device is None:
invalid_props.append('device')
if self._repetition is None:
invalid_props.append('repetition')
if self._runtime is None:
invalid_props.append('runtime')
if self._schedulers is None:
invalid_props.append('schedulers')
if self._workload is None:
invalid_props.append('workload')
return invalid_props
def is_valid(self) -> bool:
"""Returns whether the job is valid.
:return: Returns True if valid, else False.
"""
return self._delay is not None and \
self._device is not None and \
self._repetition is not None and \
self._runtime is not None and \
self._schedulers is not None and \
self._workload is not None
def _execute_workload(self) -> tuple:
"""Executes a workload.
:return: Returns a dictionary of metrics if successful, else None.
"""
log('Executing workload %s' % self.workload)
metrics = Metrics(self.workload)
start_time = ''
stop_time = ''
# Repeat job multiple times
for i in range(self.repetition):
device_short = Mem.re_device.findall(self.device)[0]
# Repeat workload if failure
retry = 0
while retry < Mem.retry:
retry += 1
# Clear all the things
clear_caches(self.device)
# Run workload along with blktrace
blktrace = Mem.format_blktrace % (self.device, device_short, self.runtime)
adj_command = adjusted_workload(self.command, self.workload)
start_time = strftime('%m/%d/%y %I:%M:%S %p', localtime())
out = run_parallel_commands([('blktrace', self.delay, blktrace), (self.workload, 0, adj_command)])
stop_time = strftime('%m/%d/%y %I:%M:%S %p', localtime())
# Error running commands
if out is None or 'blktrace' in out and out['blktrace'] is None:
log('Error running workload %s' % self.workload)
time.sleep(5)
continue
blktrace_out, _ = out['blktrace']
workload_out, _ = out[self.workload]
log('Workload Output')
log(workload_out)
if blktrace_out is None or workload_out is None:
log('Error running workload %s' % self.workload)
time.sleep(5)
continue
# Run blkparse
blkparse = Mem.format_blkparse % (device_short, device_short)
_, _ = run_command(blkparse, ignore_output=True)
# Way too much cowbell (-f '' doesn't seem to trim output)
#log('BLKPARSE Output')
#log(blkparse_out)
# Run blkrawverify
blkrawverify = Mem.format_blkrawverify % device_short
blkrawverify_out, _ = run_command(blkrawverify)
log('BLKRAWYVERIFY Output')
log(blkrawverify_out)
# Run btt
btt = Mem.format_btt % device_short
btt_out, _ = run_command(btt)
if btt_out is None:
log('Error running workload %s' % self.workload)
time.sleep(5)
continue
log('BTT Output')
btt_split = btt_out.split("# Total System")[0]
btt_split2 = btt_split.split("==================== All Devices ====================")[-1]
log("==================== All Devices ====================")
log(btt_split2)
# Cleanup intermediate files
if Mem.cleanup:
log('Cleaning up files')
cleanup_files('sda.blktrace.*', 'sda.blkparse.*', 'sys_iops_fp.dat', 'sys_mbps_fp.dat')
dmm = get_device_major_minor(self.device)
cleanup_files('%s_iops_fp.dat' % dmm, '%s_mbps_fp.dat' % dmm)
cleanup_files('%s.verify.out' % device_short)
m = Metrics.gather_metrics(None, btt_out, workload_out, self.workload)
metrics.add_metrics(m)
break
else:
print_detailed('Unable to run workload %s' % self.workload)
return None
return start_time, stop_time, metrics.average_metrics()
class MetricsStore:
"""A datastore for saving / retrieving metrics."""
def __init__(self):
self._store = dict()
def __contains__(self, item):
return item in self._store
def __len__(self):
return len(self._store)
def add(self, workload: str, device: str, scheduler: str, metrics: dict):
"""Adds a new key to the datastore.
:param workload: The workload.
:param device: The device.
:param scheduler: The scheduler.
:param metrics: The metrics.
"""
key = (workload, device, scheduler)
if key not in self._store:
self._store[key] = {'workload': workload, 'device': device, 'scheduler': scheduler, 'key': key,
'metrics': metrics}
def get(self, workload: str, device: str, scheduler: str):
"""Retrieves a single item matching the given key.
:param workload: The workload.
:param device: The device.
:param scheduler: The scheduler.
:return: The retrieved item.
:exception KeyError: Raised if key not found.
"""
key = (workload, device, scheduler)
if key not in self._store:
raise KeyError("Unable to find key: (%s, %s, %s)" % (workload, device, scheduler))
return self._store[key]
def get_all(self, **kwargs):
"""Retrieves all items with keys matching the given optional kwargs (workload, device, scheduler).
:param kwargs: The following optional kwargs can be specified for lookups (workload, device, scheduler). Only
the specified key parts will be matched on. If none are specified, all items are retrieved.
:return: A list of matched items.
"""
workload = None
if 'workload' in kwargs:
workload = kwargs['workload']
device = None
if 'device' in kwargs:
device = kwargs['device']
scheduler = None
if 'scheduler' in kwargs:
scheduler = kwargs['scheduler']
items = []
for key, value in self._store.items():
if workload and key[0] != workload:
continue
if device and key[1] != device:
continue
if scheduler and key[2] != scheduler:
continue
items.append(value)
return items
class Metrics:
"""A group of metrics for a particular workload."""
__output_initialized = False
def __init__(self, workload: str):
self.workload = workload
self._metrics = []
def add_metrics(self, metrics: dict):
"""Adds new metrics.
:param metrics: The metrics. Expects mapping of metric name to metric value (int or float)."""
self._metrics.append(metrics)
def average_metrics(self) -> dict:
"""Averages the metrics into a new dictionary.
:return: The averaged metrics.
"""
averaged_metrics = dict() # The averaged metrics
metric_frequency = dict() # The frequency of each metric
# Sums the metrics then divides each by their frequency
for metric in self._metrics:
for key, value in metric.items():
metric_frequency.setdefault(key, 0)
metric_frequency[key] += 1
averaged_metrics.setdefault(key, 0)
averaged_metrics[key] += value
for key in averaged_metrics:
averaged_metrics[key] = averaged_metrics[key] / metric_frequency[key]
return averaged_metrics
@staticmethod
def average_metric(metrics: dict, names: tuple):
"""Returns the average of the metrics.
:param metrics: The metrics dictionary.
:param names: The name of the metrics to average.
:return: The average of the metrics.
"""
count = 0
summation = 0
for name in names:
if name in metrics and metrics[name] > 0:
summation += metrics[name]
count += 1
if count == 0:
return 0
else:
return summation / count
@staticmethod
def gather_workload_metrics(workload_out: str, workload: str) -> dict:
"""Parses workload outputs and returns relevant metrics.
:param workload_out: The workload output.
:param workload: The workload.
:return: A dictionary of metrics and their values.
"""
ret = defaultdict(int)
if workload == 'fio':
data = json.loads(workload_out, encoding='utf-8')
bwrc, bwwc = 0, 0
crc, cwc = 0, 0
src, swc = 0, 0
lrc, lwc = 0, 0
iopsr, iopsw = 0, 0
iokb = 0,
for job in data['jobs']:
ret['throughput-read'] += float(job['read']['bw']) / 1024
if job['read']['bw'] > 0:
bwrc += 1
log('Grabbing metric %s: %s' % ('throughput-read', job['read']['bw'] / 1024))
ret['throughput-write'] += float(job['write']['bw']) / 1024
if job['write']['bw'] > 0:
bwwc += 1
log('Grabbing metric %s: %s' % ('throughput-write', job['write']['bw'] / 1024))
ret['clat-read'] += float(job['read']['clat_ns']['mean'])
if job['read']['clat_ns']['mean'] > 0:
crc += 1
log('Grabbing metric %s: %s' % ('clat-read', job['read']['clat_ns']['mean']))
ret['clat-write'] += float(job['write']['clat_ns']['mean'])
if job['write']['clat_ns']['mean'] > 0:
cwc += 1
log('Grabbing metric %s: %s' % ('clat-write', job['write']['clat_ns']['mean']))
ret['slat-read'] += float(job['read']['slat_ns']['mean'])
if job['read']['slat_ns']['mean'] > 0:
src += 1
log('Grabbing metric %s: %s' % ('slat-read', job['read']['slat_ns']['mean']))
ret['slat-write'] += float(job['write']['slat_ns']['mean'])
if job['write']['slat_ns']['mean'] > 0:
swc += 1
log('Grabbing metric %s: %s' % ('slat-write', job['write']['slat_ns']['mean']))
ret['lat-read'] += float(job['read']['lat_ns']['mean'])
if job['read']['lat_ns']['mean'] > 0:
lrc += 1
log('Grabbing metric %s: %s' % ('lat-read', job['read']['lat_ns']['mean']))
ret['lat-write'] += float(job['write']['lat_ns']['mean'])
if job['write']['lat_ns']['mean'] > 0:
lwc += 1
log('Grabbing metric %s: %s' % ('lat-write', job['write']['lat_ns']['mean']))
ret['iops-read'] += float(job['read']['iops'])
if job['read']['iops'] > 0:
iopsr += 1
log('Grabbing metric %s: %s' % ('iops-read', job['read']['iops']))
ret['iops-write'] += float(job['write']['iops'])
if job['write']['iops'] > 0:
iopsw += 1
log('Grabbing metric %s: %s' % ('iops-write', job['write']['iops']))
ret['io-kbytes'] += float(job['read']['io_kbytes'])
if job['read']['io_kbytes'] > 0:
log('Grabbing metric %s: %s' % ('io-kbytes', job['read']['io_kbytes']))
ret['io-kbytes'] += float(job['write']['io_kbytes'])
if job['write']['io_kbytes'] > 0:
log('Grabbing metric %s: %s' % ('io-kbytes', job['write']['io_kbytes']))
ret['io-depth'] = int(job['job options']['iodepth'])
# Compute averages
if bwrc > 0: ret['throughput-read'] /= bwrc
if bwwc > 0: ret['throughput-write'] /= bwwc
if crc > 0: ret['clat-read'] /= crc
if cwc > 0: ret['clat-write'] /= cwc
if src > 0: ret['slat-read'] /= src
if swc > 0: ret['slat-write'] /= swc
if lrc >0: ret['lat-read'] /= lrc
if lwc > 0: ret['lat-write'] /= lwc
if iopsr > 0: ret['iops-read'] /= iopsr
if iopsw > 0: ret['iops-write'] /= iopsw
# Adjust values to be in µs
ret['clat-read'] /= 10**3
ret['clat-write'] /= 10**3
ret['slat-read'] /= 10**3
ret['slat-write'] /= 10**3
ret['lat-read'] /= 10 ** 3
ret['lat-write'] /= 10 ** 3
else:
print_detailed('Unable to interpret workload %s' % workload)
return ret
@staticmethod
def gather_metrics(blkparse_out: str, btt_out: str, workload_out: str, workload: str) -> dict:
"""Parses command outputs and returns relevant metrics.
:param blkparse_out: The blkparse command output.
:param btt_out: The btt command output.
:param workload_out: The workload output.
:param workload: The workload.
:return: A dictionary of metrics and their values.
"""
metrics = dict()
# blkparse
# throughput_read = Mem.re_blkparse_throughput_read.findall(blkparse_out)
# if throughput_read:
# metrics['throughput-read'] = float(throughput_read[0]) / 1024
# log('Grabbing metric %s: %s' % ('throughput-read', metrics['throughput-read']))
# throughput_write = Mem.re_blkparse_throughput_write.findall(blkparse_out)
# if throughput_write:
# metrics['throughput-write'] = float(throughput_write[0]) / 1024
# log('Grabbing metric %s: %s' % ('throughput-write', metrics['throughput-write']))
# btt
d2c = Mem.re_btt_d2c.findall(btt_out)
if d2c:
metrics['d2c'] = float(d2c[0]) * 10**6 # µs
log('Grabbing metric %s: %s' % ('d2c', metrics['d2c']))
q2c = Mem.re_btt_q2c.findall(btt_out)
if q2c:
metrics['q2c'] = float(q2c[0]) * 10**6 # µs
log('Grabbing metric %s: %s' % ('q2c', metrics['q2c']))
workload_metrics = Metrics.gather_workload_metrics(workload_out, workload)
metrics = defaultdict(int, {**metrics, **workload_metrics})
return metrics
@staticmethod
@ignore_exception()
@log_around(exception_message='Unable to output metrics to console!')
def print(job_name: str, workload: str, scheduler: str, device: str, metrics: dict):
"""Prints metric information to STDOUT.
:param job_name: The name of the job.
:param workload: The workload.
:param scheduler: The scheduler.
:param device: The device.
:param metrics: The metrics.
"""
print_and_log('%s [%s]:' % (job_name, workload))
print_and_log(' (%s) (%s):' % (scheduler, device))
print_and_log(' Latency [µs]: (read): %.2f (write): %.2f' % (metrics['lat-read'], metrics['lat-write']))
print_and_log(' Submission Latency [µs]: (read): %.2f (write): %.2f' % (metrics['slat-read'], metrics['slat-write']))
print_and_log(' Completion Latency [µs]: (read): %.2f (write): %.2f' % (metrics['clat-read'], metrics['clat-write']))
print_and_log(' File System Latency [µs]: (read): %.2f (write): %.2f' % (metrics['fslat-read'], metrics['fslat-write']))
print_and_log(' Block Layer Latency [µs]: %.2f' % metrics['bslat'])
print_and_log(' Device Latency [µs]: %.2f' % metrics['d2c'])
print_and_log(' IOPS: (read) %.2f (write) %.2f' % (metrics['iops-read'], metrics['iops-write']))
print_and_log(' Throughput [1024 MB/s]: (read) %.2f (write) %.2f' % (metrics['throughput-read'], metrics['throughput-write']))
print_and_log(' Total IO [KB]: %.2f' % metrics['io-kbytes'])
@staticmethod
@ignore_exception()
@log_around(exception_message='Unable to output metrics to file!')
def output(metrics: dict):
"""Prints metric information in csv format to output file.
:param metrics: The metrics.
"""
if Mem.output_file is not None:
if not Metrics.__output_initialized:
Metrics.__init_output()
with open(Mem.output_file, 'a') as file:
first = True
for column in Mem.output_column_order:
if first:
first = False
else:
file.write(',')
val = metrics[column]
if type(val) is float:
file.write('%0.2f' % val)
else:
file.write(str(val))
file.write('\n')
@staticmethod
@ignore_exception()
@log_around(exception_message='Unable to create output file!')
def __init_output():
"""Initializes output by creating file if doesn't already exist and adding header."""
Metrics.__output_initialized = True
# Create file if doesn't exist
if not os.path.isfile(Mem.output_file):
# Add header
with open(Mem.output_file, 'w') as file:
file.write(','.join(Mem.output_column_order))
file.write('\n')
# endregion
# region commands
@log_around(after_message='Changed scheduler successfully',
exception_message='Unable to change scheduler',
ret_validity=True)
def change_scheduler(scheduler: str, device: str):
"""Changes the I/O scheduler for the given device.
:param scheduler: The I/O scheduler.
:param device: The device.
:return: Returns True if successful, else False.
"""
log('Changing scheduler for device %s to %s' % (device, scheduler))
command = 'bash -c "echo %s > /sys/block/%s/queue/scheduler"' % (scheduler, Mem.re_device.findall(device)[0])
out, rc = run_command(command)
return rc == 0