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