blob: ed4e8c89fd1ae935bd50b42b3133316e70931436 [file] [log] [blame]
koder aka kdanilov4643fd62015-02-10 16:20:13 -08001import abc
koder aka kdanilov66839a92015-04-11 13:22:31 +03002import time
koder aka kdanilov783b4542015-04-23 18:57:04 +03003import socket
koder aka kdanilov4d4771c2015-04-23 01:32:02 +03004import random
koder aka kdanilov4643fd62015-02-10 16:20:13 -08005import os.path
koder aka kdanilove21d7472015-02-14 19:02:04 -08006import logging
koder aka kdanilovea22c3d2015-04-21 03:42:22 +03007import datetime
koder aka kdanilove21d7472015-02-14 19:02:04 -08008
koder aka kdanilov783b4542015-04-23 18:57:04 +03009from paramiko import SSHException
10
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030011from wally.utils import ssize_to_b, open_for_append_or_create, sec_to_str
12
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030013from wally.ssh_utils import (copy_paths, run_over_ssh,
14 save_to_remote, ssh_mkdir,
15 # delete_file,
16 connect, read_from_remote, Local)
17
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030018from . import postgres
19from .io import agent as io_agent
20from .io import formatter as io_formatter
21from .io.results_loader import parse_output
koder aka kdanilov652cd802015-04-13 12:21:07 +030022
koder aka kdanilov4643fd62015-02-10 16:20:13 -080023
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030024logger = logging.getLogger("wally")
koder aka kdanilove21d7472015-02-14 19:02:04 -080025
26
koder aka kdanilov4643fd62015-02-10 16:20:13 -080027class IPerfTest(object):
koder aka kdanilovec1b9732015-04-23 20:43:29 +030028 def __init__(self, on_result_cb, test_uuid, node,
koder aka kdanilov2066daf2015-04-23 21:05:41 +030029 log_directory=None,
30 coordination_queue=None,
31 remote_dir="/tmp/wally"):
koder aka kdanilov4643fd62015-02-10 16:20:13 -080032 self.on_result_cb = on_result_cb
koder aka kdanilov4500a5f2015-04-17 16:55:17 +030033 self.log_directory = log_directory
34 self.node = node
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030035 self.test_uuid = test_uuid
koder aka kdanilovec1b9732015-04-23 20:43:29 +030036 self.coordination_queue = coordination_queue
koder aka kdanilov2066daf2015-04-23 21:05:41 +030037 self.remote_dir = remote_dir
38
39 def join_remote(self, path):
40 return os.path.join(self.remote_dir, path)
koder aka kdanilovec1b9732015-04-23 20:43:29 +030041
42 def coordinate(self, data):
43 if self.coordination_queue is not None:
44 self.coordination_queue.put(data)
koder aka kdanilov4643fd62015-02-10 16:20:13 -080045
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030046 def pre_run(self):
koder aka kdanilov4643fd62015-02-10 16:20:13 -080047 pass
48
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030049 def cleanup(self):
koder aka kdanilov4500a5f2015-04-17 16:55:17 +030050 pass
51
koder aka kdanilov4643fd62015-02-10 16:20:13 -080052 @abc.abstractmethod
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030053 def run(self, barrier):
koder aka kdanilov4643fd62015-02-10 16:20:13 -080054 pass
55
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030056 @classmethod
57 def format_for_console(cls, data):
58 msg = "{0}.format_for_console".format(cls.__name__)
59 raise NotImplementedError(msg)
60
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030061 def run_over_ssh(self, cmd, **kwargs):
62 return run_over_ssh(self.node.connection, cmd,
63 node=self.node.get_conn_id(), **kwargs)
64
koder aka kdanilovec1b9732015-04-23 20:43:29 +030065 @classmethod
66 def coordination_th(cls, coord_q, barrier, num_threads):
67 pass
68
koder aka kdanilov4643fd62015-02-10 16:20:13 -080069
Yulia Portnova7ddfa732015-02-24 17:32:58 +020070class TwoScriptTest(IPerfTest):
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030071 def __init__(self, opts, *dt, **mp):
72 IPerfTest.__init__(self, *dt, **mp)
Yulia Portnova7ddfa732015-02-24 17:32:58 +020073 self.opts = opts
Yulia Portnova7ddfa732015-02-24 17:32:58 +020074
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030075 if 'run_script' in self.opts:
76 self.run_script = self.opts['run_script']
77 self.prepare_script = self.opts['prepare_script']
Yulia Portnova7ddfa732015-02-24 17:32:58 +020078
79 def get_remote_for_script(self, script):
80 return os.path.join(self.tmp_dir, script.rpartition('/')[2])
81
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030082 def copy_script(self, src):
Yulia Portnova7ddfa732015-02-24 17:32:58 +020083 remote_path = self.get_remote_for_script(src)
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030084 copy_paths(self.node.connection, {src: remote_path})
Yulia Portnova7ddfa732015-02-24 17:32:58 +020085 return remote_path
86
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030087 def pre_run(self):
88 remote_script = self.copy_script(self.node.connection,
89 self.pre_run_script)
Yulia Portnova7ddfa732015-02-24 17:32:58 +020090 cmd = remote_script
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030091 self.run_over_ssh(cmd)
Yulia Portnova7ddfa732015-02-24 17:32:58 +020092
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030093 def run(self, barrier):
94 remote_script = self.copy_script(self.node.connection, self.run_script)
Yulia Portnova886a2562015-04-07 11:16:13 +030095 cmd_opts = ' '.join(["%s %s" % (key, val) for key, val
96 in self.opts.items()])
97 cmd = remote_script + ' ' + cmd_opts
koder aka kdanilov4d4771c2015-04-23 01:32:02 +030098 out_err = self.run_over_ssh(cmd)
koder aka kdanilov66839a92015-04-11 13:22:31 +030099 self.on_result(out_err, cmd)
Yulia Portnova7ddfa732015-02-24 17:32:58 +0200100
101 def parse_results(self, out):
102 for line in out.split("\n"):
103 key, separator, value = line.partition(":")
104 if key and value:
105 self.on_result_cb((key, float(value)))
106
koder aka kdanilov66839a92015-04-11 13:22:31 +0300107 def on_result(self, out_err, cmd):
108 try:
109 self.parse_results(out_err)
110 except Exception as exc:
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300111 msg_templ = "Error during postprocessing results: {0!s}. {1}"
112 raise RuntimeError(msg_templ.format(exc, out_err))
Yulia Portnova7ddfa732015-02-24 17:32:58 +0200113
114
115class PgBenchTest(TwoScriptTest):
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300116 root = os.path.dirname(postgres.__file__)
117 prepare_script = os.path.join(root, "prepare.sh")
118 run_script = os.path.join(root, "run.sh")
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300119
120
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800121class IOPerfTest(IPerfTest):
koder aka kdanilov2c473092015-03-29 17:12:13 +0300122
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300123 def __init__(self, test_options, *dt, **mp):
124 IPerfTest.__init__(self, *dt, **mp)
koder aka kdanilov2c473092015-03-29 17:12:13 +0300125 self.options = test_options
koder aka kdanilovda45e882015-04-06 02:24:42 +0300126 self.config_fname = test_options['cfg']
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300127 self.alive_check_interval = test_options.get('alive_check_interval')
koder aka kdanilovda45e882015-04-06 02:24:42 +0300128 self.config_params = test_options.get('params', {})
129 self.tool = test_options.get('tool', 'fio')
130 self.raw_cfg = open(self.config_fname).read()
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300131 self.configs = list(io_agent.parse_all_in_1(self.raw_cfg,
132 self.config_params))
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800133
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300134 cmd_log = os.path.join(self.log_directory, "task_compiled.cfg")
135 raw_res = os.path.join(self.log_directory, "raw_results.txt")
koder aka kdanilovda45e882015-04-06 02:24:42 +0300136
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300137 self.io_py_remote = self.join_remote("agent.py")
138 self.log_fl = self.join_remote("log.txt")
139 self.pid_file = self.join_remote("pid")
140 self.task_file = self.join_remote("task.cfg")
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300141
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300142 fio_command_file = open_for_append_or_create(cmd_log)
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300143
144 cfg_s_it = io_agent.compile_all_in_1(self.raw_cfg, self.config_params)
145 splitter = "\n\n" + "-" * 60 + "\n\n"
146 fio_command_file.write(splitter.join(cfg_s_it))
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300147 self.fio_raw_results_file = open_for_append_or_create(raw_res)
148
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300149 def cleanup(self):
150 # delete_file(conn, self.io_py_remote)
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300151 # Need to remove tempo files, used for testing
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300152 pass
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300153
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300154 def prefill_test_files(self):
155 files = {}
156
157 for section in self.configs:
158 sz = ssize_to_b(section.vals['size'])
159 msz = sz / (1024 ** 2)
160
161 if sz % (1024 ** 2) != 0:
162 msz += 1
163
164 fname = section.vals['filename']
165
166 # if already has other test with the same file name
167 # take largest size
168 files[fname] = max(files.get(fname, 0), msz)
169
170 cmd_templ = "dd oflag=direct " + \
171 "if=/dev/zero of={0} bs={1} count={2}"
172
173 if self.options.get("use_sudo", True):
174 cmd_templ = "sudo " + cmd_templ
175
176 ssize = 0
177 stime = time.time()
178
179 for fname, curr_sz in files.items():
180 cmd = cmd_templ.format(fname, 1024 ** 2, curr_sz)
181 ssize += curr_sz
182 self.run_over_ssh(cmd, timeout=curr_sz)
183
184 ddtime = time.time() - stime
185 if ddtime > 1E-3:
186 fill_bw = int(ssize / ddtime)
187 mess = "Initiall dd fill bw is {0} MiBps for this vm"
188 logger.info(mess.format(fill_bw))
189
190 def install_utils(self, max_retry=3, timeout=5):
191 need_install = []
192 for bin_name, package in (('fio', 'fio'), ('screen', 'screen')):
193 try:
194 self.run_over_ssh('which ' + bin_name, nolog=True)
195 except OSError:
196 need_install.append(package)
197
koder aka kdanilovafd98742015-04-24 01:27:22 +0300198 if len(need_install) == 0:
199 return
200
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300201 cmd = "sudo apt-get -y install " + " ".join(need_install)
202
203 for i in range(max_retry):
204 try:
205 self.run_over_ssh(cmd)
206 break
207 except OSError as err:
208 time.sleep(timeout)
209 else:
210 raise OSError("Can't install - " + str(err))
211
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300212 def pre_run(self):
koder aka kdanilova4a570f2015-04-23 22:11:40 +0300213 try:
214 cmd = 'mkdir -p "{0}"'.format(self.remote_dir)
215 if self.options.get("use_sudo", True):
216 cmd = "sudo " + cmd
217 cmd += " ; sudo chown {0} {1}".format(self.node.get_user(),
218 self.remote_dir)
219
220 self.run_over_ssh(cmd)
221 except Exception as exc:
222 msg = "Failed to create folder {0} on remote {1}. Error: {2!s}"
223 msg = msg.format(self.remote_dir, self.node.get_conn_id(), exc)
224 logger.error(msg)
225 raise
koder aka kdanilov783b4542015-04-23 18:57:04 +0300226
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300227 self.install_utils()
koder aka kdanilovda45e882015-04-06 02:24:42 +0300228
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300229 local_fname = os.path.splitext(io_agent.__file__)[0] + ".py"
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300230 files_to_copy = {local_fname: self.io_py_remote}
231 copy_paths(self.node.connection, files_to_copy)
koder aka kdanilov4643fd62015-02-10 16:20:13 -0800232
koder aka kdanilove87ae652015-04-20 02:14:35 +0300233 if self.options.get('prefill_files', True):
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300234 self.prefill_test_files()
koder aka kdanilove87ae652015-04-20 02:14:35 +0300235 else:
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300236 logger.warning("Prefilling of test files is disabled")
koder aka kdanilov6e2ae792015-03-04 18:02:24 -0800237
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300238 def run(self, barrier):
239 cmd_templ = "screen -S {screen_name} -d -m " + \
240 "env python2 {0} -p {pid_file} -o {results_file} " + \
241 "--type {1} {2} --json {3}"
242
243 if self.options.get("use_sudo", True):
244 cmd_templ = "sudo " + cmd_templ
koder aka kdanilov66839a92015-04-11 13:22:31 +0300245
246 params = " ".join("{0}={1}".format(k, v)
247 for k, v in self.config_params.items())
248
249 if "" != params:
250 params = "--params " + params
251
koder aka kdanilov783b4542015-04-23 18:57:04 +0300252 with self.node.connection.open_sftp() as sftp:
253 save_to_remote(sftp,
254 self.task_file, self.raw_cfg)
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300255
256 screen_name = self.test_uuid
257 cmd = cmd_templ.format(self.io_py_remote,
258 self.tool,
259 params,
260 self.task_file,
261 pid_file=self.pid_file,
262 results_file=self.log_fl,
263 screen_name=screen_name)
koder aka kdanilov66839a92015-04-11 13:22:31 +0300264 logger.debug("Waiting on barrier")
koder aka kdanilov652cd802015-04-13 12:21:07 +0300265
koder aka kdanilov0c598a12015-04-21 03:01:40 +0300266 exec_time = io_agent.calculate_execution_time(self.configs)
koder aka kdanilov652cd802015-04-13 12:21:07 +0300267 exec_time_str = sec_to_str(exec_time)
268
koder aka kdanilov2c473092015-03-29 17:12:13 +0300269 try:
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300270 timeout = int(exec_time * 2 + 300)
koder aka kdanilov652cd802015-04-13 12:21:07 +0300271 if barrier.wait():
koder aka kdanilovea22c3d2015-04-21 03:42:22 +0300272 templ = "Test should takes about {0}." + \
273 " Should finish at {1}," + \
274 " will wait at most till {2}"
275 now_dt = datetime.datetime.now()
276 end_dt = now_dt + datetime.timedelta(0, exec_time)
277 wait_till = now_dt + datetime.timedelta(0, timeout)
278
279 logger.info(templ.format(exec_time_str,
280 end_dt.strftime("%H:%M:%S"),
281 wait_till.strftime("%H:%M:%S")))
koder aka kdanilov652cd802015-04-13 12:21:07 +0300282
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300283 self.run_over_ssh(cmd)
284 logger.debug("Test started in screen {0}".format(screen_name))
285
286 end_of_wait_time = timeout + time.time()
287
288 # time_till_check = random.randint(30, 90)
289 time_till_check = 1
290
291 pid = None
292 no_pid_file = True
293 tcp_conn_timeout = 30
294 pid_get_timeout = 30 + time.time()
koder aka kdanilov783b4542015-04-23 18:57:04 +0300295 connection_ok = True
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300296
297 # TODO: add monitoring socket
298 if self.node.connection is not Local:
299 self.node.connection.close()
300
koder aka kdanilov783b4542015-04-23 18:57:04 +0300301 conn_id = self.node.get_conn_id()
302
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300303 while end_of_wait_time > time.time():
304 conn = None
305 time.sleep(time_till_check)
306
307 try:
308 if self.node.connection is not Local:
309 conn = connect(self.node.conn_url,
310 conn_timeout=tcp_conn_timeout)
311 else:
312 conn = self.node.connection
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300313
koder aka kdanilov783b4542015-04-23 18:57:04 +0300314 try:
315 with conn.open_sftp() as sftp:
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300316 try:
317 pid = read_from_remote(sftp, self.pid_file)
318 no_pid_file = False
319 except (NameError, IOError):
320 no_pid_file = True
321 finally:
322 if conn is not Local:
323 conn.close()
324 conn = None
koder aka kdanilov783b4542015-04-23 18:57:04 +0300325
326 if no_pid_file:
327 if pid is None:
328 if time.time() > pid_get_timeout:
329 msg = ("On node {0} pid file doesn't " +
330 "appears in time")
331 logger.error(msg.format(conn_id))
332 raise RuntimeError("Start timeout")
333 else:
334 # execution finished
335 break
336 if not connection_ok:
337 msg = "Connection with {0} is restored"
338 logger.debug(msg.format(conn_id))
339 connection_ok = True
340
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300341 except (socket.error, SSHException, EOFError) as exc:
koder aka kdanilov783b4542015-04-23 18:57:04 +0300342 if connection_ok:
343 connection_ok = False
344 msg = "Lost connection with " + conn_id
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300345 msg += ". Error: " + str(exc)
koder aka kdanilov783b4542015-04-23 18:57:04 +0300346 logger.debug(msg)
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300347
348 logger.debug("Done")
349
350 if self.node.connection is not Local:
351 timeout = tcp_conn_timeout * 3
352 self.node.connection = connect(self.node.conn_url,
353 conn_timeout=timeout)
354
koder aka kdanilov783b4542015-04-23 18:57:04 +0300355 with self.node.connection.open_sftp() as sftp:
356 # try to reboot and then connect
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300357 out_err = read_from_remote(sftp,
koder aka kdanilov783b4542015-04-23 18:57:04 +0300358 self.log_fl)
koder aka kdanilov2c473092015-03-29 17:12:13 +0300359 finally:
360 barrier.exit()
361
koder aka kdanilov652cd802015-04-13 12:21:07 +0300362 self.on_result(out_err, cmd)
363
koder aka kdanilov66839a92015-04-11 13:22:31 +0300364 def on_result(self, out_err, cmd):
365 try:
366 for data in parse_output(out_err):
367 self.on_result_cb(data)
368 except Exception as exc:
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300369 msg_templ = "Error during postprocessing results: {0!s}"
370 raise RuntimeError(msg_templ.format(exc))
koder aka kdanilov66839a92015-04-11 13:22:31 +0300371
372 def merge_results(self, results):
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300373 if len(results) == 0:
374 return None
375
koder aka kdanilov66839a92015-04-11 13:22:31 +0300376 merged_result = results[0]
377 merged_data = merged_result['res']
378 expected_keys = set(merged_data.keys())
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300379 mergable_fields = ['bw', 'clat', 'iops', 'lat', 'slat']
koder aka kdanilov66839a92015-04-11 13:22:31 +0300380
381 for res in results[1:]:
382 assert res['__meta__'] == merged_result['__meta__']
383
384 data = res['res']
385 diff = set(data.keys()).symmetric_difference(expected_keys)
386
387 msg = "Difference: {0}".format(",".join(diff))
388 assert len(diff) == 0, msg
389
390 for testname, test_data in data.items():
391 res_test_data = merged_data[testname]
392
393 diff = set(test_data.keys()).symmetric_difference(
394 res_test_data.keys())
395
396 msg = "Difference: {0}".format(",".join(diff))
397 assert len(diff) == 0, msg
398
399 for k, v in test_data.items():
400 if k in mergable_fields:
401 res_test_data[k].extend(v)
402 else:
403 msg = "{0!r} != {1!r}".format(res_test_data[k], v)
404 assert res_test_data[k] == v, msg
405
406 return merged_result
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300407
408 @classmethod
409 def format_for_console(cls, data):
410 return io_formatter.format_results_for_console(data)