handle log_unix_epoch=1
[fio.git] / tools / hist / fio-histo-log-pctiles.py
CommitLineData
d8296fdd
BE
1#!/usr/bin/env python
2
3# module to parse fio histogram log files, not using pandas
4# runs in python v2 or v3
5# to get help with the CLI: $ python fio-histo-log-pctiles.py -h
6# this can be run standalone as a script but is callable
7# assumes all threads run for same time duration
8# assumes all threads are doing the same thing for the entire run
9
10# percentiles:
11# 0 - min latency
12# 50 - median
13# 100 - max latency
14
15# TO-DO:
16# separate read and write stats for randrw mixed workload
17# report average latency if needed
18# prove that it works (partially done with unit tests)
19
20# to run unit tests, set UNITTEST environment variable to anything
21# if you do this, don't pass normal CLI parameters to it
22# otherwise it runs the CLI
23
18c1783a 24import sys, os, math, copy, time
d8296fdd 25from copy import deepcopy
c670cb44 26import argparse
d8296fdd
BE
27import unittest2
28
29msec_per_sec = 1000
30nsec_per_usec = 1000
18c1783a
BE
31direction_read = 0
32direction_write = 1
d8296fdd
BE
33
34class FioHistoLogExc(Exception):
35 pass
36
c670cb44 37# if there is an error, print message, and exit with error status
d8296fdd 38
c670cb44 39def myabort(msg):
d8296fdd 40 print('ERROR: ' + msg)
d8296fdd
BE
41 sys.exit(1)
42
d8296fdd
BE
43# convert histogram log file into a list of
44# (time_ms, direction, bsz, buckets) tuples where
45# - time_ms is the time in msec at which the log record was written
46# - direction is 0 (read) or 1 (write)
47# - bsz is block size (not used)
48# - buckets is a CSV list of counters that make up the histogram
49# caller decides if the expected number of counters are present
50
51
52def exception_suffix( record_num, pathname ):
53 return 'in histogram record %d file %s' % (record_num+1, pathname)
54
55# log file parser raises FioHistoLogExc exceptions
56# it returns histogram buckets in whatever unit fio uses
18c1783a
BE
57# inputs:
58# logfn: pathname to histogram log file
59# buckets_per_interval - how many histogram buckets to expect
60# log_hist_msec - if not None, expected time interval between histogram records
61
62def parse_hist_file(logfn, buckets_per_interval, log_hist_msec):
63 previous_ts_ms_read = -1
64 previous_ts_ms_write = -1
65
d8296fdd
BE
66 with open(logfn, 'r') as f:
67 records = [ l.strip() for l in f.readlines() ]
68 intervals = []
69 for k, r in enumerate(records):
70 if r == '':
71 continue
72 tokens = r.split(',')
73 try:
74 int_tokens = [ int(t) for t in tokens ]
75 except ValueError as e:
76 raise FioHistoLogExc('non-integer value %s' % exception_suffix(k+1, logfn))
77
78 neg_ints = list(filter( lambda tk : tk < 0, int_tokens ))
79 if len(neg_ints) > 0:
80 raise FioHistoLogExc('negative integer value %s' % exception_suffix(k+1, logfn))
81
82 if len(int_tokens) < 3:
83 raise FioHistoLogExc('too few numbers %s' % exception_suffix(k+1, logfn))
84
d8296fdd 85 direction = int_tokens[1]
18c1783a 86 if direction != direction_read and direction != direction_write:
d8296fdd
BE
87 raise FioHistoLogExc('invalid I/O direction %s' % exception_suffix(k+1, logfn))
88
18c1783a
BE
89 time_ms = int_tokens[0]
90 if direction == direction_read:
91 if time_ms < previous_ts_ms_read:
92 raise FioHistoLogExc('read timestamp in column 1 decreased %s' % exception_suffix(k+1, logfn))
93 previous_ts_ms_read = time_ms
94 elif direction == direction_write:
95 if time_ms < previous_ts_ms_write:
96 raise FioHistoLogExc('write timestamp in column 1 decreased %s' % exception_suffix(k+1, logfn))
97 previous_ts_ms_write = time_ms
98
d8296fdd
BE
99 bsz = int_tokens[2]
100 if bsz > (1 << 24):
101 raise FioHistoLogExc('block size too large %s' % exception_suffix(k+1, logfn))
102
103 buckets = int_tokens[3:]
104 if len(buckets) != buckets_per_interval:
105 raise FioHistoLogExc('%d buckets per interval but %d expected in %s' %
106 (len(buckets), buckets_per_interval, exception_suffix(k+1, logfn)))
107 intervals.append((time_ms, direction, bsz, buckets))
108 if len(intervals) == 0:
109 raise FioHistoLogExc('no records in %s' % logfn)
18c1783a
BE
110 (first_timestamp, _, _, _) = intervals[0]
111 if first_timestamp < 1000000:
112 start_time = 0 # assume log_unix_epoch = 0
113 elif log_hist_msec != None:
114 start_time = first_timestamp - log_hist_msec
115 elif len(intervals) > 1:
116 (second_timestamp, _, _, _) = intervals[1]
117 start_time = first_timestamp - (second_timestamp - first_timestamp)
118 (end_timestamp, _, _, _) = intervals[-1]
119
120 return (intervals, start_time, end_timestamp)
d8296fdd
BE
121
122
123# compute time range for each bucket index in histogram record
124# see comments in https://github.com/axboe/fio/blob/master/stat.h
125# for description of bucket groups and buckets
126# fio v3 bucket ranges are in nanosec (since response times are measured in nanosec)
127# but we convert fio v3 nanosecs to floating-point microseconds
128
129def time_ranges(groups, counters_per_group, fio_version=3):
130 bucket_width = 1
131 bucket_base = 0
132 bucket_intervals = []
133 for g in range(0, groups):
134 for b in range(0, counters_per_group):
135 rmin = float(bucket_base)
136 rmax = rmin + bucket_width
137 if fio_version == 3:
138 rmin /= nsec_per_usec
139 rmax /= nsec_per_usec
140 bucket_intervals.append( [rmin, rmax] )
141 bucket_base += bucket_width
142 if g != 0:
143 bucket_width *= 2
144 return bucket_intervals
145
146
147# compute number of time quantum intervals in the test
148
18c1783a 149def get_time_intervals(time_quantum, min_timestamp_ms, max_timestamp_ms):
d8296fdd
BE
150 # round down to nearest second
151 max_timestamp = max_timestamp_ms // msec_per_sec
18c1783a 152 min_timestamp = min_timestamp_ms // msec_per_sec
d8296fdd 153 # round up to nearest whole multiple of time_quantum
18c1783a
BE
154 time_interval_count = ((max_timestamp - min_timestamp) + time_quantum) // time_quantum
155 end_time = min_timestamp + (time_interval_count * time_quantum)
d8296fdd
BE
156 return (end_time, time_interval_count)
157
158# align raw histogram log data to time quantum so
159# we can then combine histograms from different threads with addition
160# for randrw workload we count both reads and writes in same output bucket
161# but we separate reads and writes for purposes of calculating
162# end time for histogram record.
163# this requires us to weight a raw histogram bucket by the
164# fraction of time quantum that the bucket overlaps the current
165# time quantum interval
166# for example, if we have a bucket with 515 samples for time interval
167# [ 1010, 2014 ] msec since start of test, and time quantum is 1 sec, then
168# for time quantum interval [ 1000, 2000 ] msec, the overlap is
169# (2000 - 1010) / (2000 - 1000) = 0.99
170# so the contribution of this bucket to this time quantum is
171# 515 x 0.99 = 509.85
172
18c1783a 173def align_histo_log(raw_histogram_log, time_quantum, bucket_count, min_timestamp_ms, max_timestamp_ms):
d8296fdd
BE
174
175 # slice up test time int intervals of time_quantum seconds
176
18c1783a 177 (end_time, time_interval_count) = get_time_intervals(time_quantum, min_timestamp_ms, max_timestamp_ms)
d8296fdd
BE
178 time_qtm_ms = time_quantum * msec_per_sec
179 end_time_ms = end_time * msec_per_sec
180 aligned_intervals = []
181 for j in range(0, time_interval_count):
182 aligned_intervals.append((
18c1783a 183 min_timestamp_ms + (j * time_qtm_ms),
d8296fdd
BE
184 [ 0.0 for j in range(0, bucket_count) ] ))
185
186 log_record_count = len(raw_histogram_log)
187 for k, record in enumerate(raw_histogram_log):
188
189 # find next record with same direction to get end-time
190 # have to avoid going past end of array
191 # for fio randrw workload,
192 # we have read and write records on same time interval
193 # sometimes read and write records are in opposite order
194 # assertion checks that next read/write record
195 # can be separated by at most 2 other records
196
197 (time_msec, direction, sz, interval_buckets) = record
198 if k+1 < log_record_count:
199 (time_msec_end, direction2, _, _) = raw_histogram_log[k+1]
200 if direction2 != direction:
201 if k+2 < log_record_count:
202 (time_msec_end, direction2, _, _) = raw_histogram_log[k+2]
203 if direction2 != direction:
204 if k+3 < log_record_count:
205 (time_msec_end, direction2, _, _) = raw_histogram_log[k+3]
206 assert direction2 == direction
207 else:
208 time_msec_end = end_time_ms
209 else:
210 time_msec_end = end_time_ms
211 else:
212 time_msec_end = end_time_ms
213
214 # calculate first quantum that overlaps this histogram record
215
18c1783a
BE
216 offset_from_min_ts = time_msec - min_timestamp_ms
217 qtm_start_ms = min_timestamp_ms + (offset_from_min_ts // time_qtm_ms) * time_qtm_ms
218 qtm_end_ms = min_timestamp_ms + ((offset_from_min_ts + time_qtm_ms) // time_qtm_ms) * time_qtm_ms
219 qtm_index = offset_from_min_ts // time_qtm_ms
d8296fdd
BE
220
221 # for each quantum that overlaps this histogram record's time interval
222
223 while qtm_start_ms < time_msec_end: # while quantum overlaps record
224
18c1783a
BE
225 # some histogram logs may be longer than others
226
227 if len(aligned_intervals) <= qtm_index:
228 break
229
d8296fdd
BE
230 # calculate fraction of time that this quantum
231 # overlaps histogram record's time interval
232
233 overlap_start = max(qtm_start_ms, time_msec)
234 overlap_end = min(qtm_end_ms, time_msec_end)
235 weight = float(overlap_end - overlap_start)
236 weight /= (time_msec_end - time_msec)
237 (_,aligned_histogram) = aligned_intervals[qtm_index]
238 for bx, b in enumerate(interval_buckets):
239 weighted_bucket = weight * b
240 aligned_histogram[bx] += weighted_bucket
241
242 # advance to the next time quantum
243
244 qtm_start_ms += time_qtm_ms
245 qtm_end_ms += time_qtm_ms
246 qtm_index += 1
247
248 return aligned_intervals
249
250# add histogram in "source" to histogram in "target"
251# it is assumed that the 2 histograms are precisely time-aligned
252
253def add_to_histo_from( target, source ):
254 for b in range(0, len(source)):
255 target[b] += source[b]
256
257# compute percentiles
258# inputs:
259# buckets: histogram bucket array
260# wanted: list of floating-pt percentiles to calculate
261# time_ranges: [tmin,tmax) time interval for each bucket
262# returns None if no I/O reported.
263# otherwise we would be dividing by zero
264# think of buckets as probability distribution function
265# and this loop is integrating to get cumulative distribution function
266
267def get_pctiles(buckets, wanted, time_ranges):
268
269 # get total of IO requests done
270 total_ios = 0
271 for io_count in buckets:
272 total_ios += io_count
273
274 # don't return percentiles if no I/O was done during interval
275 if total_ios == 0.0:
276 return None
277
278 pctile_count = len(wanted)
279
280 # results returned as dictionary keyed by percentile
281 pctile_result = {}
282
283 # index of next percentile in list
284 pctile_index = 0
285
286 # next percentile
287 next_pctile = wanted[pctile_index]
288
289 # no one is interested in percentiles bigger than this but not 100.0
290 # this prevents floating-point error from preventing loop exit
291 almost_100 = 99.9999
292
0456267b
BE
293 # pct is the percentile corresponding to
294 # all I/O requests up through bucket b
295 pct = 0.0
d8296fdd
BE
296 total_so_far = 0
297 for b, io_count in enumerate(buckets):
0456267b
BE
298 if io_count == 0:
299 continue
d8296fdd 300 total_so_far += io_count
0456267b
BE
301 # last_pct_lt is the percentile corresponding to
302 # all I/O requests up to, but not including, bucket b
303 last_pct = pct
304 pct = 100.0 * float(total_so_far) / total_ios
d8296fdd
BE
305 # a single bucket could satisfy multiple pctiles
306 # so this must be a while loop
0456267b
BE
307 # for 100-percentile (max latency) case, no bucket exceeds it
308 # so we must stop there.
309 while ((next_pctile == 100.0 and pct >= almost_100) or
310 (next_pctile < 100.0 and pct > next_pctile)):
311 # interpolate between min and max time for bucket time interval
312 # we keep the time_ranges access inside this loop,
313 # even though it could be above the loop,
314 # because in many cases we will not be even entering
315 # the loop so we optimize out these accesses
d8296fdd 316 range_max_time = time_ranges[b][1]
0456267b
BE
317 range_min_time = time_ranges[b][0]
318 offset_frac = (next_pctile - last_pct)/(pct - last_pct)
319 interpolation = range_min_time + (offset_frac*(range_max_time - range_min_time))
320 pctile_result[next_pctile] = interpolation
d8296fdd
BE
321 pctile_index += 1
322 if pctile_index == pctile_count:
323 break
324 next_pctile = wanted[pctile_index]
325 if pctile_index == pctile_count:
326 break
327 assert pctile_index == pctile_count
328 return pctile_result
329
330
c670cb44 331# this is really the main program
d8296fdd 332
c670cb44
BE
333def compute_percentiles_from_logs():
334 parser = argparse.ArgumentParser()
335 parser.add_argument("--fio-version", dest="fio_version",
336 default="3", choices=[2,3], type=int,
337 help="fio version (default=3)")
338 parser.add_argument("--bucket-groups", dest="bucket_groups", default="29", type=int,
339 help="fio histogram bucket groups (default=29)")
340 parser.add_argument("--bucket-bits", dest="bucket_bits",
341 default="6", type=int,
342 help="fio histogram buckets-per-group bits (default=6 means 64 buckets/group)")
343 parser.add_argument("--percentiles", dest="pctiles_wanted",
4b34a0eb 344 default=[ 0., 50., 95., 99., 100.], type=float, nargs='+',
c670cb44
BE
345 help="fio histogram buckets-per-group bits (default=6 means 64 buckets/group)")
346 parser.add_argument("--time-quantum", dest="time_quantum",
347 default="1", type=int,
348 help="time quantum in seconds (default=1)")
18c1783a
BE
349 parser.add_argument("--log-hist-msec", dest="log_hist_msec",
350 type=int, default=None,
351 help="log_hist_msec value in fio job file")
c670cb44
BE
352 parser.add_argument("--output-unit", dest="output_unit",
353 default="usec", type=str,
354 help="Latency percentile output unit: msec|usec|nsec (default usec)")
4b34a0eb
BE
355 parser.add_argument("file_list", nargs='+',
356 help='list of files, preceded by " -- " if necessary')
c670cb44 357 args = parser.parse_args()
c670cb44 358
4b34a0eb
BE
359 # default changes based on fio version
360 if args.fio_version == 2:
361 args.bucket_groups = 19
d8296fdd 362
c670cb44 363 # print parameters
d8296fdd 364
4b34a0eb 365 print('fio version = %d' % args.fio_version)
c670cb44
BE
366 print('bucket groups = %d' % args.bucket_groups)
367 print('bucket bits = %d' % args.bucket_bits)
368 print('time quantum = %d sec' % args.time_quantum)
369 print('percentiles = %s' % ','.join([ str(p) for p in args.pctiles_wanted ]))
370 buckets_per_group = 1 << args.bucket_bits
d8296fdd 371 print('buckets per group = %d' % buckets_per_group)
c670cb44 372 buckets_per_interval = buckets_per_group * args.bucket_groups
d8296fdd
BE
373 print('buckets per interval = %d ' % buckets_per_interval)
374 bucket_index_range = range(0, buckets_per_interval)
18c1783a
BE
375 if args.log_hist_msec != None:
376 print('log_hist_msec = %d' % args.log_hist_msec)
c670cb44
BE
377 if args.time_quantum == 0:
378 print('ERROR: time-quantum must be a positive number of seconds')
379 print('output unit = ' + args.output_unit)
380 if args.output_unit == 'msec':
18c1783a 381 time_divisor = float(msec_per_sec)
c670cb44 382 elif args.output_unit == 'usec':
d8296fdd
BE
383 time_divisor = 1.0
384
d8296fdd
BE
385 # construct template for each histogram bucket array with buckets all zeroes
386 # we just copy this for each new histogram
387
388 zeroed_buckets = [ 0.0 for r in bucket_index_range ]
389
18c1783a 390 # calculate response time interval associated with each histogram bucket
d8296fdd 391
18c1783a 392 bucket_times = time_ranges(args.bucket_groups, buckets_per_group, fio_version=args.fio_version)
d8296fdd
BE
393
394 # parse the histogram logs
395 # assumption: each bucket has a monotonically increasing time
396 # assumption: time ranges do not overlap for a single thread's records
397 # (exception: if randrw workload, then there is a read and a write
398 # record for the same time interval)
399
18c1783a
BE
400 test_start_time = 0
401 test_end_time = 1.0e18
d8296fdd 402 hist_files = {}
c670cb44 403 for fn in args.file_list:
d8296fdd 404 try:
18c1783a 405 (hist_files[fn], log_start_time, log_end_time) = parse_hist_file(fn, buckets_per_interval, args.log_hist_msec)
d8296fdd 406 except FioHistoLogExc as e:
c670cb44 407 myabort(str(e))
18c1783a
BE
408 # we consider the test started when all threads have started logging
409 test_start_time = max(test_start_time, log_start_time)
410 # we consider the test over when one of the logs has ended
411 test_end_time = min(test_end_time, log_end_time)
412
413 if test_start_time >= test_end_time:
414 raise FioHistoLogExc('no time interval when all threads logs overlapped')
415 if test_start_time > 0:
416 print('all threads running as of unix epoch time %d = %s' % (
417 test_start_time/float(msec_per_sec),
418 time.ctime(test_start_time/1000.0)))
419
420 (end_time, time_interval_count) = get_time_intervals(args.time_quantum, test_start_time, test_end_time)
c670cb44 421 all_threads_histograms = [ ((j*args.time_quantum*msec_per_sec), deepcopy(zeroed_buckets))
18c1783a 422 for j in range(0, time_interval_count) ]
d8296fdd
BE
423
424 for logfn in hist_files.keys():
425 aligned_per_thread = align_histo_log(hist_files[logfn],
c670cb44 426 args.time_quantum,
d8296fdd 427 buckets_per_interval,
18c1783a
BE
428 test_start_time,
429 test_end_time)
d8296fdd
BE
430 for t in range(0, time_interval_count):
431 (_, all_threads_histo_t) = all_threads_histograms[t]
432 (_, log_histo_t) = aligned_per_thread[t]
d8296fdd
BE
433 add_to_histo_from( all_threads_histo_t, log_histo_t )
434
c670cb44 435 # calculate percentiles across aggregate histogram for all threads
18c1783a
BE
436 # print CSV header just like fiologparser_hist does
437
438 header = 'msec-since-start, '
439 for p in args.pctiles_wanted:
440 header += '%3.1f, ' % p
441 print('time (millisec), percentiles in increasing order with values in ' + args.output_unit)
442 print(header)
c670cb44 443
d8296fdd 444 for (t_msec, all_threads_histo_t) in all_threads_histograms:
18c1783a 445 record = '%8d, ' % t_msec
c670cb44 446 pct = get_pctiles(all_threads_histo_t, args.pctiles_wanted, bucket_times)
d8296fdd 447 if not pct:
c670cb44 448 for w in args.pctiles_wanted:
d8296fdd
BE
449 record += ', '
450 else:
451 pct_keys = [ k for k in pct.keys() ]
452 pct_values = [ str(pct[wanted]/time_divisor) for wanted in sorted(pct_keys) ]
453 record += ', '.join(pct_values)
454 print(record)
455
456
457
458#end of MAIN PROGRAM
459
460
461
462##### below are unit tests ##############
463
464import tempfile, shutil
465from os.path import join
466should_not_get_here = False
467
468class Test(unittest2.TestCase):
469 tempdir = None
470
471 # a little less typing please
472 def A(self, boolean_val):
473 self.assertTrue(boolean_val)
474
475 # initialize unit test environment
476
477 @classmethod
478 def setUpClass(cls):
479 d = tempfile.mkdtemp()
480 Test.tempdir = d
481
482 # remove anything left by unit test environment
483 # unless user sets UNITTEST_LEAVE_FILES environment variable
484
485 @classmethod
486 def tearDownClass(cls):
487 if not os.getenv("UNITTEST_LEAVE_FILES"):
488 shutil.rmtree(cls.tempdir)
489
490 def setUp(self):
491 self.fn = join(Test.tempdir, self.id())
492
493 def test_a_add_histos(self):
494 a = [ 1.0, 2.0 ]
495 b = [ 1.5, 2.5 ]
496 add_to_histo_from( a, b )
497 self.A(a == [2.5, 4.5])
498 self.A(b == [1.5, 2.5])
499
500 def test_b1_parse_log(self):
501 with open(self.fn, 'w') as f:
502 f.write('1234, 0, 4096, 1, 2, 3, 4\n')
503 f.write('5678,1,16384,5,6,7,8 \n')
18c1783a
BE
504 (raw_histo_log, min_timestamp, max_timestamp) = parse_hist_file(self.fn, 4, None) # 4 buckets per interval
505 # if not log_unix_epoch=1, then min_timestamp will always be set to zero
506 self.A(len(raw_histo_log) == 2 and min_timestamp == 0 and max_timestamp == 5678)
d8296fdd
BE
507 (time_ms, direction, bsz, histo) = raw_histo_log[0]
508 self.A(time_ms == 1234 and direction == 0 and bsz == 4096 and histo == [ 1, 2, 3, 4 ])
509 (time_ms, direction, bsz, histo) = raw_histo_log[1]
510 self.A(time_ms == 5678 and direction == 1 and bsz == 16384 and histo == [ 5, 6, 7, 8 ])
511
512 def test_b2_parse_empty_log(self):
513 with open(self.fn, 'w') as f:
514 pass
515 try:
18c1783a 516 (raw_histo_log, _, _) = parse_hist_file(self.fn, 4, None)
d8296fdd
BE
517 self.A(should_not_get_here)
518 except FioHistoLogExc as e:
519 self.A(str(e).startswith('no records'))
520
521 def test_b3_parse_empty_records(self):
522 with open(self.fn, 'w') as f:
523 f.write('\n')
524 f.write('1234, 0, 4096, 1, 2, 3, 4\n')
525 f.write('5678,1,16384,5,6,7,8 \n')
526 f.write('\n')
18c1783a 527 (raw_histo_log, _, max_timestamp_ms) = parse_hist_file(self.fn, 4, None)
d8296fdd
BE
528 self.A(len(raw_histo_log) == 2 and max_timestamp_ms == 5678)
529 (time_ms, direction, bsz, histo) = raw_histo_log[0]
530 self.A(time_ms == 1234 and direction == 0 and bsz == 4096 and histo == [ 1, 2, 3, 4 ])
531 (time_ms, direction, bsz, histo) = raw_histo_log[1]
532 self.A(time_ms == 5678 and direction == 1 and bsz == 16384 and histo == [ 5, 6, 7, 8 ])
533
534 def test_b4_parse_non_int(self):
535 with open(self.fn, 'w') as f:
536 f.write('12, 0, 4096, 1a, 2, 3, 4\n')
537 try:
18c1783a 538 (raw_histo_log, _, _) = parse_hist_file(self.fn, 4, None)
d8296fdd
BE
539 self.A(False)
540 except FioHistoLogExc as e:
541 self.A(str(e).startswith('non-integer'))
542
543 def test_b5_parse_neg_int(self):
544 with open(self.fn, 'w') as f:
545 f.write('-12, 0, 4096, 1, 2, 3, 4\n')
546 try:
18c1783a 547 (raw_histo_log, _, _) = parse_hist_file(self.fn, 4, None)
d8296fdd
BE
548 self.A(False)
549 except FioHistoLogExc as e:
550 self.A(str(e).startswith('negative integer'))
551
552 def test_b6_parse_too_few_int(self):
553 with open(self.fn, 'w') as f:
554 f.write('0, 0\n')
555 try:
18c1783a 556 (raw_histo_log, _, _) = parse_hist_file(self.fn, 4, None)
d8296fdd
BE
557 self.A(False)
558 except FioHistoLogExc as e:
559 self.A(str(e).startswith('too few numbers'))
560
561 def test_b7_parse_invalid_direction(self):
562 with open(self.fn, 'w') as f:
563 f.write('100, 2, 4096, 1, 2, 3, 4\n')
564 try:
18c1783a 565 (raw_histo_log, _, _) = parse_hist_file(self.fn, 4, None)
d8296fdd
BE
566 self.A(False)
567 except FioHistoLogExc as e:
568 self.A(str(e).startswith('invalid I/O direction'))
569
570 def test_b8_parse_bsz_too_big(self):
571 with open(self.fn+'_good', 'w') as f:
572 f.write('100, 1, %d, 1, 2, 3, 4\n' % (1<<24))
18c1783a 573 (raw_histo_log, _, _) = parse_hist_file(self.fn+'_good', 4, None)
d8296fdd
BE
574 with open(self.fn+'_bad', 'w') as f:
575 f.write('100, 1, 20000000, 1, 2, 3, 4\n')
576 try:
18c1783a 577 (raw_histo_log, _, _) = parse_hist_file(self.fn+'_bad', 4, None)
d8296fdd
BE
578 self.A(False)
579 except FioHistoLogExc as e:
580 self.A(str(e).startswith('block size too large'))
581
582 def test_b9_parse_wrong_bucket_count(self):
583 with open(self.fn, 'w') as f:
584 f.write('100, 1, %d, 1, 2, 3, 4, 5\n' % (1<<24))
585 try:
18c1783a 586 (raw_histo_log, _, _) = parse_hist_file(self.fn, 4, None)
d8296fdd
BE
587 self.A(False)
588 except FioHistoLogExc as e:
589 self.A(str(e).__contains__('buckets per interval'))
590
591 def test_c1_time_ranges(self):
592 ranges = time_ranges(3, 2) # fio_version defaults to 3
593 expected_ranges = [ # fio_version 3 is in nanoseconds
594 [0.000, 0.001], [0.001, 0.002], # first group
595 [0.002, 0.003], [0.003, 0.004], # second group same width
596 [0.004, 0.006], [0.006, 0.008]] # subsequent groups double width
597 self.A(ranges == expected_ranges)
598 ranges = time_ranges(3, 2, fio_version=3)
599 self.A(ranges == expected_ranges)
600 ranges = time_ranges(3, 2, fio_version=2)
601 expected_ranges_v2 = [ [ 1000.0 * min_or_max for min_or_max in time_range ]
602 for time_range in expected_ranges ]
603 self.A(ranges == expected_ranges_v2)
604 # see fio V3 stat.h for why 29 groups and 2^6 buckets/group
605 normal_ranges_v3 = time_ranges(29, 64)
606 # for v3, bucket time intervals are measured in nanoseconds
607 self.A(len(normal_ranges_v3) == 29 * 64 and normal_ranges_v3[-1][1] == 64*(1<<(29-1))/1000.0)
608 normal_ranges_v2 = time_ranges(19, 64, fio_version=2)
609 # for v2, bucket time intervals are measured in microseconds so we have fewer buckets
610 self.A(len(normal_ranges_v2) == 19 * 64 and normal_ranges_v2[-1][1] == 64*(1<<(19-1)))
611
612 def test_d1_align_histo_log_1_quantum(self):
613 with open(self.fn, 'w') as f:
614 f.write('100, 1, 4096, 1, 2, 3, 4')
18c1783a
BE
615 (raw_histo_log, min_timestamp_ms, max_timestamp_ms) = parse_hist_file(self.fn, 4, None)
616 self.A(min_timestamp_ms == 0 and max_timestamp_ms == 100)
617 aligned_log = align_histo_log(raw_histo_log, 5, 4, min_timestamp_ms, max_timestamp_ms)
618 self.A(len(aligned_log) == 1)
619 (time_ms0, h) = aligned_log[0]
620 self.A(time_ms0 == 0 and h == [1., 2., 3., 4.])
621
622 # handle case with log_unix_epoch=1 timestamps, 1-second time quantum
623 # here both records will be separated into 2 aligned intervals
624
625 def test_d1a_align_2rec_histo_log_epoch_1_quantum_1sec(self):
626 with open(self.fn, 'w') as f:
627 f.write('1536504002123, 1, 4096, 1, 2, 3, 4\n')
628 f.write('1536504003123, 1, 4096, 4, 3, 2, 1\n')
629 (raw_histo_log, min_timestamp_ms, max_timestamp_ms) = parse_hist_file(self.fn, 4, None)
630 self.A(min_timestamp_ms == 1536504001123 and max_timestamp_ms == 1536504003123)
631 aligned_log = align_histo_log(raw_histo_log, 1, 4, min_timestamp_ms, max_timestamp_ms)
632 self.A(len(aligned_log) == 3)
633 (time_ms0, h) = aligned_log[0]
634 self.A(time_ms0 == 1536504001123 and h == [0., 0., 0., 0.])
635 (time_ms1, h) = aligned_log[1]
636 self.A(time_ms1 == 1536504002123 and h == [1., 2., 3., 4.])
637 (time_ms2, h) = aligned_log[2]
638 self.A(time_ms2 == 1536504003123 and h == [4., 3., 2., 1.])
639
640 # handle case with log_unix_epoch=1 timestamps, 5-second time quantum
641 # here both records will be merged into a single aligned time interval
642
643 def test_d1b_align_2rec_histo_log_epoch_1_quantum_5sec(self):
644 with open(self.fn, 'w') as f:
645 f.write('1536504002123, 1, 4096, 1, 2, 3, 4\n')
646 f.write('1536504003123, 1, 4096, 4, 3, 2, 1\n')
647 (raw_histo_log, min_timestamp_ms, max_timestamp_ms) = parse_hist_file(self.fn, 4, None)
648 self.A(min_timestamp_ms == 1536504001123 and max_timestamp_ms == 1536504003123)
649 aligned_log = align_histo_log(raw_histo_log, 5, 4, min_timestamp_ms, max_timestamp_ms)
d8296fdd
BE
650 self.A(len(aligned_log) == 1)
651 (time_ms0, h) = aligned_log[0]
18c1783a 652 self.A(time_ms0 == 1536504001123 and h == [5., 5., 5., 5.])
d8296fdd
BE
653
654 # we need this to compare 2 lists of floating point numbers for equality
655 # because of floating-point imprecision
656
657 def compare_2_floats(self, x, y):
658 if x == 0.0 or y == 0.0:
659 return (x+y) < 0.0000001
660 else:
661 return (math.fabs(x-y)/x) < 0.00001
662
663 def is_close(self, buckets, buckets_expected):
664 if len(buckets) != len(buckets_expected):
665 return False
666 compare_buckets = lambda k: self.compare_2_floats(buckets[k], buckets_expected[k])
667 indices_close = list(filter(compare_buckets, range(0, len(buckets))))
668 return len(indices_close) == len(buckets)
669
670 def test_d2_align_histo_log_2_quantum(self):
671 with open(self.fn, 'w') as f:
672 f.write('2000, 1, 4096, 1, 2, 3, 4\n')
673 f.write('7000, 1, 4096, 1, 2, 3, 4\n')
18c1783a
BE
674 (raw_histo_log, min_timestamp_ms, max_timestamp_ms) = parse_hist_file(self.fn, 4, None)
675 self.A(min_timestamp_ms == 0 and max_timestamp_ms == 7000)
d8296fdd
BE
676 (_, _, _, raw_buckets1) = raw_histo_log[0]
677 (_, _, _, raw_buckets2) = raw_histo_log[1]
18c1783a 678 aligned_log = align_histo_log(raw_histo_log, 5, 4, min_timestamp_ms, max_timestamp_ms)
d8296fdd
BE
679 self.A(len(aligned_log) == 2)
680 (time_ms1, h1) = aligned_log[0]
681 (time_ms2, h2) = aligned_log[1]
682 # because first record is from time interval [2000, 7000]
683 # we weight it according
684 expect1 = [float(b) * 0.6 for b in raw_buckets1]
685 expect2 = [float(b) * 0.4 for b in raw_buckets1]
686 for e in range(0, len(expect2)):
687 expect2[e] += raw_buckets2[e]
688 self.A(time_ms1 == 0 and self.is_close(h1, expect1))
689 self.A(time_ms2 == 5000 and self.is_close(h2, expect2))
690
0456267b
BE
691 # what to expect if histogram buckets are all equal
692 def test_e1_get_pctiles_flat_histo(self):
d8296fdd
BE
693 with open(self.fn, 'w') as f:
694 buckets = [ 100 for j in range(0, 128) ]
695 f.write('9000, 1, 4096, %s\n' % ', '.join([str(b) for b in buckets]))
18c1783a
BE
696 (raw_histo_log, min_timestamp_ms, max_timestamp_ms) = parse_hist_file(self.fn, 128, None)
697 self.A(min_timestamp_ms == 0 and max_timestamp_ms == 9000)
698 aligned_log = align_histo_log(raw_histo_log, 5, 128, min_timestamp_ms, max_timestamp_ms)
d8296fdd
BE
699 time_intervals = time_ranges(4, 32)
700 # since buckets are all equal, then median is halfway through time_intervals
701 # and max latency interval is at end of time_intervals
702 self.A(time_intervals[64][1] == 0.066 and time_intervals[127][1] == 0.256)
703 pctiles_wanted = [ 0, 50, 100 ]
704 pct_vs_time = []
705 for (time_ms, histo) in aligned_log:
706 pct_vs_time.append(get_pctiles(histo, pctiles_wanted, time_intervals))
707 self.A(pct_vs_time[0] == None) # no I/O in this time interval
0456267b 708 expected_pctiles = { 0:0.000, 50:0.064, 100:0.256 }
d8296fdd
BE
709 self.A(pct_vs_time[1] == expected_pctiles)
710
0456267b
BE
711 # what to expect if just the highest histogram bucket is used
712 def test_e2_get_pctiles_highest_pct(self):
713 fio_v3_bucket_count = 29 * 64
714 with open(self.fn, 'w') as f:
715 # make a empty fio v3 histogram
716 buckets = [ 0 for j in range(0, fio_v3_bucket_count) ]
717 # add one I/O request to last bucket
718 buckets[-1] = 1
719 f.write('9000, 1, 4096, %s\n' % ', '.join([str(b) for b in buckets]))
18c1783a
BE
720 (raw_histo_log, min_timestamp_ms, max_timestamp_ms) = parse_hist_file(self.fn, fio_v3_bucket_count, None)
721 self.A(min_timestamp_ms == 0 and max_timestamp_ms == 9000)
722 aligned_log = align_histo_log(raw_histo_log, 5, fio_v3_bucket_count, min_timestamp_ms, max_timestamp_ms)
0456267b
BE
723 (time_ms, histo) = aligned_log[1]
724 time_intervals = time_ranges(29, 64)
725 expected_pctiles = { 100.0:(64*(1<<28))/1000.0 }
726 pct = get_pctiles( histo, [ 100.0 ], time_intervals )
727 self.A(pct == expected_pctiles)
728
d8296fdd
BE
729# we are using this module as a standalone program
730
731if __name__ == '__main__':
732 if os.getenv('UNITTEST'):
733 sys.exit(unittest2.main())
734 else:
735 compute_percentiles_from_logs()
736