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