blob: 95e39bf069674961f2b9d665af47c5f2980b9c43 [file] [log] [blame]
Alex0989ecf2022-03-29 13:43:21 -05001# Author: Alex Savatieiev (osavatieiev@mirantis.com; a.savex@gmail.com)
2# Copyright 2019-2022 Mirantis, Inc.
Alex5cace3b2021-11-10 16:40:37 -06003import csv
4import os
5import json
6
Alexbdc72742021-12-23 13:26:05 -06007from copy import deepcopy
Alex3034ba52021-11-13 17:06:45 -06008from datetime import datetime, timedelta, timezone
Alex5cace3b2021-11-10 16:40:37 -06009
Alexdcb792f2021-10-04 14:24:21 -050010from cfg_checker.common import logger_cli
Alex3034ba52021-11-13 17:06:45 -060011from cfg_checker.common.decorators import retry
Alexb2129542021-11-23 15:49:42 -060012from cfg_checker.common.file_utils import write_str_to_file
Alexbfa947c2021-11-11 18:14:28 -060013from cfg_checker.helpers.console_utils import Progress
Alexe4de1142022-11-04 19:26:03 -050014from cfg_checker.helpers.console_utils import cl_typewriter
Alexb2129542021-11-23 15:49:42 -060015from cfg_checker.reports import reporter
Alexdcb792f2021-10-04 14:24:21 -050016# from cfg_checker.common.exception import InvalidReturnException
17# from cfg_checker.common.exception import ConfigException
18# from cfg_checker.common.exception import KubeException
19
20from cfg_checker.nodes import KubeNodes
Alex5cace3b2021-11-10 16:40:37 -060021from cfg_checker.agent.fio_runner import _get_seconds, _datetime_fmt
Alexdcb792f2021-10-04 14:24:21 -050022
23
Alex90ac1532021-12-09 11:13:14 -060024_file_datetime_fmt = "%m%d%Y%H%M%S%z"
25
26
Alexb2129542021-11-23 15:49:42 -060027def _reformat_timestr(_str, _chars=["/", ",", " ", ":", "+"], _tchar=""):
28 _new = ""
29 for _c in _str:
30 _new += _c if _c not in _chars else _tchar
31 return _new
32
33
34def _parse_json_output(buffer):
35 try:
36 return json.loads(buffer)
37 except TypeError as e:
38 logger_cli.error(
39 "ERROR: Status not decoded: {}\n{}".format(e, buffer)
40 )
41 except json.decoder.JSONDecodeError as e:
42 logger_cli.error(
43 "ERROR: Status not decoded: {}\n{}".format(e, buffer)
44 )
45 return {}
46
47
Alex30380a42021-12-20 16:11:20 -060048def _split_vol_size(size):
49 # I know, but it is faster then regex
50 _numbers = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57]
51 _s_int = "0"
52 _s_type = ""
53 for ch in size:
54 if ord(ch) in _numbers:
55 _s_int += ch
56 else:
57 _s_type += ch
58 return int(_s_int), _s_type
59
60
Alexdcb792f2021-10-04 14:24:21 -050061class CephBench(object):
Alex5cace3b2021-11-10 16:40:37 -060062 _agent_template = "cfgagent-template.yaml"
63
64 def __init__(self, config):
Alexdcb792f2021-10-04 14:24:21 -050065 self.env_config = config
66 return
67
Alexdcb792f2021-10-04 14:24:21 -050068
69class SaltCephBench(CephBench):
70 def __init__(
71 self,
72 config
73 ):
Alex5cace3b2021-11-10 16:40:37 -060074 logger_cli.error("ERROR: Not impelented for Salt environment!")
Alexdcb792f2021-10-04 14:24:21 -050075
76 # self.master = SaltNodes(config)
Alex5cace3b2021-11-10 16:40:37 -060077 super(SaltCephBench, self).__init__(config)
Alexdcb792f2021-10-04 14:24:21 -050078 return
79
80
81class KubeCephBench(CephBench):
82 def __init__(self, config):
Alex5cace3b2021-11-10 16:40:37 -060083 self.agent_count = config.bench_agent_count
Alexdcb792f2021-10-04 14:24:21 -050084 self.master = KubeNodes(config)
85 super(KubeCephBench, self).__init__(config)
Alexb2129542021-11-23 15:49:42 -060086
Alex5cace3b2021-11-10 16:40:37 -060087 self.mode = config.bench_mode
Alexb2129542021-11-23 15:49:42 -060088 self.resource_prefix = config.resource_prefix
Alex30380a42021-12-20 16:11:20 -060089
Alex5cace3b2021-11-10 16:40:37 -060090 if config.bench_mode == "tasks":
Alex3034ba52021-11-13 17:06:45 -060091 self.taskfile = config.bench_task_file
92 self.load_tasks(self.taskfile)
Alex30380a42021-12-20 16:11:20 -060093
94 if config.bench_mode == "cleanup":
Alexb2129542021-11-23 15:49:42 -060095 self.cleanup_list = []
96 return
97
Alex90ac1532021-12-09 11:13:14 -060098 self.bench_name = config.bench_name
Alex30380a42021-12-20 16:11:20 -060099 self.results_dump_path = config.bench_results_dump_path
100 self.results = {}
101 self.agent_results = {}
102 self.cleanup_list = []
Alexb2129542021-11-23 15:49:42 -0600103 self.agent_pods = []
Alex30380a42021-12-20 16:11:20 -0600104
105 if config.bench_mode == "report":
106 self.results = {}
107 return
108
109 self.storage_class = config.bench_storage_class
Alexb2129542021-11-23 15:49:42 -0600110 self.services = []
111 # By default,
112 # 30 seconds should be enough to send tasks to 3-5 agents
113 self.scheduled_delay = 30
Alex5cace3b2021-11-10 16:40:37 -0600114
Alexb2129542021-11-23 15:49:42 -0600115 def set_ceph_info_class(self, ceph_info):
116 self.ceph_info = ceph_info
Alex2a7657c2021-11-10 20:51:34 -0600117
Alex5cace3b2021-11-10 16:40:37 -0600118 def load_tasks(self, taskfile):
119 # Load csv file
120 logger_cli.info("-> Loading taskfile '{}'".format(taskfile))
121 self.tasks = []
122 with open(taskfile) as f:
123 _reader = csv.reader(f, delimiter=',')
124 # load packages
125 for row in _reader:
126 self.tasks.append({
127 "readwrite": row[0],
128 "rwmixread": row[1],
129 "bs": row[2],
130 "iodepth": row[3],
Alexe4de1142022-11-04 19:26:03 -0500131 "size": row[4],
132 "ramp_time": row[5],
133 "runtime": row[6]
Alex5cace3b2021-11-10 16:40:37 -0600134 })
Alexb2129542021-11-23 15:49:42 -0600135 logger_cli.info("-> Loaded {} tasks".format(len(self.tasks)))
Alex5cace3b2021-11-10 16:40:37 -0600136
Alex2a7657c2021-11-10 20:51:34 -0600137 def add_for_deletion(self, obj, typ):
Alexb2129542021-11-23 15:49:42 -0600138 self.cleanup_list.append(
139 [
140 typ,
141 obj.metadata.namespace,
142 obj.metadata.name
143 ]
144 )
145 return
146
147 def prepare_cleanup(self):
148 # Assume number of resources not given
149 # list all svc, pod, pvc, pv and identify 'cfgagent-xx ones
150 _types = ["pv", "pvc", "pod", "svc"]
151 _prefix = self.resource_prefix
152 for _typ in _types:
153 _list = self.master.list_resource_names_by_type_and_ns(_typ)
154 for ns, name in _list:
155 if name.startswith(_prefix):
156 if ns:
157 _msg = "{} {}/{}".format(_typ, ns, name)
158 else:
159 _msg = "{} {}".format(_typ, name)
160 logger_cli.info("-> Found {}".format(_msg))
161 self.cleanup_list.append([_typ, ns, name])
Alex2a7657c2021-11-10 20:51:34 -0600162 return
163
Alex5cace3b2021-11-10 16:40:37 -0600164 def prepare_agents(self, options):
165 logger_cli.info("# Preparing {} agents".format(self.agent_count))
Alex30380a42021-12-20 16:11:20 -0600166 # Increase volume size a bit, so datafile fits
167 _quanitizer = 1.3
168 _v_size, _vol_size_units = _split_vol_size(options['size'])
169 _v_size = round(_v_size * _quanitizer)
170 _vol_size = str(_v_size) + _vol_size_units + "i"
171 logger_cli.info(
172 "-> Testfile size: {0}, Volume size: {1} ({0}*{2})".format(
173 options['size'],
174 _vol_size,
175 _quanitizer
176 )
177 )
178 # Start preparing
Alex5cace3b2021-11-10 16:40:37 -0600179 for idx in range(self.agent_count):
180 # create pvc/pv and pod
181 logger_cli.info("-> creating agent '{:02}'".format(idx))
Alex90ac1532021-12-09 11:13:14 -0600182 # _agent, _pv, _pvc = self.master.prepare_benchmark_agent(
183 _agent, _pvc = self.master.prepare_benchmark_agent(
Alex5cace3b2021-11-10 16:40:37 -0600184 idx,
185 os.path.split(options["filename"])[0],
186 self.storage_class,
Alex30380a42021-12-20 16:11:20 -0600187 _vol_size,
Alex5cace3b2021-11-10 16:40:37 -0600188 self._agent_template
189 )
Alex2a7657c2021-11-10 20:51:34 -0600190 # save it to lists
Alex5cace3b2021-11-10 16:40:37 -0600191 self.agent_pods.append(_agent)
Alex90ac1532021-12-09 11:13:14 -0600192 # self.add_for_deletion(_pv, "pv")
Alex2a7657c2021-11-10 20:51:34 -0600193 self.add_for_deletion(_pvc, "pvc")
194 self.add_for_deletion(_agent, "pod")
195
Alex5cace3b2021-11-10 16:40:37 -0600196 # expose it
197 _svc = self.master.expose_benchmark_agent(_agent)
Alex2a7657c2021-11-10 20:51:34 -0600198 self.add_for_deletion(_svc, "svc")
Alex5cace3b2021-11-10 16:40:37 -0600199 # Save service
200 self.services.append(_svc)
Alex3034ba52021-11-13 17:06:45 -0600201 # prepopulate results
Alexb2129542021-11-23 15:49:42 -0600202 self.agent_results[_agent.metadata.name] = {}
203 self.agent_results[_agent.metadata.name]["url"] = \
Alex5cace3b2021-11-10 16:40:37 -0600204 "http://{}:{}/api/".format(
Alex3034ba52021-11-13 17:06:45 -0600205 _svc.spec.cluster_ip,
Alex5cace3b2021-11-10 16:40:37 -0600206 8765
207 )
Alexb2129542021-11-23 15:49:42 -0600208 self.agent_results[_agent.metadata.name]["storage_class"] = \
Alex3034ba52021-11-13 17:06:45 -0600209 self.storage_class
Alexb2129542021-11-23 15:49:42 -0600210 self.agent_results[_agent.metadata.name]["volume_size"] = \
Alex3034ba52021-11-13 17:06:45 -0600211 options['size']
212
Alex5cace3b2021-11-10 16:40:37 -0600213 logger_cli.info("-> Done creating agents")
Alexb2129542021-11-23 15:49:42 -0600214 # TODO: Update after implementing pooled task sending
Alex90ac1532021-12-09 11:13:14 -0600215 self.scheduled_delay = self.agent_count * 10
Alexb2129542021-11-23 15:49:42 -0600216 logger_cli.info(
217 "-> Schedule delay set to {} sec".format(self.scheduled_delay)
218 )
Alex5cace3b2021-11-10 16:40:37 -0600219 return
220
221 def _poke_agent(self, url, body, action="GET"):
222 _datafile = "/tmp/data"
223 _data = [
Alexbfa947c2021-11-11 18:14:28 -0600224 "-d",
225 "@" + _datafile
Alex5cace3b2021-11-10 16:40:37 -0600226 ]
227 _cmd = [
228 "curl",
229 "-s",
230 "-H",
231 "'Content-Type: application/json'",
232 "-X",
233 action,
234 url
235 ]
236 if body:
237 _cmd += _data
238 _ret = self.master.prepare_json_in_pod(
239 self.agent_pods[0].metadata.name,
240 self.master._namespace,
241 body,
242 _datafile
243 )
244 _ret = self.master.exec_cmd_on_target_pod(
245 self.agent_pods[0].metadata.name,
246 self.master._namespace,
247 " ".join(_cmd)
248 )
Alexb2129542021-11-23 15:49:42 -0600249 return _parse_json_output(_ret)
Alex5cace3b2021-11-10 16:40:37 -0600250
Alex3034ba52021-11-13 17:06:45 -0600251 def _ensure_agents_ready(self):
Alex5cace3b2021-11-10 16:40:37 -0600252 # make sure agents idle
Alex3034ba52021-11-13 17:06:45 -0600253 _status_set = []
254 _ready_set = []
255 for _agent, _d in self.get_agents_status().items():
256 # obviously, there should be some answer
257 if _d is None:
Alex5cace3b2021-11-10 16:40:37 -0600258 logger_cli.error("ERROR: Agent status not available")
259 return False
Alex3034ba52021-11-13 17:06:45 -0600260 # status should be idle or finished
261 if _d['status'] not in ["idle", "finished"]:
262 logger_cli.error(
263 "Agent status invalid {}:{}".format(_agent, _d['status'])
264 )
265 _status_set += [False]
Alex5cace3b2021-11-10 16:40:37 -0600266 else:
Alex3034ba52021-11-13 17:06:45 -0600267 # Good agent
268 _status_set += [True]
269 # agent's fio shell should be in 'ready'
270 if not _d["healthcheck"]["ready"]:
271 logger_cli.error("Agent is not ready {}".format(_agent))
272 _ready_set += [False]
Alex5cace3b2021-11-10 16:40:37 -0600273 else:
Alex3034ba52021-11-13 17:06:45 -0600274 # 'fio' shell for agent is ready
275 _ready_set += [True]
276 # all agent's statuses should be True
277 # and all 'fio' shell modules should be 'ready'
278 if not any(_status_set) or not any(_ready_set):
279 # At least one is not ready and it was already logged above
280 return False
281 else:
282 # All is good
283 return True
284
Alexe4de1142022-11-04 19:26:03 -0500285 def get_agents_status(self, silent=True):
Alex3034ba52021-11-13 17:06:45 -0600286 _status = {}
Alexb2129542021-11-23 15:49:42 -0600287 _results = self.master.exec_on_labeled_pods_and_ns(
288 "app=cfgagent",
Alexe4de1142022-11-04 19:26:03 -0500289 "curl -s http://localhost:8765/api/fio",
290 silent=silent
Alexb2129542021-11-23 15:49:42 -0600291 )
292 for _agent, _result in _results.items():
293 _j = _parse_json_output(_result)
294 _status[_agent] = _j
Alex3034ba52021-11-13 17:06:45 -0600295 return _status
296
Alexb2129542021-11-23 15:49:42 -0600297 @retry(Exception, initial_wait=5)
Alex3034ba52021-11-13 17:06:45 -0600298 def get_agents_resultlist(self):
299 _t = {"module": "fio", "action": "get_resultlist"}
300 _status = {}
Alexb2129542021-11-23 15:49:42 -0600301 for _agent, _d in self.agent_results.items():
Alex3034ba52021-11-13 17:06:45 -0600302 _status[_agent] = self._poke_agent(_d["url"], _t, action="POST")
303 return _status
304
Alexb2129542021-11-23 15:49:42 -0600305 @retry(Exception, initial_wait=5)
Alex3034ba52021-11-13 17:06:45 -0600306 def get_result_from_agent(self, agent, time):
307 _t = {
308 "module": "fio",
309 "action": "get_result",
310 "options": {
311 "time": time
312 }
313 }
Alexb2129542021-11-23 15:49:42 -0600314 return self._poke_agent(
315 self.agent_results[agent]["url"],
316 _t,
317 action="POST"
318 )
Alex3034ba52021-11-13 17:06:45 -0600319
320 def _get_next_scheduled_time(self):
321 _now = datetime.now(timezone.utc)
322 logger_cli.info("-> time is '{}'".format(_now.strftime(_datetime_fmt)))
Alex90ac1532021-12-09 11:13:14 -0600323 self.next_scheduled_time = _now + timedelta(
324 seconds=self.scheduled_delay
325 )
326 _str_time = self.next_scheduled_time.strftime(_datetime_fmt)
Alex3034ba52021-11-13 17:06:45 -0600327 logger_cli.info(
328 "-> next benchmark scheduled to '{}'".format(_str_time)
329 )
330 return _str_time
331
332 def _send_scheduled_task(self, options):
333 _task = {
334 "module": "fio",
335 "action": "do_scheduledrun",
336 "options": options
337 }
Alexb2129542021-11-23 15:49:42 -0600338 for _agent, _d in self.agent_results.items():
Alex3034ba52021-11-13 17:06:45 -0600339 logger_cli.info(
340 "-> sending task to '{}:{}'".format(_agent, _d["url"])
341 )
342 _ret = self._poke_agent(_d["url"], _task, action="POST")
343 if 'error' in _ret:
344 logger_cli.error(
345 "ERROR: Agent returned: '{}'".format(_ret['error'])
346 )
347 return False
348 # No errors detected
349 return True
350
351 def track_benchmark(self, options):
352 _runtime = _get_seconds(options["runtime"])
353 _ramptime = _get_seconds(options["ramp_time"])
354 # Sum up all timings that we must wait and double it
355 _timeout = (self.scheduled_delay + _runtime + _ramptime) * 2
Alex30380a42021-12-20 16:11:20 -0600356 # We should have no more than 65 measurements
357 _stats_delay = round((_runtime + _ramptime) / 65)
Alex90ac1532021-12-09 11:13:14 -0600358 _start = self.next_scheduled_time
Alex3034ba52021-11-13 17:06:45 -0600359 _end = datetime.now(timezone.utc) + timedelta(seconds=_timeout)
Alexe4de1142022-11-04 19:26:03 -0500360 logger_cli.info(" ")
361 tw = cl_typewriter()
Alex3034ba52021-11-13 17:06:45 -0600362 while True:
363 # Print status
Alexe4de1142022-11-04 19:26:03 -0500364 tw.cl_start(" ")
365 _sts = self.get_agents_status(silent=True)
366 # Use same line
Alex3034ba52021-11-13 17:06:45 -0600367 diff = (_end - datetime.now(timezone.utc)).total_seconds()
Alexe4de1142022-11-04 19:26:03 -0500368 _startin = (_start - datetime.now(timezone.utc)).total_seconds()
369 if _startin > 0:
370 tw.cl_inline("-> starting in {:.2f}s ".format(_startin))
371 else:
372 tw.cl_inline("-> {:.2f}s; ".format(diff))
373 _progress = [_st["progress"] for _st in _sts.values()]
374 tw.cl_inline(
375 "{}% <-> {}%; ".format(
376 min(_progress),
377 max(_progress)
Alex3034ba52021-11-13 17:06:45 -0600378 )
379 )
Alexe4de1142022-11-04 19:26:03 -0500380
381 _a_sts = [_t["status"] for _t in _sts.values()]
382 tw.cl_inline(
383 ", ".join(
384 ["{} {}".format(_a_sts.count(_s), _s)
385 for _s in set(_a_sts)]
386 )
387 )
388
Alex90ac1532021-12-09 11:13:14 -0600389 # Get Ceph status if _start time passed
390 _elapsed = (datetime.now(timezone.utc) - _start).total_seconds()
Alex30380a42021-12-20 16:11:20 -0600391 if _elapsed > _stats_delay:
Alexe4de1142022-11-04 19:26:03 -0500392 # Use same line output
393 tw.cl_inline(" {:.2f}s elapsed".format(_elapsed))
Alex30380a42021-12-20 16:11:20 -0600394 _sec = "{:0.1f}".format(_elapsed)
395 self.results[options["scheduled_to"]]["ceph"][_sec] = \
Alex90ac1532021-12-09 11:13:14 -0600396 self.ceph_info.get_cluster_status()
397 # Check if agents finished
Alexb2129542021-11-23 15:49:42 -0600398 finished = [True for _s in _sts.values()
Alex3034ba52021-11-13 17:06:45 -0600399 if _s["status"] == 'finished']
400 _fcnt = len(finished)
401 _tcnt = len(_sts)
402 if _fcnt < _tcnt:
Alexe4de1142022-11-04 19:26:03 -0500403 tw.cl_inline(" {}/{}".format(_fcnt, _tcnt))
Alex3034ba52021-11-13 17:06:45 -0600404 else:
Alexe4de1142022-11-04 19:26:03 -0500405 tw.cl_flush(newline=True)
Alex3034ba52021-11-13 17:06:45 -0600406 logger_cli.info("-> All agents finished run")
407 return True
408 # recalc how much is left
409 diff = (_end - datetime.now(timezone.utc)).total_seconds()
410 # In case end_datetime was in past to begin with
411 if diff < 0:
Alexe4de1142022-11-04 19:26:03 -0500412 tw.cl_flush(newline=True)
Alex3034ba52021-11-13 17:06:45 -0600413 logger_cli.info("-> Timed out waiting for agents to finish")
414 return False
Alexe4de1142022-11-04 19:26:03 -0500415 tw.cl_flush()
Alex3034ba52021-11-13 17:06:45 -0600416
417 def _do_testrun(self, options):
Alex30380a42021-12-20 16:11:20 -0600418 self.results[options["scheduled_to"]]["osd_df_before"] = \
419 self.ceph_info.get_ceph_osd_df()
Alex3034ba52021-11-13 17:06:45 -0600420 # send single to agent
421 if not self._send_scheduled_task(options):
422 return False
423 # Track this benchmark progress
424 if not self.track_benchmark(options):
425 return False
426 else:
Alex90ac1532021-12-09 11:13:14 -0600427 logger_cli.info("-> Finished testrun. Collecting results...")
Alex30380a42021-12-20 16:11:20 -0600428 # get ceph osd stats
429 self.results[options["scheduled_to"]]["osd_df_after"] = \
430 self.ceph_info.get_ceph_osd_df()
Alex3034ba52021-11-13 17:06:45 -0600431 # Get results for each agent
Alex90ac1532021-12-09 11:13:14 -0600432 self.collect_results()
433 logger_cli.info("-> Calculating totals and averages")
434 self.calculate_totals()
435 self.calculate_ceph_stats()
Alex30380a42021-12-20 16:11:20 -0600436 self.osd_df_compare(options["scheduled_to"])
Alex90ac1532021-12-09 11:13:14 -0600437 logger_cli.info("-> Dumping results")
438 for _time, _d in self.results.items():
439 self.dump_result(
440 self._get_dump_filename(_time),
441 _d
442 )
Alex3034ba52021-11-13 17:06:45 -0600443 return True
444
Alexb2129542021-11-23 15:49:42 -0600445 def wait_ceph_cooldown(self):
Alex3034ba52021-11-13 17:06:45 -0600446 # TODO: Query Ceph ince a 20 sec to make sure its load dropped
447
Alexb2129542021-11-23 15:49:42 -0600448 # get ceph idle status
449 self.ceph_idle_status = self.ceph_info.get_cluster_status()
450 self.health_detail = self.ceph_info.get_health_detail()
451 self.ceph_df = self.ceph_info.get_ceph_df()
452 self.ceph_pg_dump = self.ceph_info.get_ceph_pg_dump()
Alex3034ba52021-11-13 17:06:45 -0600453 return
454
455 def run_benchmark(self, options):
456 logger_cli.info("# Starting '{}' benchmark".format(self.mode))
457 # Check agent readyness
458 logger_cli.info("# Checking agents")
459 if not self._ensure_agents_ready():
Alex5cace3b2021-11-10 16:40:37 -0600460 return False
461
462 # Make sure that Ceph is at low load
463 # TODO: Ceph status check
Alexb2129542021-11-23 15:49:42 -0600464 # self._wait_ceph_cooldown()
465
Alex5cace3b2021-11-10 16:40:37 -0600466 # Do benchmark according to mode
467 if self.mode == "tasks":
Alex5cace3b2021-11-10 16:40:37 -0600468 logger_cli.info(
Alex3034ba52021-11-13 17:06:45 -0600469 "# Running benchmark with tasks from '{}'".format(
470 self.taskfile
Alex5cace3b2021-11-10 16:40:37 -0600471 )
Alex3034ba52021-11-13 17:06:45 -0600472 )
473 # take next task
474 _total_tasks = len(self.tasks)
475 for idx in range(_total_tasks):
Alexb2129542021-11-23 15:49:42 -0600476 # init time to schedule
Alex3034ba52021-11-13 17:06:45 -0600477 _task = self.tasks[idx]
Alexbdc72742021-12-23 13:26:05 -0600478 _r = self.results
Alex3034ba52021-11-13 17:06:45 -0600479 logger_cli.info(
480 "-> Starting next task ({}/{})".format(idx+1, _total_tasks)
481 )
482 logger_cli.info("-> Updating options with: {}".format(
483 ", ".join(
484 ["{} = {}".format(k, v) for k, v in _task.items()]
485 )
486 )
487 )
488 # update options
489 options.update(_task)
Alexbdc72742021-12-23 13:26:05 -0600490 # Check if such result already exists
491 o = "input_options"
492 _existing = filter(
493 lambda t:
494 _r[t]["id"] == idx and
495 _r[t]["mode"] == "tasks" and
496 _r[t][o]["readwrite"] == options["readwrite"] and
497 _r[t][o]["rwmixread"] == options["rwmixread"] and
498 _r[t][o]["bs"] == options["bs"] and
499 _r[t][o]["iodepth"] == options["iodepth"] and
500 _r[t][o]["size"] == options["size"],
501 _r
502 )
503 if len(list(_existing)) > 0:
504 logger_cli.info(
505 "-> Skipped already performed task from {}: "
506 "line {}, {}({}), {}, {}, {}".format(
507 self.taskfile,
508 idx,
509 options["readwrite"],
510 options["rwmixread"],
511 options["bs"],
512 options["iodepth"],
513 options["size"]
514 )
515 )
516 continue
Alexb2129542021-11-23 15:49:42 -0600517 _sch_time = self._get_next_scheduled_time()
518 options["scheduled_to"] = _sch_time
519 # init results table
Alexbdc72742021-12-23 13:26:05 -0600520 _r[_sch_time] = {
521 "id": idx,
522 "mode": self.mode,
523 "input_options": deepcopy(options),
Alexb2129542021-11-23 15:49:42 -0600524 "agents": {},
Alex30380a42021-12-20 16:11:20 -0600525 "ceph": {}
Alexb2129542021-11-23 15:49:42 -0600526 }
Alex30380a42021-12-20 16:11:20 -0600527 # exit on error
Alex3034ba52021-11-13 17:06:45 -0600528 if not self._do_testrun(options):
529 return False
Alex30380a42021-12-20 16:11:20 -0600530 # Save ceph osd stats and wait cooldown
Alexb2129542021-11-23 15:49:42 -0600531 self.wait_ceph_cooldown()
Alex3034ba52021-11-13 17:06:45 -0600532 elif self.mode == "single":
533 logger_cli.info("# Running single benchmark")
534 # init time to schedule
Alexb2129542021-11-23 15:49:42 -0600535 _sch_time = self._get_next_scheduled_time()
536 options["scheduled_to"] = _sch_time
537 # init results table
538 self.results[_sch_time] = {
Alexbdc72742021-12-23 13:26:05 -0600539 "id": "{:2}".format(0),
Alexb2129542021-11-23 15:49:42 -0600540 "input_options": options,
541 "agents": {},
Alex30380a42021-12-20 16:11:20 -0600542 "ceph": {}
Alexb2129542021-11-23 15:49:42 -0600543 }
Alex3034ba52021-11-13 17:06:45 -0600544 if not self._do_testrun(options):
545 return False
Alex30380a42021-12-20 16:11:20 -0600546 # Save ceph osd stats
Alex3034ba52021-11-13 17:06:45 -0600547 else:
548 logger_cli.error("ERROR: Unknown mode '{}'".format(self.mode))
549 return False
550
551 # Normal exit
552 logger_cli.info("# All benchmark tasks done")
Alex5cace3b2021-11-10 16:40:37 -0600553 return True
554
555 def cleanup(self):
Alexb2129542021-11-23 15:49:42 -0600556 logger_cli.info("# Cleaning up")
Alex2a7657c2021-11-10 20:51:34 -0600557 self.cleanup_list.reverse()
Alex5cace3b2021-11-10 16:40:37 -0600558
Alex2a7657c2021-11-10 20:51:34 -0600559 for _res in self.cleanup_list:
560 self.master.cleanup_resource_by_name(_res[0], _res[2], ns=_res[1])
Alexbfa947c2021-11-11 18:14:28 -0600561
562 # Wait for resource to be cleaned
563 _timeout = 120
564 _total = len(self.cleanup_list)
565 logger_cli.info("-> Wait until {} resources cleaned".format(_total))
566 _p = Progress(_total)
567 while True:
568 _g = self.master.get_resource_phase_by_name
569 _l = [_g(r[0], r[2], ns=r[1]) for r in self.cleanup_list]
570 _l = [item for item in _l if item]
571 _idx = _total - len(_l)
572 if len(_l) > 0:
573 _p.write_progress(_idx)
574 else:
Alex3034ba52021-11-13 17:06:45 -0600575 _p.write_progress(_idx)
Alexbfa947c2021-11-11 18:14:28 -0600576 _p.end()
577 logger_cli.info("# Done cleaning up")
578 break
579 if _timeout > 0:
580 _timeout -= 1
581 else:
582 _p.end()
583 logger_cli.info("# Timed out waiting after 120s.")
584 break
585
Alex5cace3b2021-11-10 16:40:37 -0600586 return
587
Alex90ac1532021-12-09 11:13:14 -0600588 def collect_results(self):
Alex3034ba52021-11-13 17:06:45 -0600589 logger_cli.info("# Collecting results")
590 # query agents for results
591 _agents = self.get_agents_resultlist()
Alex3034ba52021-11-13 17:06:45 -0600592 for _agent, _l in _agents.items():
Alexb2129542021-11-23 15:49:42 -0600593 # Check if we already have this locally
594 for _time in _l["resultlist"]:
Alex90ac1532021-12-09 11:13:14 -0600595 # There is a file already for this task/time
596 # Check if we need to load it
597 if _time not in self.results:
598 # Some older results found
599 # do not process them
Alexe4de1142022-11-04 19:26:03 -0500600 logger_cli.debug(
601 "...skipped old results for '{}'".format(_time)
Alex90ac1532021-12-09 11:13:14 -0600602 )
603 continue
604 elif _agent not in self.results[_time]["agents"]:
605 # Load result add it locally
Alexb2129542021-11-23 15:49:42 -0600606 logger_cli.info(
607 "-> Getting results for '{}' from '{}'".format(
Alex90ac1532021-12-09 11:13:14 -0600608 _time,
Alexb2129542021-11-23 15:49:42 -0600609 _agent
610 )
Alex3034ba52021-11-13 17:06:45 -0600611 )
Alexb2129542021-11-23 15:49:42 -0600612 _r = self.get_result_from_agent(_agent, _time)
Alex90ac1532021-12-09 11:13:14 -0600613 self.results[_time]["agents"][_agent] = _r[_time]
614 else:
615 # Should never happen, actually
616 logger_cli.info(
617 "-> Skipped loaded result for '{}' from '{}'".format(
618 _time,
619 _agent
620 )
621 )
Alex3034ba52021-11-13 17:06:45 -0600622
Alex90ac1532021-12-09 11:13:14 -0600623 def _get_dump_filename(self, _time):
624 _r = self.results[_time]
625 _dirname = _r["input_options"]["name"]
Alexb2129542021-11-23 15:49:42 -0600626 _filename = "-".join([
Alex90ac1532021-12-09 11:13:14 -0600627 _reformat_timestr(_time),
628 "{:02}".format(len(_r["agents"])),
629 _r["input_options"]["readwrite"],
630 _r["input_options"]["bs"],
631 str(_r["input_options"]["iodepth"]),
Alexb2129542021-11-23 15:49:42 -0600632 ]) + ".json"
633 return os.path.join(
634 self.results_dump_path,
635 _dirname,
636 _filename
637 )
638
Alex90ac1532021-12-09 11:13:14 -0600639 def preload_results(self):
640 logger_cli.info(
641 "# Preloading results for '{}'".format(self.bench_name)
642 )
643 # get all dirs in folder
644 _p = self.results_dump_path
645 if not os.path.isdir(_p):
646 logger_cli.warn(
647 "WARNING: Dump path is not a folder '{}'".format(_p)
648 )
649 return
650 for path, dirs, files in os.walk(_p):
651 if path == os.path.join(_p, self.bench_name):
652 logger_cli.info("-> Folder found '{}'".format(path))
653 for _fname in files:
654 logger_cli.debug("... processing '{}'".format(_fname))
655 _ext = _fname.split('.')[-1]
656 if _ext != "json":
657 logger_cli.info(
658 "-> Extension invalid '{}', "
659 "'json' is expected".format(_ext)
660 )
661 continue
662 # get time from filename
663 # Ugly, but works
664 _t = _fname.split('-')[0]
665 _str_time = _t[:14] + "+" + _t[14:]
666 _t = datetime.strptime(_str_time, _file_datetime_fmt)
667 _time = _t.strftime(_datetime_fmt)
668 self.results[_time] = self.load_dumped_result(
669 os.path.join(path, _fname)
670 )
671 logger_cli.info(
672 "-> Loaded '{}' as '{}'".format(
673 _fname,
674 _time
675 )
676 )
677
Alexb2129542021-11-23 15:49:42 -0600678 def dump_result(self, filename, data):
679 # Function dumps all available results as jsons to the given path
Alex3034ba52021-11-13 17:06:45 -0600680 # overwriting if needed
Alexb2129542021-11-23 15:49:42 -0600681 _folder, _file = os.path.split(filename)
682 # Do dump
683 if not os.path.exists(_folder):
684 os.mkdir(_folder)
685 logger_cli.info("-> Created folder '{}'".format(_folder))
686 # Dump agent data for this test run
687 write_str_to_file(filename, json.dumps(data, indent=2))
688 logger_cli.info("-> Dumped '{}'".format(filename))
Alex3034ba52021-11-13 17:06:45 -0600689 return
690
Alexb2129542021-11-23 15:49:42 -0600691 def load_dumped_result(self, filename):
692 try:
693 with open(filename, "rt+") as f:
694 return json.loads(f.read())
695 except FileNotFoundError as e:
696 logger_cli.error(
697 "ERROR: {}".format(e)
698 )
699 except TypeError as e:
700 logger_cli.error(
701 "ERROR: Invalid file ({}): {}".format(filename, e)
702 )
703 except json.decoder.JSONDecodeError as e:
704 logger_cli.error(
705 "ERROR: Failed to decode json ({}): {}".format(filename, e)
706 )
707 return None
708
709 def _lookup_storage_class_id_by_name(self, storage_class_name):
710 # Assume that self had proper data
711 for _pool in self.ceph_df["pools"]:
712 if storage_class_name == _pool["name"]:
713 return _pool["id"]
714 return None
715
716 def calculate_totals(self):
Alexe4de1142022-11-04 19:26:03 -0500717 def _savg(vlist):
718 if len(vlist) > 0:
719 return (sum(vlist) / len(vlist)) / 1000
720 else:
721 return 0
Alexb2129542021-11-23 15:49:42 -0600722 # Calculate totals for Read and Write
723 for _time, data in self.results.items():
724 if "totals" not in data:
725 data["totals"] = {}
726 else:
727 continue
728 _totals = data["totals"]
729 _r_bw = 0
730 _r_avglat = []
Alex0989ecf2022-03-29 13:43:21 -0500731 _r_95clat = []
Alexb2129542021-11-23 15:49:42 -0600732 _r_iops = 0
733 _w_bw = 0
734 _w_avglat = []
Alex0989ecf2022-03-29 13:43:21 -0500735 _w_95clat = []
Alexb2129542021-11-23 15:49:42 -0600736 _w_iops = 0
737 for _a, _d in data["agents"].items():
738 # Hardcoded number of jobs param :(
Alex90ac1532021-12-09 11:13:14 -0600739 _j = _d["jobs"][0]
Alexb2129542021-11-23 15:49:42 -0600740 _r_bw += _j["read"]["bw_bytes"]
741 _r_avglat += [_j["read"]["lat_ns"]["mean"]]
Alex0989ecf2022-03-29 13:43:21 -0500742 _r_95clat += [_j["read"]["clat_ns"]["percentile"]["95.000000"]]
Alexb2129542021-11-23 15:49:42 -0600743 _r_iops += _j["read"]["iops"]
744 _w_bw += _j["write"]["bw_bytes"]
745 _w_avglat += [_j["write"]["lat_ns"]["mean"]]
Alex0989ecf2022-03-29 13:43:21 -0500746 _w_95clat += \
747 [_j["write"]["clat_ns"]["percentile"]["95.000000"]]
Alexb2129542021-11-23 15:49:42 -0600748 _w_iops += _j["write"]["iops"]
749 # Save storage class name
750 if "storage_class" not in _totals:
751 _totals["storage_class"] = \
752 self.agent_results[_a]["storage_class"]
753 # Lookup storage class id and num_pg
754 _totals["storage_class_stats"] = \
755 reporter.get_pool_stats_by_id(
756 self._lookup_storage_class_id_by_name(
757 self.agent_results[_a]["storage_class"]
758 ),
759 self.ceph_pg_dump
760 )
761
762 _totals["read_bw_bytes"] = _r_bw
Alexe4de1142022-11-04 19:26:03 -0500763 _totals["read_avg_lat_us"] = _savg(_r_avglat)
764 _totals["read_95p_clat_us"] = _savg(_r_95clat)
Alexb2129542021-11-23 15:49:42 -0600765 _totals["read_iops"] = _r_iops
766 _totals["write_bw_bytes"] = _w_bw
Alexe4de1142022-11-04 19:26:03 -0500767 _totals["write_avg_lat_us"] = _savg(_w_avglat)
768 _totals["write_95p_clat_us"] = _savg(_w_95clat)
Alexb2129542021-11-23 15:49:42 -0600769 _totals["write_iops"] = _w_iops
770
Alex90ac1532021-12-09 11:13:14 -0600771 def calculate_ceph_stats(self):
772 # func to get values as lists
Alex30380a42021-12-20 16:11:20 -0600773 def _get_max_value(key, stats):
774 _max_time = 0
775 _value = 0
776 for _k, _v in stats.items():
777 if key in _v and _value < _v[key]:
778 _max_time = _k
779 _value = _v[key]
780 return _max_time, _value
Alex90ac1532021-12-09 11:13:14 -0600781
782 def _perc(n, m):
783 if not n:
784 return 0
785 elif not m:
786 return 0
787 else:
Alex30380a42021-12-20 16:11:20 -0600788 return "{:.0f}%".format((n / m) * 100)
789
790 def _axis_vals(val):
791 return [
792 val, int(val*1.1), int(val*0.75), int(val*0.50), int(val*0.15)
793 ]
Alex90ac1532021-12-09 11:13:14 -0600794
795 _stats = {}
796 for _time, data in self.results.items():
797 if "ceph" not in data:
798 logger_cli.warning(
799 "WARNING: Ceph stats raw data not found in results"
800 )
801 continue
802 if "ceph_stats" not in data:
803 data["ceph_stats"] = {}
804 else:
805 continue
806 # Copy pool stats data
807 for _e, _d in data["ceph"].items():
808 _stats[_e] = _d["pgmap"]
809 # Maximums
Alex30380a42021-12-20 16:11:20 -0600810 mrb_t, mrb = _get_max_value("read_bytes_sec", _stats)
811 mwb_t, mwb = _get_max_value("write_bytes_sec", _stats)
812 mri_t, mri = _get_max_value("read_op_per_sec", _stats)
813 mwi_t, mwi = _get_max_value("write_op_per_sec", _stats)
Alex90ac1532021-12-09 11:13:14 -0600814 # Replace ceph with shorter data
815 data["ceph"] = {
Alex30380a42021-12-20 16:11:20 -0600816 "max_rbl": _axis_vals(mrb),
817 "max_rbl_time": mrb_t,
818 "max_wbl": _axis_vals(mwb),
819 "max_wbl_time": mwb_t,
820 "max_ril": _axis_vals(mri),
821 "max_ril_time": mri_t,
822 "max_wil": _axis_vals(mwi),
823 "max_wil_time": mwi_t,
Alex90ac1532021-12-09 11:13:14 -0600824 "stats": _stats
825 }
826 # Calculate %% values for barchart
827 for _e, _d in data["ceph"]["stats"].items():
828 _d["read_bytes_sec_perc"] = \
Alex30380a42021-12-20 16:11:20 -0600829 _perc(_d.get("read_bytes_sec", 0), mrb)
Alex90ac1532021-12-09 11:13:14 -0600830 _d["write_bytes_sec_perc"] = \
Alex30380a42021-12-20 16:11:20 -0600831 _perc(_d.get("write_bytes_sec", 0), mwb)
Alex90ac1532021-12-09 11:13:14 -0600832 _d["read_op_per_sec_perc"] = \
Alex30380a42021-12-20 16:11:20 -0600833 _perc(_d.get("read_op_per_sec", 0), mri)
Alex90ac1532021-12-09 11:13:14 -0600834 _d["write_op_per_sec_perc"] = \
Alex30380a42021-12-20 16:11:20 -0600835 _perc(_d.get("write_op_per_sec", 0), mwi)
836 return
837
838 def osd_df_compare(self, _time):
839 def _get_osd(osd_id, nodes):
840 for osd in nodes:
841 if osd["id"] == osd_id:
842 return osd
843 return None
844
845 logger_cli.info("# Comparing OSD stats")
846 _osd = {}
847 if _time not in self.results:
848 logger_cli.warning("WARNING: {} not found in results. Check data")
849 return
850 data = self.results[_time]
851 # Save summary
852 data["osd_summary"] = {}
853 data["osd_summary"]["before"] = data["osd_df_before"]["summary"]
854 data["osd_summary"]["after"] = data["osd_df_after"]["summary"]
855 data["osd_summary"]["active"] = {
856 "status": "",
857 "device_class": "",
Alexe4de1142022-11-04 19:26:03 -0500858 "pgs": 0,
Alex30380a42021-12-20 16:11:20 -0600859 "kb_used": 0,
860 "kb_used_data": 0,
861 "kb_used_omap": 0,
862 "kb_used_meta": 0,
863 "utilization": 0,
864 "var_down": 0,
865 "var_up": 0
866 }
867 # Compare OSD counts
868 osds_before = len(data["osd_df_before"]["nodes"])
869 osds_after = len(data["osd_df_after"]["nodes"])
870 if osds_before != osds_after:
871 logger_cli.warning(
872 "WARNING: Before/After bench OSD "
873 "count mismatch for '{}'".format(_time)
874 )
875 # iterate osds from before
876 _pgs = 0
877 _classes = set()
878 _nodes_up = 0
879 for idx in range(osds_before):
880 _osd_b = data["osd_df_before"]["nodes"][idx]
881 # search for the same osd in after
882 _osd_a = _get_osd(_osd_b["id"], data["osd_df_after"]["nodes"])
883 # Save data to the new place
884 _osd[_osd_b["name"]] = {}
885 _osd[_osd_b["name"]]["before"] = _osd_b
886 if not _osd_a:
887 # If this happen, Ceph cluster is actually broken
888 logger_cli.warning(
889 "WARNING: Wow! {} dissapered".format(_osd_b["name"])
890 )
891 _osd[_osd_b["name"]]["after"] = {}
892 else:
893 _osd[_osd_b["name"]]["after"] = _osd_a
894 _osd[_osd_b["name"]]["percent"] = {}
895 # Calculate summary using "after" data
896 _pgs += _osd_a["pgs"]
897 _classes.update([_osd_a["device_class"]])
898 if _osd_a["status"] == "up":
899 _nodes_up += 1
900 # compare
901 _keys_b = list(_osd_b.keys())
902 _keys_a = list(_osd_a.keys())
903 _nodes_up
904 # To be safe, detect if some keys are different
905 # ...and log it.
906 _diff = set(_keys_b).symmetric_difference(_keys_a)
907 if len(_diff) > 0:
908 # This should never happen, actually
909 logger_cli.warning(
910 "WARNING: Before/after keys mismatch "
911 "for OSD node {}: {}".format(idx, ", ".join(_diff))
912 )
913 continue
914 # Compare each key and calculate how it changed
915 for k in _keys_b:
916 if _osd_b[k] != _osd_a[k]:
917 # Announce change
918 logger_cli.debug(
919 "-> {:4}: {}, {} -> {}".format(
920 idx,
921 k,
922 _osd_b[k],
923 _osd_a[k]
924 )
925 )
926 # calculate percent
927 _change_perc = (_osd_a[k] / _osd_b[k]) * 100 - 100
928 _osd[_osd_b["name"]]["percent"][k] = _change_perc
929
930 # Increase counters
931 _p = data["osd_summary"]["active"]
932
933 if k not in _p:
934 _p[k] = 1
935 else:
936 _p[k] += 1
937 if k == "var":
938 if _change_perc > 0:
939 _p["var_up"] += 1
940 elif _change_perc < 0:
941 _p["var_down"] += 1
942 # Save sorted data
943 data["osds"] = _osd
944 logger_cli.info("-> Removing redundand osd before/after data")
945 data.pop("osd_df_before")
946 data.pop("osd_df_after")
947 # Save summary
948 data["osd_summary"]["active"]["status"] = "{}".format(_nodes_up)
949 data["osd_summary"]["active"]["device_class"] = \
950 "{}".format(len(list(_classes)))
951 data["osd_summary"]["active"]["pgs"] = _pgs
Alex90ac1532021-12-09 11:13:14 -0600952 return
953
Alex5cace3b2021-11-10 16:40:37 -0600954 # Create report
Alex2a7657c2021-11-10 20:51:34 -0600955 def create_report(self, filename):
Alexb2129542021-11-23 15:49:42 -0600956 """
957 Create static html showing ceph info report
958
959 :return: none
960 """
961 logger_cli.info("### Generating report to '{}'".format(filename))
962 _report = reporter.ReportToFile(
963 reporter.HTMLCephBench(self),
964 filename
965 )
Alexb2129542021-11-23 15:49:42 -0600966 _report(
967 {
968 "results": self.results,
969 "idle_status": self.ceph_idle_status,
970 "health_detail": self.health_detail,
971 "ceph_df": self.ceph_df,
972 "ceph_pg_dump": self.ceph_pg_dump,
973 "info": self.ceph_info.ceph_info,
974 "cluster": self.ceph_info.cluster_info,
975 "ceph_version": self.ceph_info.ceph_version,
976 "nodes": self.agent_pods
977 }
978 )
979 logger_cli.info("-> Done")
Alex5cace3b2021-11-10 16:40:37 -0600980
981 return