blob: 58dcf5636c42bcfdc74c5f5fe52bb8efd920dd67 [file] [log] [blame]
koder aka kdanilov7f59d562016-12-26 01:34:23 +02001import abc
koder aka kdanilova047e1b2015-04-21 23:16:59 +03002import logging
koder aka kdanilov7f59d562016-12-26 01:34:23 +02003from typing import Dict, Any, Iterator, Tuple, cast, List
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +03004
koder aka kdanilovffaf48d2016-12-27 02:25:29 +02005import numpy
6import scipy
7import matplotlib
8import matplotlib.pyplot as plt
koder aka kdanilovbe8f89f2015-04-28 14:51:51 +03009
koder aka kdanilovffaf48d2016-12-27 02:25:29 +020010
11matplotlib.use('svg')
12
13
koder aka kdanilov3b4da8b2016-10-17 00:17:53 +030014from .utils import ssize2b
koder aka kdanilov39e449e2016-12-17 15:15:26 +020015from .stage import Stage, StepOrder
16from .test_run_class import TestRun
koder aka kdanilovffaf48d2016-12-27 02:25:29 +020017from .result_classes import NormStatProps
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030018
koder aka kdanilov4a510ee2015-04-21 18:50:42 +030019
koder aka kdanilov962ee5f2016-12-19 02:40:08 +020020logger = logging.getLogger("wally")
koder aka kdanilova047e1b2015-04-21 23:16:59 +030021
22
koder aka kdanilov39e449e2016-12-17 15:15:26 +020023class ConsoleReportStage(Stage):
24
25 priority = StepOrder.REPORT
26
27 def run(self, ctx: TestRun) -> None:
28 # TODO(koder): load data from storage
29 raise NotImplementedError("...")
30
koder aka kdanilov7f59d562016-12-26 01:34:23 +020031
koder aka kdanilov39e449e2016-12-17 15:15:26 +020032class HtmlReportStage(Stage):
33
34 priority = StepOrder.REPORT
35
36 def run(self, ctx: TestRun) -> None:
37 # TODO(koder): load data from storage
38 raise NotImplementedError("...")
39
koder aka kdanilov7f59d562016-12-26 01:34:23 +020040
41# TODO: need to be revised, have to user StatProps fields instead
42class StoragePerfSummary:
43 def __init__(self, name: str) -> None:
44 self.direct_iops_r_max = 0 # type: int
45 self.direct_iops_w_max = 0 # type: int
46
47 # 64 used instead of 4k to faster feed caches
48 self.direct_iops_w64_max = 0 # type: int
49
50 self.rws4k_10ms = 0 # type: int
51 self.rws4k_30ms = 0 # type: int
52 self.rws4k_100ms = 0 # type: int
53 self.bw_write_max = 0 # type: int
54 self.bw_read_max = 0 # type: int
55
56 self.bw = None # type: float
57 self.iops = None # type: float
58 self.lat = None # type: float
59 self.lat_50 = None # type: float
60 self.lat_95 = None # type: float
61
62
63class HTMLBlock:
64 data = None # type: str
65 js_links = [] # type: List[str]
66 css_links = [] # type: List[str]
67
68
69class Reporter(metaclass=abc.ABCMeta):
70 @abc.abstractmethod
71 def get_divs(self, config, storage) -> Iterator[Tuple[str, str, HTMLBlock]]:
72 pass
73
74
75# Main performance report
76class PerformanceSummary(Reporter):
77 """Creates graph, which show how IOPS and Latency depend on QD"""
78
79
80# Main performance report
81class IOPS_QD(Reporter):
82 """Creates graph, which show how IOPS and Latency depend on QD"""
83
84
85# Linearization report
86class IOPS_Bsize(Reporter):
87 """Creates graphs, which show how IOPS and Latency depend on block size"""
88
89
90# IOPS/latency distribution
91class IOPSHist(Reporter):
92 """IOPS.latency distribution histogram"""
93
94
95# IOPS/latency over test time
96class IOPSTime(Reporter):
97 """IOPS/latency during test"""
koder aka kdanilovffaf48d2016-12-27 02:25:29 +020098 def get_divs(self, config, storage) -> Iterator[Tuple[str, str, HTMLBlock]]:
99 pass
koder aka kdanilov7f59d562016-12-26 01:34:23 +0200100
101
102# Cluster load over test time
103class ClusterLoad(Reporter):
104 """IOPS/latency during test"""
105
106
107# Node load over test time
108class NodeLoad(Reporter):
109 """IOPS/latency during test"""
110
111
112# Ceph cluster summary
113class CephClusterSummary(Reporter):
114 """IOPS/latency during test"""
115
116
117# TODO: Resource consumption report
118# TODO: Ceph operation breakout report
119# TODO: Resource consumption for different type of test
120
121
koder aka kdanilov70227062016-11-26 23:23:21 +0200122#
123# # disk_info = None
124# # base = None
125# # linearity = None
126#
127#
128# def group_by_name(test_data):
129# name_map = collections.defaultdict(lambda: [])
130#
131# for data in test_data:
132# name_map[(data.name, data.summary())].append(data)
133#
134# return name_map
135#
136#
137# def report(name, required_fields):
138# def closure(func):
139# report_funcs.append((required_fields.split(","), name, func))
140# return func
141# return closure
142#
143#
144# def get_test_lcheck_params(pinfo):
145# res = [{
146# 's': 'sync',
147# 'd': 'direct',
148# 'a': 'async',
149# 'x': 'sync direct'
150# }[pinfo.sync_mode]]
151#
152# res.append(pinfo.p.rw)
153#
154# return " ".join(res)
155#
156#
157# def get_emb_data_svg(plt):
158# sio = StringIO()
159# plt.savefig(sio, format='svg')
160# img_start = "<!-- Created with matplotlib (http://matplotlib.org/) -->"
161# return sio.getvalue().split(img_start, 1)[1]
162#
163#
164# def get_template(templ_name):
165# very_root_dir = os.path.dirname(os.path.dirname(wally.__file__))
166# templ_dir = os.path.join(very_root_dir, 'report_templates')
167# templ_file = os.path.join(templ_dir, templ_name)
168# return open(templ_file, 'r').read()
169#
170#
171# def group_by(data, func):
172# if len(data) < 2:
173# yield data
174# return
175#
176# ndata = [(func(dt), dt) for dt in data]
177# ndata.sort(key=func)
178# pkey, dt = ndata[0]
179# curr_list = [dt]
180#
181# for key, val in ndata[1:]:
182# if pkey != key:
183# yield curr_list
184# curr_list = [val]
185# else:
186# curr_list.append(val)
187# pkey = key
188#
189# yield curr_list
190#
191#
192# @report('linearity', 'linearity_test')
193# def linearity_report(processed_results, lab_info, comment):
194# labels_and_data_mp = collections.defaultdict(lambda: [])
195# vls = {}
196#
197# # plot io_time = func(bsize)
198# for res in processed_results.values():
199# if res.name.startswith('linearity_test'):
200# iotimes = [1000. / val for val in res.iops.raw]
201#
202# op_summ = get_test_summary(res.params)[:3]
203#
204# labels_and_data_mp[op_summ].append(
205# [res.p.blocksize, res.iops.raw, iotimes])
206#
207# cvls = res.params.vals.copy()
208# del cvls['blocksize']
209# del cvls['rw']
210#
211# cvls.pop('sync', None)
212# cvls.pop('direct', None)
213# cvls.pop('buffered', None)
214#
215# if op_summ not in vls:
216# vls[op_summ] = cvls
217# else:
218# assert cvls == vls[op_summ]
219#
220# all_labels = None
221# _, ax1 = plt.subplots()
222# for name, labels_and_data in labels_and_data_mp.items():
223# labels_and_data.sort(key=lambda x: ssize2b(x[0]))
224#
225# labels, _, iotimes = zip(*labels_and_data)
226#
227# if all_labels is None:
228# all_labels = labels
229# else:
230# assert all_labels == labels
231#
232# plt.boxplot(iotimes)
233# if len(labels_and_data) > 2 and \
234# ssize2b(labels_and_data[-2][0]) >= 4096:
235#
236# xt = range(1, len(labels) + 1)
237#
238# def io_time(sz, bw, initial_lat):
239# return sz / bw + initial_lat
240#
241# x = numpy.array(map(ssize2b, labels))
242# y = numpy.array([sum(dt) / len(dt) for dt in iotimes])
243# popt, _ = scipy.optimize.curve_fit(io_time, x, y, p0=(100., 1.))
244#
245# y1 = io_time(x, *popt)
246# plt.plot(xt, y1, linestyle='--',
247# label=name + ' LS linear approx')
248#
249# for idx, (sz, _, _) in enumerate(labels_and_data):
250# if ssize2b(sz) >= 4096:
251# break
252#
253# bw = (x[-1] - x[idx]) / (y[-1] - y[idx])
254# lat = y[-1] - x[-1] / bw
255# y2 = io_time(x, bw, lat)
256# plt.plot(xt, y2, linestyle='--',
257# label=abbv_name_to_full(name) +
258# ' (4k & max) linear approx')
259#
260# plt.setp(ax1, xticklabels=labels)
261#
262# plt.xlabel("Block size")
263# plt.ylabel("IO time, ms")
264#
265# plt.subplots_adjust(top=0.85)
266# plt.legend(bbox_to_anchor=(0.5, 1.15),
267# loc='upper center',
268# prop={'size': 10}, ncol=2)
269# plt.grid()
270# iotime_plot = get_emb_data_svg(plt)
271# plt.clf()
272#
273# # plot IOPS = func(bsize)
274# _, ax1 = plt.subplots()
275#
276# for name, labels_and_data in labels_and_data_mp.items():
277# labels_and_data.sort(key=lambda x: ssize2b(x[0]))
278# _, data, _ = zip(*labels_and_data)
279# plt.boxplot(data)
280# avg = [float(sum(arr)) / len(arr) for arr in data]
281# xt = range(1, len(data) + 1)
282# plt.plot(xt, avg, linestyle='--',
283# label=abbv_name_to_full(name) + " avg")
284#
285# plt.setp(ax1, xticklabels=labels)
286# plt.xlabel("Block size")
287# plt.ylabel("IOPS")
288# plt.legend(bbox_to_anchor=(0.5, 1.15),
289# loc='upper center',
290# prop={'size': 10}, ncol=2)
291# plt.grid()
292# plt.subplots_adjust(top=0.85)
293#
294# iops_plot = get_emb_data_svg(plt)
295#
296# res = set(get_test_lcheck_params(res) for res in processed_results.values())
297# ncount = list(set(res.testnodes_count for res in processed_results.values()))
298# conc = list(set(res.concurence for res in processed_results.values()))
299#
300# assert len(conc) == 1
301# assert len(ncount) == 1
302#
303# descr = {
304# 'vm_count': ncount[0],
305# 'concurence': conc[0],
306# 'oper_descr': ", ".join(res).capitalize()
307# }
308#
309# params_map = {'iotime_vs_size': iotime_plot,
310# 'iops_vs_size': iops_plot,
311# 'descr': descr}
312#
313# return get_template('report_linearity.html').format(**params_map)
314#
315#
316# @report('lat_vs_iops', 'lat_vs_iops')
317# def lat_vs_iops(processed_results, lab_info, comment):
318# lat_iops = collections.defaultdict(lambda: [])
319# requsted_vs_real = collections.defaultdict(lambda: {})
320#
321# for res in processed_results.values():
322# if res.name.startswith('lat_vs_iops'):
323# lat_iops[res.concurence].append((res.lat,
324# 0,
325# res.iops.average,
326# res.iops.deviation))
327# # lat_iops[res.concurence].append((res.lat.average / 1000.0,
328# # res.lat.deviation / 1000.0,
329# # res.iops.average,
330# # res.iops.deviation))
331# requested_iops = res.p.rate_iops * res.concurence
332# requsted_vs_real[res.concurence][requested_iops] = \
333# (res.iops.average, res.iops.deviation)
334#
335# colors = ['red', 'green', 'blue', 'orange', 'magenta', "teal"]
336# colors_it = iter(colors)
337# for conc, lat_iops in sorted(lat_iops.items()):
338# lat, dev, iops, iops_dev = zip(*lat_iops)
339# plt.errorbar(iops, lat, xerr=iops_dev, yerr=dev, fmt='ro',
340# label=str(conc) + " threads",
341# color=next(colors_it))
342#
343# plt.xlabel("IOPS")
344# plt.ylabel("Latency, ms")
345# plt.grid()
346# plt.legend(loc=0)
347# plt_iops_vs_lat = get_emb_data_svg(plt)
348# plt.clf()
349#
350# colors_it = iter(colors)
351# for conc, req_vs_real in sorted(requsted_vs_real.items()):
352# req, real = zip(*sorted(req_vs_real.items()))
353# iops, dev = zip(*real)
354# plt.errorbar(req, iops, yerr=dev, fmt='ro',
355# label=str(conc) + " threads",
356# color=next(colors_it))
357# plt.xlabel("Requested IOPS")
358# plt.ylabel("Get IOPS")
359# plt.grid()
360# plt.legend(loc=0)
361# plt_iops_vs_requested = get_emb_data_svg(plt)
362#
363# res1 = processed_results.values()[0]
364# params_map = {'iops_vs_lat': plt_iops_vs_lat,
365# 'iops_vs_requested': plt_iops_vs_requested,
366# 'oper_descr': get_test_lcheck_params(res1).capitalize()}
367#
368# return get_template('report_iops_vs_lat.html').format(**params_map)
369#
370#
371# def render_all_html(comment, info, lab_description, images, templ_name):
372# data = info.__dict__.copy()
373# for name, val in data.items():
374# if not name.startswith('__'):
375# if val is None:
376# if name in ('direct_iops_w64_max', 'direct_iops_w_max'):
377# data[name] = ('-', '-', '-')
378# else:
379# data[name] = '-'
380# elif isinstance(val, (int, float, long)):
381# data[name] = round_3_digit(val)
382#
383# data['bw_read_max'] = (data['bw_read_max'][0] // 1024,
384# data['bw_read_max'][1],
385# data['bw_read_max'][2])
386#
387# data['bw_write_max'] = (data['bw_write_max'][0] // 1024,
388# data['bw_write_max'][1],
389# data['bw_write_max'][2])
390#
391# images.update(data)
392# templ = get_template(templ_name)
393# return templ.format(lab_info=lab_description,
394# comment=comment,
395# **images)
396#
397#
398# def io_chart(title, concurence,
399# latv, latv_min, latv_max,
400# iops_or_bw, iops_or_bw_err,
401# legend,
402# log_iops=False,
403# log_lat=False,
404# boxplots=False,
405# latv_50=None,
406# latv_95=None,
407# error2=None):
408#
409# matplotlib.rcParams.update({'font.size': 10})
410# points = " MiBps" if legend == 'BW' else ""
411# lc = len(concurence)
412# width = 0.35
413# xt = range(1, lc + 1)
414#
415# op_per_vm = [v / (vm * th) for v, (vm, th) in zip(iops_or_bw, concurence)]
416# fig, p1 = plt.subplots()
417# xpos = [i - width / 2 for i in xt]
418#
419# p1.bar(xpos, iops_or_bw,
420# width=width,
421# color='y',
422# label=legend)
423#
424# err1_leg = None
425# for pos, y, err in zip(xpos, iops_or_bw, iops_or_bw_err):
426# err1_leg = p1.errorbar(pos + width / 2,
427# y,
428# err,
429# color='magenta')
430#
431# err2_leg = None
432# if error2 is not None:
433# for pos, y, err in zip(xpos, iops_or_bw, error2):
434# err2_leg = p1.errorbar(pos + width / 2 + 0.08,
435# y,
436# err,
437# lw=2,
438# alpha=0.5,
439# color='teal')
440#
441# p1.grid(True)
442# p1.plot(xt, op_per_vm, '--', label=legend + "/thread", color='black')
443# handles1, labels1 = p1.get_legend_handles_labels()
444#
445# handles1 += [err1_leg]
446# labels1 += ["95% conf"]
447#
448# if err2_leg is not None:
449# handles1 += [err2_leg]
450# labels1 += ["95% dev"]
451#
452# p2 = p1.twinx()
453#
454# if latv_50 is None:
455# p2.plot(xt, latv_max, label="lat max")
456# p2.plot(xt, latv, label="lat avg")
457# p2.plot(xt, latv_min, label="lat min")
458# else:
459# p2.plot(xt, latv_50, label="lat med")
460# p2.plot(xt, latv_95, label="lat 95%")
461#
462# plt.xlim(0.5, lc + 0.5)
463# plt.xticks(xt, ["{0} * {1}".format(vm, th) for (vm, th) in concurence])
464# p1.set_xlabel("VM Count * Thread per VM")
465# p1.set_ylabel(legend + points)
466# p2.set_ylabel("Latency ms")
467# plt.title(title)
468# handles2, labels2 = p2.get_legend_handles_labels()
469#
470# plt.legend(handles1 + handles2, labels1 + labels2,
471# loc='center left', bbox_to_anchor=(1.1, 0.81))
472#
473# if log_iops:
474# p1.set_yscale('log')
475#
476# if log_lat:
477# p2.set_yscale('log')
478#
479# plt.subplots_adjust(right=0.68)
480#
481# return get_emb_data_svg(plt)
482#
483#
484# def make_plots(processed_results, plots):
485# """
486# processed_results: [PerfInfo]
487# plots = [(test_name_prefix:str, fname:str, description:str)]
488# """
489# files = {}
490# for name_pref, fname, desc in plots:
491# chart_data = []
492#
493# for res in processed_results:
494# summ = res.name + "_" + res.summary
495# if summ.startswith(name_pref):
496# chart_data.append(res)
497#
498# if len(chart_data) == 0:
499# raise ValueError("Can't found any date for " + name_pref)
500#
501# use_bw = ssize2b(chart_data[0].p.blocksize) > 16 * 1024
502#
503# chart_data.sort(key=lambda x: x.params['vals']['numjobs'])
504#
505# lat = None
506# lat_min = None
507# lat_max = None
508#
509# lat_50 = [x.lat_50 for x in chart_data]
510# lat_95 = [x.lat_95 for x in chart_data]
511#
512# lat_diff_max = max(x.lat_95 / x.lat_50 for x in chart_data)
513# lat_log_scale = (lat_diff_max > 10)
514#
515# testnodes_count = x.testnodes_count
516# concurence = [(testnodes_count, x.concurence)
517# for x in chart_data]
518#
519# if use_bw:
520# data = [x.bw.average / 1000 for x in chart_data]
521# data_conf = [x.bw.confidence / 1000 for x in chart_data]
522# data_dev = [x.bw.deviation * 2.5 / 1000 for x in chart_data]
523# name = "BW"
524# else:
525# data = [x.iops.average for x in chart_data]
526# data_conf = [x.iops.confidence for x in chart_data]
527# data_dev = [x.iops.deviation * 2 for x in chart_data]
528# name = "IOPS"
529#
530# fc = io_chart(title=desc,
531# concurence=concurence,
532#
533# latv=lat,
534# latv_min=lat_min,
535# latv_max=lat_max,
536#
537# iops_or_bw=data,
538# iops_or_bw_err=data_conf,
539#
540# legend=name,
541# log_lat=lat_log_scale,
542#
543# latv_50=lat_50,
544# latv_95=lat_95,
545#
546# error2=data_dev)
547# files[fname] = fc
548#
549# return files
550#
551#
552# def find_max_where(processed_results, sync_mode, blocksize, rw, iops=True):
553# result = None
554# attr = 'iops' if iops else 'bw'
555# for measurement in processed_results:
556# ok = measurement.sync_mode == sync_mode
557# ok = ok and (measurement.p.blocksize == blocksize)
558# ok = ok and (measurement.p.rw == rw)
559#
560# if ok:
561# field = getattr(measurement, attr)
562#
563# if result is None:
564# result = field
565# elif field.average > result.average:
566# result = field
567#
568# return result
569#
570#
571# def get_disk_info(processed_results):
572# di = DiskInfo()
573# di.direct_iops_w_max = find_max_where(processed_results,
574# 'd', '4k', 'randwrite')
575# di.direct_iops_r_max = find_max_where(processed_results,
576# 'd', '4k', 'randread')
577#
578# di.direct_iops_w64_max = find_max_where(processed_results,
579# 'd', '64k', 'randwrite')
580#
581# for sz in ('16m', '64m'):
582# di.bw_write_max = find_max_where(processed_results,
583# 'd', sz, 'randwrite', False)
584# if di.bw_write_max is not None:
585# break
586#
587# if di.bw_write_max is None:
588# for sz in ('1m', '2m', '4m', '8m'):
589# di.bw_write_max = find_max_where(processed_results,
590# 'd', sz, 'write', False)
591# if di.bw_write_max is not None:
592# break
593#
594# for sz in ('16m', '64m'):
595# di.bw_read_max = find_max_where(processed_results,
596# 'd', sz, 'randread', False)
597# if di.bw_read_max is not None:
598# break
599#
600# if di.bw_read_max is None:
601# di.bw_read_max = find_max_where(processed_results,
602# 'd', '1m', 'read', False)
603#
604# rws4k_iops_lat_th = []
605# for res in processed_results:
606# if res.sync_mode in 'xs' and res.p.blocksize == '4k':
607# if res.p.rw != 'randwrite':
608# continue
609# rws4k_iops_lat_th.append((res.iops.average,
610# res.lat,
611# # res.lat.average,
612# res.concurence))
613#
614# rws4k_iops_lat_th.sort(key=lambda x: x[2])
615#
616# latv = [lat for _, lat, _ in rws4k_iops_lat_th]
617#
618# for tlat in [10, 30, 100]:
619# pos = bisect.bisect_left(latv, tlat)
620# if 0 == pos:
621# setattr(di, 'rws4k_{}ms'.format(tlat), 0)
622# elif pos == len(latv):
623# iops3, _, _ = rws4k_iops_lat_th[-1]
624# iops3 = int(round_3_digit(iops3))
625# setattr(di, 'rws4k_{}ms'.format(tlat), ">=" + str(iops3))
626# else:
627# lat1 = latv[pos - 1]
628# lat2 = latv[pos]
629#
630# iops1, _, th1 = rws4k_iops_lat_th[pos - 1]
631# iops2, _, th2 = rws4k_iops_lat_th[pos]
632#
633# th_lat_coef = (th2 - th1) / (lat2 - lat1)
634# th3 = th_lat_coef * (tlat - lat1) + th1
635#
636# th_iops_coef = (iops2 - iops1) / (th2 - th1)
637# iops3 = th_iops_coef * (th3 - th1) + iops1
638# iops3 = int(round_3_digit(iops3))
639# setattr(di, 'rws4k_{}ms'.format(tlat), iops3)
640#
641# hdi = DiskInfo()
642#
643# def pp(x):
644# med, conf = x.rounded_average_conf()
645# conf_perc = int(float(conf) / med * 100)
646# dev_perc = int(float(x.deviation) / med * 100)
647# return (round_3_digit(med), conf_perc, dev_perc)
648#
649# hdi.direct_iops_r_max = pp(di.direct_iops_r_max)
650#
651# if di.direct_iops_w_max is not None:
652# hdi.direct_iops_w_max = pp(di.direct_iops_w_max)
653# else:
654# hdi.direct_iops_w_max = None
655#
656# if di.direct_iops_w64_max is not None:
657# hdi.direct_iops_w64_max = pp(di.direct_iops_w64_max)
658# else:
659# hdi.direct_iops_w64_max = None
660#
661# hdi.bw_write_max = pp(di.bw_write_max)
662# hdi.bw_read_max = pp(di.bw_read_max)
663#
664# hdi.rws4k_10ms = di.rws4k_10ms if 0 != di.rws4k_10ms else None
665# hdi.rws4k_30ms = di.rws4k_30ms if 0 != di.rws4k_30ms else None
666# hdi.rws4k_100ms = di.rws4k_100ms if 0 != di.rws4k_100ms else None
667# return hdi
668#
669#
670# @report('hdd', 'hdd')
671# def make_hdd_report(processed_results, lab_info, comment):
672# plots = [
673# ('hdd_rrd4k', 'rand_read_4k', 'Random read 4k direct IOPS'),
674# ('hdd_rwx4k', 'rand_write_4k', 'Random write 4k sync IOPS')
675# ]
676# perf_infos = [res.disk_perf_info() for res in processed_results]
677# images = make_plots(perf_infos, plots)
678# di = get_disk_info(perf_infos)
679# return render_all_html(comment, di, lab_info, images, "report_hdd.html")
680#
681#
682# @report('cinder_iscsi', 'cinder_iscsi')
683# def make_cinder_iscsi_report(processed_results, lab_info, comment):
684# plots = [
685# ('cinder_iscsi_rrd4k', 'rand_read_4k', 'Random read 4k direct IOPS'),
686# ('cinder_iscsi_rwx4k', 'rand_write_4k', 'Random write 4k sync IOPS')
687# ]
688# perf_infos = [res.disk_perf_info() for res in processed_results]
689# try:
690# images = make_plots(perf_infos, plots)
691# except ValueError:
692# plots = [
693# ('cinder_iscsi_rrd4k', 'rand_read_4k', 'Random read 4k direct IOPS'),
694# ('cinder_iscsi_rws4k', 'rand_write_4k', 'Random write 4k sync IOPS')
695# ]
696# images = make_plots(perf_infos, plots)
697# di = get_disk_info(perf_infos)
698#
699# return render_all_html(comment, di, lab_info, images, "report_cinder_iscsi.html")
700#
701#
702# @report('ceph', 'ceph')
703# def make_ceph_report(processed_results, lab_info, comment):
704# plots = [
705# ('ceph_rrd4k', 'rand_read_4k', 'Random read 4k direct IOPS'),
706# ('ceph_rws4k', 'rand_write_4k', 'Random write 4k sync IOPS'),
707# ('ceph_rrd16m', 'rand_read_16m', 'Random read 16m direct MiBps'),
708# ('ceph_rwd16m', 'rand_write_16m',
709# 'Random write 16m direct MiBps'),
710# ]
711#
712# perf_infos = [res.disk_perf_info() for res in processed_results]
713# images = make_plots(perf_infos, plots)
714# di = get_disk_info(perf_infos)
715# return render_all_html(comment, di, lab_info, images, "report_ceph.html")
716#
717#
718# @report('mixed', 'mixed')
719# def make_mixed_report(processed_results, lab_info, comment):
720# #
721# # IOPS(X% read) = 100 / ( X / IOPS_W + (100 - X) / IOPS_R )
722# #
723#
724# perf_infos = [res.disk_perf_info() for res in processed_results]
725# mixed = collections.defaultdict(lambda: [])
726#
727# is_ssd = False
728# for res in perf_infos:
729# if res.name.startswith('mixed'):
730# if res.name.startswith('mixed-ssd'):
731# is_ssd = True
732# mixed[res.concurence].append((res.p.rwmixread,
733# res.lat,
734# 0,
735# # res.lat.average / 1000.0,
736# # res.lat.deviation / 1000.0,
737# res.iops.average,
738# res.iops.deviation))
739#
740# if len(mixed) == 0:
741# raise ValueError("No mixed load found")
742#
743# fig, p1 = plt.subplots()
744# p2 = p1.twinx()
745#
746# colors = ['red', 'green', 'blue', 'orange', 'magenta', "teal"]
747# colors_it = iter(colors)
748# for conc, mix_lat_iops in sorted(mixed.items()):
749# mix_lat_iops = sorted(mix_lat_iops)
750# read_perc, lat, dev, iops, iops_dev = zip(*mix_lat_iops)
751# p1.errorbar(read_perc, iops, color=next(colors_it),
752# yerr=iops_dev, label=str(conc) + " th")
753#
754# p2.errorbar(read_perc, lat, color=next(colors_it),
755# ls='--', yerr=dev, label=str(conc) + " th lat")
756#
757# if is_ssd:
758# p1.set_yscale('log')
759# p2.set_yscale('log')
760#
761# p1.set_xlim(-5, 105)
762#
763# read_perc = set(read_perc)
764# read_perc.add(0)
765# read_perc.add(100)
766# read_perc = sorted(read_perc)
767#
768# plt.xticks(read_perc, map(str, read_perc))
769#
770# p1.grid(True)
771# p1.set_xlabel("% of reads")
772# p1.set_ylabel("Mixed IOPS")
773# p2.set_ylabel("Latency, ms")
774#
775# handles1, labels1 = p1.get_legend_handles_labels()
776# handles2, labels2 = p2.get_legend_handles_labels()
777# plt.subplots_adjust(top=0.85)
778# plt.legend(handles1 + handles2, labels1 + labels2,
779# bbox_to_anchor=(0.5, 1.15),
780# loc='upper center',
781# prop={'size': 12}, ncol=3)
782# plt.show()
783#
784#
785# def make_load_report(idx, results_dir, fname):
786# dpath = os.path.join(results_dir, "io_" + str(idx))
787# files = sorted(os.listdir(dpath))
788# gf = lambda x: "_".join(x.rsplit(".", 1)[0].split('_')[:3])
789#
790# for key, group in itertools.groupby(files, gf):
791# fname = os.path.join(dpath, key + ".fio")
792#
793# cfgs = list(parse_all_in_1(open(fname).read(), fname))
794#
795# fname = os.path.join(dpath, key + "_lat.log")
796#
797# curr = []
798# arrays = []
799#
800# with open(fname) as fd:
801# for offset, lat, _, _ in csv.reader(fd):
802# offset = int(offset)
803# lat = int(lat)
804# if len(curr) > 0 and curr[-1][0] > offset:
805# arrays.append(curr)
806# curr = []
807# curr.append((offset, lat))
808# arrays.append(curr)
809# conc = int(cfgs[0].vals.get('numjobs', 1))
810#
811# if conc != 5:
812# continue
813#
814# assert len(arrays) == len(cfgs) * conc
815#
816# garrays = [[(0, 0)] for _ in range(conc)]
817#
818# for offset in range(len(cfgs)):
819# for acc, new_arr in zip(garrays, arrays[offset * conc:(offset + 1) * conc]):
820# last = acc[-1][0]
821# for off, lat in new_arr:
822# acc.append((off / 1000. + last, lat / 1000.))
823#
824# for cfg, arr in zip(cfgs, garrays):
825# plt.plot(*zip(*arr[1:]))
826# plt.show()
827# exit(1)
828#
829#
830# def make_io_report(dinfo, comment, path, lab_info=None):
831# lab_info = {
832# "total_disk": "None",
833# "total_memory": "None",
834# "nodes_count": "None",
835# "processor_count": "None"
836# }
837#
838# try:
839# res_fields = sorted(v.name for v in dinfo)
840#
841# found = False
842# for fields, name, func in report_funcs:
843# for field in fields:
844# pos = bisect.bisect_left(res_fields, field)
845#
846# if pos == len(res_fields):
847# break
848#
849# if not res_fields[pos].startswith(field):
850# break
851# else:
852# found = True
853# hpath = path.format(name)
854#
855# try:
856# report = func(dinfo, lab_info, comment)
857# except:
858# logger.exception("Diring {0} report generation".format(name))
859# continue
860#
861# if report is not None:
862# try:
863# with open(hpath, "w") as fd:
864# fd.write(report)
865# except:
866# logger.exception("Diring saving {0} report".format(name))
867# continue
868# logger.info("Report {0} saved into {1}".format(name, hpath))
869# else:
870# logger.warning("No report produced by {0!r}".format(name))
871#
872# if not found:
873# logger.warning("No report generator found for this load")
874#
875# except Exception as exc:
876# import traceback
877# traceback.print_exc()
878# logger.error("Failed to generate html report:" + str(exc))
879#
880#
881# # @classmethod
882# # def prepare_data(cls, results) -> List[Dict[str, Any]]:
883# # """create a table with io performance report for console"""
884# #
885# # def key_func(data: FioRunResult) -> Tuple[str, str, str, str, int]:
886# # tpl = data.summary_tpl()
887# # return (data.name,
888# # tpl.oper,
889# # tpl.mode,
890# # ssize2b(tpl.bsize),
891# # int(tpl.th_count) * int(tpl.vm_count))
892# # res = []
893# #
894# # for item in sorted(results, key=key_func):
895# # test_dinfo = item.disk_perf_info()
896# # testnodes_count = len(item.config.nodes)
897# #
898# # iops, _ = test_dinfo.iops.rounded_average_conf()
899# #
900# # if test_dinfo.iops_sys is not None:
901# # iops_sys, iops_sys_conf = test_dinfo.iops_sys.rounded_average_conf()
902# # _, iops_sys_dev = test_dinfo.iops_sys.rounded_average_dev()
903# # iops_sys_per_vm = round_3_digit(iops_sys / testnodes_count)
904# # iops_sys = round_3_digit(iops_sys)
905# # else:
906# # iops_sys = None
907# # iops_sys_per_vm = None
908# # iops_sys_dev = None
909# # iops_sys_conf = None
910# #
911# # bw, bw_conf = test_dinfo.bw.rounded_average_conf()
912# # _, bw_dev = test_dinfo.bw.rounded_average_dev()
913# # conf_perc = int(round(bw_conf * 100 / bw))
914# # dev_perc = int(round(bw_dev * 100 / bw))
915# #
916# # lat_50 = round_3_digit(int(test_dinfo.lat_50))
917# # lat_95 = round_3_digit(int(test_dinfo.lat_95))
918# # lat_avg = round_3_digit(int(test_dinfo.lat_avg))
919# #
920# # iops_per_vm = round_3_digit(iops / testnodes_count)
921# # bw_per_vm = round_3_digit(bw / testnodes_count)
922# #
923# # iops = round_3_digit(iops)
924# # bw = round_3_digit(bw)
925# #
926# # summ = "{0.oper}{0.mode} {0.bsize:>4} {0.th_count:>3}th {0.vm_count:>2}vm".format(item.summary_tpl())
927# #
928# # res.append({"name": key_func(item)[0],
929# # "key": key_func(item)[:4],
930# # "summ": summ,
931# # "iops": int(iops),
932# # "bw": int(bw),
933# # "conf": str(conf_perc),
934# # "dev": str(dev_perc),
935# # "iops_per_vm": int(iops_per_vm),
936# # "bw_per_vm": int(bw_per_vm),
937# # "lat_50": lat_50,
938# # "lat_95": lat_95,
939# # "lat_avg": lat_avg,
940# #
941# # "iops_sys": iops_sys,
942# # "iops_sys_per_vm": iops_sys_per_vm,
943# # "sys_conf": iops_sys_conf,
944# # "sys_dev": iops_sys_dev})
945# #
946# # return res
947# #
948# # Field = collections.namedtuple("Field", ("header", "attr", "allign", "size"))
949# # fiels_and_header = [
950# # Field("Name", "name", "l", 7),
951# # Field("Description", "summ", "l", 19),
952# # Field("IOPS\ncum", "iops", "r", 3),
953# # # Field("IOPS_sys\ncum", "iops_sys", "r", 3),
954# # Field("KiBps\ncum", "bw", "r", 6),
955# # Field("Cnf %\n95%", "conf", "r", 3),
956# # Field("Dev%", "dev", "r", 3),
957# # Field("iops\n/vm", "iops_per_vm", "r", 3),
958# # Field("KiBps\n/vm", "bw_per_vm", "r", 6),
959# # Field("lat ms\nmedian", "lat_50", "r", 3),
960# # Field("lat ms\n95%", "lat_95", "r", 3),
961# # Field("lat\navg", "lat_avg", "r", 3),
962# # ]
963# #
964# # fiels_and_header_dct = dict((item.attr, item) for item in fiels_and_header)
965# #
966# # @classmethod
967# # def format_for_console(cls, results) -> str:
968# # """create a table with io performance report for console"""
969# #
970# # tab = texttable.Texttable(max_width=120)
971# # tab.set_deco(tab.HEADER | tab.VLINES | tab.BORDER)
972# # tab.set_cols_align([f.allign for f in cls.fiels_and_header])
973# # sep = ["-" * f.size for f in cls.fiels_and_header]
974# # tab.header([f.header for f in cls.fiels_and_header])
975# # prev_k = None
976# # for item in cls.prepare_data(results):
977# # if prev_k is not None:
978# # if prev_k != item["key"]:
979# # tab.add_row(sep)
980# #
981# # prev_k = item["key"]
982# # tab.add_row([item[f.attr] for f in cls.fiels_and_header])
983# #
984# # return tab.draw()
985# #
986# # @classmethod
987# # def format_diff_for_console(cls, list_of_results: List[Any]) -> str:
988# # """create a table with io performance report for console"""
989# #
990# # tab = texttable.Texttable(max_width=200)
991# # tab.set_deco(tab.HEADER | tab.VLINES | tab.BORDER)
992# #
993# # header = [
994# # cls.fiels_and_header_dct["name"].header,
995# # cls.fiels_and_header_dct["summ"].header,
996# # ]
997# # allign = ["l", "l"]
998# #
999# # header.append("IOPS ~ Cnf% ~ Dev%")
1000# # allign.extend(["r"] * len(list_of_results))
1001# # header.extend(
1002# # "IOPS_{0} %".format(i + 2) for i in range(len(list_of_results[1:]))
1003# # )
1004# #
1005# # header.append("BW")
1006# # allign.extend(["r"] * len(list_of_results))
1007# # header.extend(
1008# # "BW_{0} %".format(i + 2) for i in range(len(list_of_results[1:]))
1009# # )
1010# #
1011# # header.append("LAT")
1012# # allign.extend(["r"] * len(list_of_results))
1013# # header.extend(
1014# # "LAT_{0}".format(i + 2) for i in range(len(list_of_results[1:]))
1015# # )
1016# #
1017# # tab.header(header)
1018# # sep = ["-" * 3] * len(header)
1019# # processed_results = map(cls.prepare_data, list_of_results)
1020# #
1021# # key2results = []
1022# # for res in processed_results:
1023# # key2results.append(dict(
1024# # ((item["name"], item["summ"]), item) for item in res
1025# # ))
1026# #
1027# # prev_k = None
1028# # iops_frmt = "{0[iops]} ~ {0[conf]:>2} ~ {0[dev]:>2}"
1029# # for item in processed_results[0]:
1030# # if prev_k is not None:
1031# # if prev_k != item["key"]:
1032# # tab.add_row(sep)
1033# #
1034# # prev_k = item["key"]
1035# #
1036# # key = (item['name'], item['summ'])
1037# # line = list(key)
1038# # base = key2results[0][key]
1039# #
1040# # line.append(iops_frmt.format(base))
1041# #
1042# # for test_results in key2results[1:]:
1043# # val = test_results.get(key)
1044# # if val is None:
1045# # line.append("-")
1046# # elif base['iops'] == 0:
1047# # line.append("Nan")
1048# # else:
1049# # prc_val = {'dev': val['dev'], 'conf': val['conf']}
1050# # prc_val['iops'] = int(100 * val['iops'] / base['iops'])
1051# # line.append(iops_frmt.format(prc_val))
1052# #
1053# # line.append(base['bw'])
1054# #
1055# # for test_results in key2results[1:]:
1056# # val = test_results.get(key)
1057# # if val is None:
1058# # line.append("-")
1059# # elif base['bw'] == 0:
1060# # line.append("Nan")
1061# # else:
1062# # line.append(int(100 * val['bw'] / base['bw']))
1063# #
1064# # for test_results in key2results:
1065# # val = test_results.get(key)
1066# # if val is None:
1067# # line.append("-")
1068# # else:
1069# # line.append("{0[lat_50]} - {0[lat_95]}".format(val))
1070# #
1071# # tab.add_row(line)
1072# #
1073# # tab.set_cols_align(allign)
1074# # return tab.draw()
1075#
1076#
1077# # READ_IOPS_DISCSTAT_POS = 3
1078# # WRITE_IOPS_DISCSTAT_POS = 7
1079# #
1080# #
1081# # def load_sys_log_file(ftype: str, fname: str) -> TimeSeriesValue:
1082# # assert ftype == 'iops'
1083# # pval = None
1084# # with open(fname) as fd:
1085# # iops = []
1086# # for ln in fd:
1087# # params = ln.split()
1088# # cval = int(params[WRITE_IOPS_DISCSTAT_POS]) + \
1089# # int(params[READ_IOPS_DISCSTAT_POS])
1090# # if pval is not None:
1091# # iops.append(cval - pval)
1092# # pval = cval
1093# #
1094# # vals = [(idx * 1000, val) for idx, val in enumerate(iops)]
1095# # return TimeSeriesValue(vals)
1096# #
1097# #
1098# # def load_test_results(folder: str, run_num: int) -> 'FioRunResult':
1099# # res = {}
1100# # params = None
1101# #
1102# # fn = os.path.join(folder, str(run_num) + '_params.yaml')
1103# # params = yaml.load(open(fn).read())
1104# #
1105# # conn_ids_set = set()
1106# # rr = r"{}_(?P<conn_id>.*?)_(?P<type>[^_.]*)\.\d+\.log$".format(run_num)
1107# # for fname in os.listdir(folder):
1108# # rm = re.match(rr, fname)
1109# # if rm is None:
1110# # continue
1111# #
1112# # conn_id_s = rm.group('conn_id')
1113# # conn_id = conn_id_s.replace('_', ':')
1114# # ftype = rm.group('type')
1115# #
1116# # if ftype not in ('iops', 'bw', 'lat'):
1117# # continue
1118# #
1119# # ts = load_fio_log_file(os.path.join(folder, fname))
1120# # res.setdefault(ftype, {}).setdefault(conn_id, []).append(ts)
1121# #
1122# # conn_ids_set.add(conn_id)
1123# #
1124# # rr = r"{}_(?P<conn_id>.*?)_(?P<type>[^_.]*)\.sys\.log$".format(run_num)
1125# # for fname in os.listdir(folder):
1126# # rm = re.match(rr, fname)
1127# # if rm is None:
1128# # continue
1129# #
1130# # conn_id_s = rm.group('conn_id')
1131# # conn_id = conn_id_s.replace('_', ':')
1132# # ftype = rm.group('type')
1133# #
1134# # if ftype not in ('iops', 'bw', 'lat'):
1135# # continue
1136# #
1137# # ts = load_sys_log_file(ftype, os.path.join(folder, fname))
1138# # res.setdefault(ftype + ":sys", {}).setdefault(conn_id, []).append(ts)
1139# #
1140# # conn_ids_set.add(conn_id)
1141# #
1142# # mm_res = {}
1143# #
1144# # if len(res) == 0:
1145# # raise ValueError("No data was found")
1146# #
1147# # for key, data in res.items():
1148# # conn_ids = sorted(conn_ids_set)
1149# # awail_ids = [conn_id for conn_id in conn_ids if conn_id in data]
1150# # matr = [data[conn_id] for conn_id in awail_ids]
1151# # mm_res[key] = MeasurementMatrix(matr, awail_ids)
1152# #
1153# # raw_res = {}
1154# # for conn_id in conn_ids:
1155# # fn = os.path.join(folder, "{0}_{1}_rawres.json".format(run_num, conn_id_s))
1156# #
1157# # # remove message hack
1158# # fc = "{" + open(fn).read().split('{', 1)[1]
1159# # raw_res[conn_id] = json.loads(fc)
1160# #
1161# # fio_task = FioJobSection(params['name'])
1162# # fio_task.vals.update(params['vals'])
1163# #
1164# # config = TestConfig('io', params, None, params['nodes'], folder, None)
1165# # return FioRunResult(config, fio_task, mm_res, raw_res, params['intervals'], run_num)
1166# #
1167#
1168# # class DiskPerfInfo:
1169# # def __init__(self, name: str, summary: str, params: Dict[str, Any], testnodes_count: int) -> None:
1170# # self.name = name
1171# # self.bw = None
1172# # self.iops = None
1173# # self.lat = None
1174# # self.lat_50 = None
1175# # self.lat_95 = None
1176# # self.lat_avg = None
1177# #
1178# # self.raw_bw = []
1179# # self.raw_iops = []
1180# # self.raw_lat = []
1181# #
1182# # self.params = params
1183# # self.testnodes_count = testnodes_count
1184# # self.summary = summary
1185# #
1186# # self.sync_mode = get_test_sync_mode(self.params['vals'])
1187# # self.concurence = self.params['vals'].get('numjobs', 1)
1188# #
1189# #
1190# # class IOTestResults:
1191# # def __init__(self, suite_name: str, fio_results: 'FioRunResult', log_directory: str):
1192# # self.suite_name = suite_name
1193# # self.fio_results = fio_results
1194# # self.log_directory = log_directory
1195# #
1196# # def __iter__(self):
1197# # return iter(self.fio_results)
1198# #
1199# # def __len__(self):
1200# # return len(self.fio_results)
1201# #
1202# # def get_yamable(self) -> Dict[str, List[str]]:
1203# # items = [(fio_res.summary(), fio_res.idx) for fio_res in self]
1204# # return {self.suite_name: [self.log_directory] + items}
1205#
1206#
1207# # class FioRunResult(TestResults):
1208# # """
1209# # Fio run results
1210# # config: TestConfig
1211# # fio_task: FioJobSection
1212# # ts_results: {str: MeasurementMatrix[TimeSeriesValue]}
1213# # raw_result: ????
1214# # run_interval:(float, float) - test tun time, used for sensors
1215# # """
1216# # def __init__(self, config, fio_task, ts_results, raw_result, run_interval, idx):
1217# #
1218# # self.name = fio_task.name.rsplit("_", 1)[0]
1219# # self.fio_task = fio_task
1220# # self.idx = idx
1221# #
1222# # self.bw = ts_results['bw']
1223# # self.lat = ts_results['lat']
1224# # self.iops = ts_results['iops']
1225# #
1226# # if 'iops:sys' in ts_results:
1227# # self.iops_sys = ts_results['iops:sys']
1228# # else:
1229# # self.iops_sys = None
1230# #
1231# # res = {"bw": self.bw,
1232# # "lat": self.lat,
1233# # "iops": self.iops,
1234# # "iops:sys": self.iops_sys}
1235# #
1236# # self.sensors_data = None
1237# # self._pinfo = None
1238# # TestResults.__init__(self, config, res, raw_result, run_interval)
1239# #
1240# # def get_params_from_fio_report(self):
1241# # nodes = self.bw.connections_ids
1242# #
1243# # iops = [self.raw_result[node]['jobs'][0]['mixed']['iops'] for node in nodes]
1244# # total_ios = [self.raw_result[node]['jobs'][0]['mixed']['total_ios'] for node in nodes]
1245# # runtime = [self.raw_result[node]['jobs'][0]['mixed']['runtime'] / 1000 for node in nodes]
1246# # flt_iops = [float(ios) / rtime for ios, rtime in zip(total_ios, runtime)]
1247# #
1248# # bw = [self.raw_result[node]['jobs'][0]['mixed']['bw'] for node in nodes]
1249# # total_bytes = [self.raw_result[node]['jobs'][0]['mixed']['io_bytes'] for node in nodes]
1250# # flt_bw = [float(tbytes) / rtime for tbytes, rtime in zip(total_bytes, runtime)]
1251# #
1252# # return {'iops': iops,
1253# # 'flt_iops': flt_iops,
1254# # 'bw': bw,
1255# # 'flt_bw': flt_bw}
1256# #
1257# # def summary(self):
1258# # return get_test_summary(self.fio_task, len(self.config.nodes))
1259# #
1260# # def summary_tpl(self):
1261# # return get_test_summary_tuple(self.fio_task, len(self.config.nodes))
1262# #
1263# # def get_lat_perc_50_95_multy(self):
1264# # lat_mks = collections.defaultdict(lambda: 0)
1265# # num_res = 0
1266# #
1267# # for result in self.raw_result.values():
1268# # num_res += len(result['jobs'])
1269# # for job_info in result['jobs']:
1270# # for k, v in job_info['latency_ms'].items():
1271# # if isinstance(k, basestring) and k.startswith('>='):
1272# # lat_mks[int(k[2:]) * 1000] += v
1273# # else:
1274# # lat_mks[int(k) * 1000] += v
1275# #
1276# # for k, v in job_info['latency_us'].items():
1277# # lat_mks[int(k)] += v
1278# #
1279# # for k, v in lat_mks.items():
1280# # lat_mks[k] = float(v) / num_res
1281# # return get_lat_perc_50_95(lat_mks)
1282# #
1283# # def disk_perf_info(self, avg_interval=2.0):
1284# #
1285# # if self._pinfo is not None:
1286# # return self._pinfo
1287# #
1288# # testnodes_count = len(self.config.nodes)
1289# #
1290# # pinfo = DiskPerfInfo(self.name,
1291# # self.summary(),
1292# # self.params,
1293# # testnodes_count)
1294# #
1295# # def prepare(data, drop=1):
1296# # if data is None:
1297# # return data
1298# #
1299# # res = []
1300# # for ts_data in data:
1301# # if ts_data.average_interval() < avg_interval:
1302# # ts_data = ts_data.derived(avg_interval)
1303# #
1304# # # drop last value on bounds
1305# # # as they may contains ranges without activities
1306# # assert len(ts_data.values) >= drop + 1, str(drop) + " " + str(ts_data.values)
1307# #
1308# # if drop > 0:
1309# # res.append(ts_data.values[:-drop])
1310# # else:
1311# # res.append(ts_data.values)
1312# #
1313# # return res
1314# #
1315# # def agg_data(matr):
1316# # arr = sum(matr, [])
1317# # min_len = min(map(len, arr))
1318# # res = []
1319# # for idx in range(min_len):
1320# # res.append(sum(dt[idx] for dt in arr))
1321# # return res
1322# #
1323# # pinfo.raw_lat = map(prepare, self.lat.per_vm())
1324# # num_th = sum(map(len, pinfo.raw_lat))
1325# # lat_avg = [val / num_th for val in agg_data(pinfo.raw_lat)]
1326# # pinfo.lat_avg = data_property(lat_avg).average / 1000 # us to ms
1327# #
1328# # pinfo.lat_50, pinfo.lat_95 = self.get_lat_perc_50_95_multy()
1329# # pinfo.lat = pinfo.lat_50
1330# #
1331# # pinfo.raw_bw = map(prepare, self.bw.per_vm())
1332# # pinfo.raw_iops = map(prepare, self.iops.per_vm())
1333# #
1334# # if self.iops_sys is not None:
1335# # pinfo.raw_iops_sys = map(prepare, self.iops_sys.per_vm())
1336# # pinfo.iops_sys = data_property(agg_data(pinfo.raw_iops_sys))
1337# # else:
1338# # pinfo.raw_iops_sys = None
1339# # pinfo.iops_sys = None
1340# #
1341# # fparams = self.get_params_from_fio_report()
1342# # fio_report_bw = sum(fparams['flt_bw'])
1343# # fio_report_iops = sum(fparams['flt_iops'])
1344# #
1345# # agg_bw = agg_data(pinfo.raw_bw)
1346# # agg_iops = agg_data(pinfo.raw_iops)
1347# #
1348# # log_bw_avg = average(agg_bw)
1349# # log_iops_avg = average(agg_iops)
1350# #
1351# # # update values to match average from fio report
1352# # coef_iops = fio_report_iops / float(log_iops_avg)
1353# # coef_bw = fio_report_bw / float(log_bw_avg)
1354# #
1355# # bw_log = data_property([val * coef_bw for val in agg_bw])
1356# # iops_log = data_property([val * coef_iops for val in agg_iops])
1357# #
1358# # bw_report = data_property([fio_report_bw])
1359# # iops_report = data_property([fio_report_iops])
1360# #
1361# # # When IOPS/BW per thread is too low
1362# # # data from logs is rounded to match
1363# # iops_per_th = sum(sum(pinfo.raw_iops, []), [])
1364# # if average(iops_per_th) > 10:
1365# # pinfo.iops = iops_log
1366# # pinfo.iops2 = iops_report
1367# # else:
1368# # pinfo.iops = iops_report
1369# # pinfo.iops2 = iops_log
1370# #
1371# # bw_per_th = sum(sum(pinfo.raw_bw, []), [])
1372# # if average(bw_per_th) > 10:
1373# # pinfo.bw = bw_log
1374# # pinfo.bw2 = bw_report
1375# # else:
1376# # pinfo.bw = bw_report
1377# # pinfo.bw2 = bw_log
1378# #
1379# # self._pinfo = pinfo
1380# #
1381# # return pinfo
1382#
1383# # class TestResult:
1384# # """Hold all information for a given test - test info,
1385# # sensors data and performance results for test period from all nodes"""
1386# # run_id = None # type: int
1387# # test_info = None # type: Any
1388# # begin_time = None # type: int
1389# # end_time = None # type: int
1390# # sensors = None # Dict[Tuple[str, str, str], TimeSeries]
1391# # performance = None # Dict[Tuple[str, str], TimeSeries]
1392# #
1393# # class TestResults:
1394# # """
1395# # this class describe test results
1396# #
1397# # config:TestConfig - test config object
1398# # params:dict - parameters from yaml file for this test
1399# # results:{str:MeasurementMesh} - test results object
1400# # raw_result:Any - opaque object to store raw results
1401# # run_interval:(float, float) - test tun time, used for sensors
1402# # """
1403# #
1404# # def __init__(self,
1405# # config: TestConfig,
1406# # results: Dict[str, Any],
1407# # raw_result: Any,
1408# # run_interval: Tuple[float, float]) -> None:
1409# # self.config = config
1410# # self.params = config.params
1411# # self.results = results
1412# # self.raw_result = raw_result
1413# # self.run_interval = run_interval
1414# #
1415# # def __str__(self) -> str:
1416# # res = "{0}({1}):\n results:\n".format(
1417# # self.__class__.__name__,
1418# # self.summary())
1419# #
1420# # for name, val in self.results.items():
1421# # res += " {0}={1}\n".format(name, val)
1422# #
1423# # res += " params:\n"
1424# #
1425# # for name, val in self.params.items():
1426# # res += " {0}={1}\n".format(name, val)
1427# #
1428# # return res
1429# #
1430# # def summary(self) -> str:
1431# # raise NotImplementedError()
1432# # return ""
1433# #
1434# # def get_yamable(self) -> Any:
1435# # raise NotImplementedError()
1436# # return None
1437#
1438#
1439#
1440# # class MeasurementMatrix:
1441# # """
1442# # data:[[MeasurementResult]] - VM_COUNT x TH_COUNT matrix of MeasurementResult
1443# # """
1444# # def __init__(self, data, connections_ids):
1445# # self.data = data
1446# # self.connections_ids = connections_ids
1447# #
1448# # def per_vm(self):
1449# # return self.data
1450# #
1451# # def per_th(self):
1452# # return sum(self.data, [])
1453#
1454#
1455# # class MeasurementResults:
1456# # data = None # type: List[Any]
1457# #
1458# # def stat(self) -> StatProps:
1459# # return data_property(self.data)
1460# #
1461# # def __str__(self) -> str:
1462# # return 'TS([' + ", ".join(map(str, self.data)) + '])'
1463# #
1464# #
1465# # class SimpleVals(MeasurementResults):
1466# # """
1467# # data:[float] - list of values
1468# # """
1469# # def __init__(self, data: List[float]) -> None:
1470# # self.data = data
1471# #
1472# #
1473# # class TimeSeriesValue(MeasurementResults):
1474# # """
1475# # data:[(float, float, float)] - list of (start_time, lenght, average_value_for_interval)
1476# # odata: original values
1477# # """
1478# # def __init__(self, data: List[Tuple[float, float]]) -> None:
1479# # assert len(data) > 0
1480# # self.odata = data[:]
1481# # self.data = [] # type: List[Tuple[float, float, float]]
1482# #
1483# # cstart = 0.0
1484# # for nstart, nval in data:
1485# # self.data.append((cstart, nstart - cstart, nval))
1486# # cstart = nstart
1487# #
1488# # @property
1489# # def values(self) -> List[float]:
1490# # return [val[2] for val in self.data]
1491# #
1492# # def average_interval(self) -> float:
1493# # return float(sum([val[1] for val in self.data])) / len(self.data)
1494# #
1495# # def skip(self, seconds) -> 'TimeSeriesValue':
1496# # nres = []
1497# # for start, ln, val in self.data:
1498# # nstart = start + ln - seconds
1499# # if nstart > 0:
1500# # nres.append([nstart, val])
1501# # return self.__class__(nres)
1502# #
1503# # def derived(self, tdelta) -> 'TimeSeriesValue':
1504# # end = self.data[-1][0] + self.data[-1][1]
1505# # tdelta = float(tdelta)
1506# #
1507# # ln = end / tdelta
1508# #
1509# # if ln - int(ln) > 0:
1510# # ln += 1
1511# #
1512# # res = [[tdelta * i, 0.0] for i in range(int(ln))]
1513# #
1514# # for start, lenght, val in self.data:
1515# # start_idx = int(start / tdelta)
1516# # end_idx = int((start + lenght) / tdelta)
1517# #
1518# # for idx in range(start_idx, end_idx + 1):
1519# # rstart = tdelta * idx
1520# # rend = tdelta * (idx + 1)
1521# #
1522# # intersection_ln = min(rend, start + lenght) - max(start, rstart)
1523# # if intersection_ln > 0:
1524# # try:
1525# # res[idx][1] += val * intersection_ln / tdelta
1526# # except IndexError:
1527# # raise
1528# #
1529# # return self.__class__(res)
1530#
1531#
1532# def console_report_stage(ctx: TestRun) -> None:
1533# # TODO(koder): load data from storage
1534# raise NotImplementedError("...")
1535# # first_report = True
1536# # text_rep_fname = ctx.config.text_report_file
1537# #
1538# # with open(text_rep_fname, "w") as fd:
1539# # for tp, data in ctx.results.items():
1540# # if 'io' == tp and data is not None:
1541# # rep_lst = []
1542# # for result in data:
1543# # rep_lst.append(
1544# # IOPerfTest.format_for_console(list(result)))
1545# # rep = "\n\n".join(rep_lst)
1546# # elif tp in ['mysql', 'pgbench'] and data is not None:
1547# # rep = MysqlTest.format_for_console(data)
1548# # elif tp == 'omg':
1549# # rep = OmgTest.format_for_console(data)
1550# # else:
1551# # logger.warning("Can't generate text report for " + tp)
1552# # continue
1553# #
1554# # fd.write(rep)
1555# # fd.write("\n")
1556# #
1557# # if first_report:
1558# # logger.info("Text report were stored in " + text_rep_fname)
1559# # first_report = False
1560# #
1561# # print("\n" + rep + "\n")
1562#
1563#
1564# # def test_load_report_stage(cfg: Config, ctx: TestRun) -> None:
1565# # load_rep_fname = cfg.load_report_file
1566# # found = False
1567# # for idx, (tp, data) in enumerate(ctx.results.items()):
1568# # if 'io' == tp and data is not None:
1569# # if found:
1570# # logger.error("Making reports for more than one " +
1571# # "io block isn't supported! All " +
1572# # "report, except first are skipped")
1573# # continue
1574# # found = True
1575# # report.make_load_report(idx, cfg['results'], load_rep_fname)
1576# #
1577# #
1578#
1579# # def html_report_stage(ctx: TestRun) -> None:
1580# # TODO(koder): load data from storage
1581# # raise NotImplementedError("...")
1582# # html_rep_fname = cfg.html_report_file
1583# # found = False
1584# # for tp, data in ctx.results.items():
1585# # if 'io' == tp and data is not None:
1586# # if found or len(data) > 1:
1587# # logger.error("Making reports for more than one " +
1588# # "io block isn't supported! All " +
1589# # "report, except first are skipped")
1590# # continue
1591# # found = True
1592# # report.make_io_report(list(data[0]),
1593# # cfg.get('comment', ''),
1594# # html_rep_fname,
1595# # lab_info=ctx.nodes)
1596#
1597# #
1598# # def load_data_from_path(test_res_dir: str) -> Mapping[str, List[Any]]:
1599# # files = get_test_files(test_res_dir)
1600# # raw_res = yaml_load(open(files['raw_results']).read())
1601# # res = collections.defaultdict(list)
1602# #
1603# # for tp, test_lists in raw_res:
1604# # for tests in test_lists:
1605# # for suite_name, suite_data in tests.items():
1606# # result_folder = suite_data[0]
1607# # res[tp].append(TOOL_TYPE_MAPPER[tp].load(suite_name, result_folder))
1608# #
1609# # return res
1610# #
1611# #
1612# # def load_data_from_path_stage(var_dir: str, _, ctx: TestRun) -> None:
1613# # for tp, vals in load_data_from_path(var_dir).items():
1614# # ctx.results.setdefault(tp, []).extend(vals)
1615# #
1616# #
1617# # def load_data_from(var_dir: str) -> Callable[[TestRun], None]:
1618# # return functools.partial(load_data_from_path_stage, var_dir)