blob: 72ba4cfa82ff59ee4ef0d6fe198dbdfaab87f050 [file] [log] [blame]
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +03001from __future__ import print_function
2
gstepanov023c1e42015-04-08 15:50:19 +03003import os
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -08004import sys
koder aka kdanilov57ce4db2015-04-25 21:25:51 +03005import time
koder aka kdanilov2c473092015-03-29 17:12:13 +03006import Queue
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -08007import pprint
koder aka kdanilove21d7472015-02-14 19:02:04 -08008import logging
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -08009import argparse
koder aka kdanilov168f6092015-04-19 02:33:38 +030010import functools
koder aka kdanilov2c473092015-03-29 17:12:13 +030011import threading
koder aka kdanilov168f6092015-04-19 02:33:38 +030012import contextlib
koder aka kdanilov7306c642015-04-23 15:29:45 +030013import subprocess
koder aka kdanilov2c473092015-03-29 17:12:13 +030014import collections
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -080015
koder aka kdanilov66839a92015-04-11 13:22:31 +030016import yaml
koder aka kdanilov2c473092015-03-29 17:12:13 +030017from concurrent.futures import ThreadPoolExecutor
koder aka kdanilov6c491062015-04-09 22:33:13 +030018
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030019from wally import pretty_yaml
koder aka kdanilovf86d7af2015-05-06 04:01:54 +030020from wally.hw_info import get_hw_info
21from wally.discover import discover, Node
koder aka kdanilov63ad2062015-04-27 13:11:40 +030022from wally.timeseries import SensorDatastore
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030023from wally import utils, report, ssh_utils, start_vms
Yulia Portnovab1a15072015-05-06 14:59:25 +030024from wally.suits.itest import IOPerfTest, PgBenchTest, MysqlTest
koder aka kdanilov63ad2062015-04-27 13:11:40 +030025from wally.sensors_utils import deploy_sensors_stage
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030026from wally.config import cfg_dict, load_config, setup_loggers
koder aka kdanilov63ad2062015-04-27 13:11:40 +030027
koder aka kdanilov57ce4db2015-04-25 21:25:51 +030028
29try:
30 from wally import webui
31except ImportError:
32 webui = None
koder aka kdanilov2c473092015-03-29 17:12:13 +030033
34
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +030035logger = logging.getLogger("wally")
koder aka kdanilovcee43342015-04-14 22:52:53 +030036
koder aka kdanilov7acd6bd2015-02-12 14:28:30 -080037
Yulia Portnova7ddfa732015-02-24 17:32:58 +020038def format_result(res, formatter):
koder aka kdanilove21d7472015-02-14 19:02:04 -080039 data = "\n{0}\n".format("=" * 80)
40 data += pprint.pformat(res) + "\n"
41 data += "{0}\n".format("=" * 80)
koder aka kdanilovfe056622015-02-19 08:46:15 -080042 templ = "{0}\n\n====> {1}\n\n{2}\n\n"
Yulia Portnova7ddfa732015-02-24 17:32:58 +020043 return templ.format(data, formatter(res), "=" * 80)
koder aka kdanilove21d7472015-02-14 19:02:04 -080044
45
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030046class Context(object):
47 def __init__(self):
48 self.build_meta = {}
49 self.nodes = []
50 self.clear_calls_stack = []
51 self.openstack_nodes_ids = []
koder aka kdanilov168f6092015-04-19 02:33:38 +030052 self.sensors_mon_q = None
koder aka kdanilovf86d7af2015-05-06 04:01:54 +030053 self.hw_info = []
koder aka kdanilov1c2b5112015-04-10 16:53:51 +030054
55
koder aka kdanilov168f6092015-04-19 02:33:38 +030056def connect_one(node, vm=False):
koder aka kdanilov0c598a12015-04-21 03:01:40 +030057 if node.conn_url == 'local':
58 node.connection = ssh_utils.connect(node.conn_url)
59 return
60
koder aka kdanilov5d589b42015-03-26 12:25:51 +020061 try:
koder aka kdanilov2c473092015-03-29 17:12:13 +030062 ssh_pref = "ssh://"
63 if node.conn_url.startswith(ssh_pref):
64 url = node.conn_url[len(ssh_pref):]
koder aka kdanilov168f6092015-04-19 02:33:38 +030065
66 if vm:
koder aka kdanilov6b1341a2015-04-21 22:44:21 +030067 conn_timeout = 240
koder aka kdanilov168f6092015-04-19 02:33:38 +030068 else:
koder aka kdanilov6b1341a2015-04-21 22:44:21 +030069 conn_timeout = 30
koder aka kdanilov168f6092015-04-19 02:33:38 +030070
71 node.connection = ssh_utils.connect(url,
koder aka kdanilov6b1341a2015-04-21 22:44:21 +030072 conn_timeout=conn_timeout)
koder aka kdanilov2c473092015-03-29 17:12:13 +030073 else:
74 raise ValueError("Unknown url type {0}".format(node.conn_url))
koder aka kdanilove87ae652015-04-20 02:14:35 +030075 except Exception as exc:
76 # logger.exception("During connect to " + node.get_conn_id())
koder aka kdanilovec1b9732015-04-23 20:43:29 +030077 msg = "During connect to {0}: {1!s}".format(node.get_conn_id(),
78 exc)
koder aka kdanilove87ae652015-04-20 02:14:35 +030079 logger.error(msg)
koder aka kdanilov168f6092015-04-19 02:33:38 +030080 node.connection = None
koder aka kdanilov5d589b42015-03-26 12:25:51 +020081
82
koder aka kdanilov168f6092015-04-19 02:33:38 +030083def connect_all(nodes, vm=False):
koder aka kdanilov2c473092015-03-29 17:12:13 +030084 logger.info("Connecting to nodes")
85 with ThreadPoolExecutor(32) as pool:
koder aka kdanilov168f6092015-04-19 02:33:38 +030086 connect_one_f = functools.partial(connect_one, vm=vm)
87 list(pool.map(connect_one_f, nodes))
koder aka kdanilov2c473092015-03-29 17:12:13 +030088
89
koder aka kdanilovf86d7af2015-05-06 04:01:54 +030090def collect_hw_info_stage(cfg, ctx):
91 if os.path.exists(cfg['hwreport_fname']):
92 msg = "{0} already exists. Skip hw info"
93 logger.info(msg.format(cfg['hwreport_fname']))
94 return
95
96 with ThreadPoolExecutor(32) as pool:
97 connections = (node.connection for node in ctx.nodes)
98 ctx.hw_info.extend(pool.map(get_hw_info, connections))
99
100 with open(cfg['hwreport_fname'], 'w') as hwfd:
101 for node, info in zip(ctx.nodes, ctx.hw_info):
102 hwfd.write("-" * 60 + "\n")
103 hwfd.write("Roles : " + ", ".join(node.roles) + "\n")
104 hwfd.write(str(info) + "\n")
105 hwfd.write("-" * 60 + "\n\n")
106
107 if info.hostname is not None:
108 fname = os.path.join(
109 cfg_dict['hwinfo_directory'],
110 info.hostname + "_lshw.xml")
111
112 with open(fname, "w") as fd:
113 fd.write(info.raw)
114 logger.info("Hardware report stored in " + cfg['hwreport_fname'])
115 logger.debug("Raw hardware info in " + cfg['hwinfo_directory'] + " folder")
116
117
koder aka kdanilov652cd802015-04-13 12:21:07 +0300118def test_thread(test, node, barrier, res_q):
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300119 exc = None
koder aka kdanilov2c473092015-03-29 17:12:13 +0300120 try:
koder aka kdanilova047e1b2015-04-21 23:16:59 +0300121 logger.debug("Run preparation for {0}".format(node.get_conn_id()))
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300122 test.pre_run()
koder aka kdanilova047e1b2015-04-21 23:16:59 +0300123 logger.debug("Run test for {0}".format(node.get_conn_id()))
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300124 test.run(barrier)
koder aka kdanilove2de58c2015-04-24 22:59:36 +0300125 except utils.StopTestError as exc:
126 pass
koder aka kdanilov652cd802015-04-13 12:21:07 +0300127 except Exception as exc:
koder aka kdanilove2de58c2015-04-24 22:59:36 +0300128 msg = "In test {0} for node {1}"
129 msg = msg.format(test, node.get_conn_id())
130 logger.exception(msg)
131 exc = utils.StopTestError(msg, exc)
koder aka kdanilov2c473092015-03-29 17:12:13 +0300132
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300133 try:
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300134 test.cleanup()
koder aka kdanilove2de58c2015-04-24 22:59:36 +0300135 except utils.StopTestError as exc1:
136 if exc is None:
137 exc = exc1
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300138 except:
139 msg = "Duringf cleanup - in test {0} for node {1}"
140 logger.exception(msg.format(test, node))
141
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300142 if exc is not None:
143 res_q.put(exc)
koder aka kdanilov2c473092015-03-29 17:12:13 +0300144
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300145
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300146def run_tests(cfg, test_block, nodes):
koder aka kdanilov2c473092015-03-29 17:12:13 +0300147 tool_type_mapper = {
148 "io": IOPerfTest,
149 "pgbench": PgBenchTest,
Yulia Portnovab1a15072015-05-06 14:59:25 +0300150 "mysql": MysqlTest,
koder aka kdanilov2c473092015-03-29 17:12:13 +0300151 }
152
153 test_nodes = [node for node in nodes
154 if 'testnode' in node.roles]
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300155 test_number_per_type = {}
koder aka kdanilov2c473092015-03-29 17:12:13 +0300156 res_q = Queue.Queue()
157
koder aka kdanilovcee43342015-04-14 22:52:53 +0300158 for name, params in test_block.items():
159 logger.info("Starting {0} tests".format(name))
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300160 test_num = test_number_per_type.get(name, 0)
161 test_number_per_type[name] = test_num + 1
koder aka kdanilovcee43342015-04-14 22:52:53 +0300162 threads = []
163 barrier = utils.Barrier(len(test_nodes))
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300164 coord_q = Queue.Queue()
165 test_cls = tool_type_mapper[name]
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300166 rem_folder = cfg['default_test_local_folder'].format(name=name)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300167
koder aka kdanilovabd6ead2015-04-24 02:03:07 +0300168 for idx, node in enumerate(test_nodes):
koder aka kdanilovcee43342015-04-14 22:52:53 +0300169 msg = "Starting {0} test on {1} node"
170 logger.debug(msg.format(name, node.conn_url))
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300171
172 dr = os.path.join(
173 cfg_dict['test_log_directory'],
174 "{0}_{1}_{2}".format(name, test_num, node.get_ip())
175 )
176
177 if not os.path.exists(dr):
178 os.makedirs(dr)
179
koder aka kdanilovabd6ead2015-04-24 02:03:07 +0300180 test = test_cls(options=params,
181 is_primary=(idx == 0),
182 on_result_cb=res_q.put,
183 test_uuid=cfg['run_uuid'],
184 node=node,
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300185 remote_dir=rem_folder,
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300186 log_directory=dr,
187 coordination_queue=coord_q)
koder aka kdanilovcee43342015-04-14 22:52:53 +0300188 th = threading.Thread(None, test_thread, None,
189 (test, node, barrier, res_q))
190 threads.append(th)
191 th.daemon = True
192 th.start()
koder aka kdanilov2c473092015-03-29 17:12:13 +0300193
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300194 th = threading.Thread(None, test_cls.coordination_th, None,
195 (coord_q, barrier, len(threads)))
196 threads.append(th)
197 th.daemon = True
198 th.start()
199
koder aka kdanilovcee43342015-04-14 22:52:53 +0300200 def gather_results(res_q, results):
201 while not res_q.empty():
202 val = res_q.get()
koder aka kdanilov66839a92015-04-11 13:22:31 +0300203
koder aka kdanilove2de58c2015-04-24 22:59:36 +0300204 if isinstance(val, utils.StopTestError):
205 raise val
206
koder aka kdanilovcee43342015-04-14 22:52:53 +0300207 if isinstance(val, Exception):
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300208 msg = "Exception during test execution: {0!s}"
209 raise ValueError(msg.format(val))
koder aka kdanilov652cd802015-04-13 12:21:07 +0300210
koder aka kdanilovcee43342015-04-14 22:52:53 +0300211 results.append(val)
koder aka kdanilov652cd802015-04-13 12:21:07 +0300212
koder aka kdanilovcee43342015-04-14 22:52:53 +0300213 results = []
koder aka kdanilov652cd802015-04-13 12:21:07 +0300214
koder aka kdanilove87ae652015-04-20 02:14:35 +0300215 # MAX_WAIT_TIME = 10
216 # end_time = time.time() + MAX_WAIT_TIME
217
218 # while time.time() < end_time:
koder aka kdanilovcee43342015-04-14 22:52:53 +0300219 while True:
220 for th in threads:
221 th.join(1)
222 gather_results(res_q, results)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300223 # if time.time() > end_time:
224 # break
koder aka kdanilov652cd802015-04-13 12:21:07 +0300225
koder aka kdanilovcee43342015-04-14 22:52:53 +0300226 if all(not th.is_alive() for th in threads):
227 break
koder aka kdanilov652cd802015-04-13 12:21:07 +0300228
koder aka kdanilove87ae652015-04-20 02:14:35 +0300229 # if any(th.is_alive() for th in threads):
230 # logger.warning("Some test threads still running")
231
koder aka kdanilovcee43342015-04-14 22:52:53 +0300232 gather_results(res_q, results)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300233 result = test_cls.merge_results(results)
koder aka kdanilov63ad2062015-04-27 13:11:40 +0300234 result['__test_meta__'] = {'testnodes_count': len(test_nodes)}
235 yield name, result
koder aka kdanilov2c473092015-03-29 17:12:13 +0300236
237
koder aka kdanilovda45e882015-04-06 02:24:42 +0300238def log_nodes_statistic(_, ctx):
239 nodes = ctx.nodes
koder aka kdanilov2c473092015-03-29 17:12:13 +0300240 logger.info("Found {0} nodes total".format(len(nodes)))
241 per_role = collections.defaultdict(lambda: 0)
242 for node in nodes:
243 for role in node.roles:
244 per_role[role] += 1
245
246 for role, count in sorted(per_role.items()):
247 logger.debug("Found {0} nodes with role {1}".format(count, role))
248
249
koder aka kdanilovda45e882015-04-06 02:24:42 +0300250def connect_stage(cfg, ctx):
251 ctx.clear_calls_stack.append(disconnect_stage)
252 connect_all(ctx.nodes)
253
koder aka kdanilov168f6092015-04-19 02:33:38 +0300254 all_ok = True
koder aka kdanilovda45e882015-04-06 02:24:42 +0300255
koder aka kdanilov168f6092015-04-19 02:33:38 +0300256 for node in ctx.nodes:
257 if node.connection is None:
258 if 'testnode' in node.roles:
259 msg = "Can't connect to testnode {0}"
260 raise RuntimeError(msg.format(node.get_conn_id()))
261 else:
262 msg = "Node {0} would be excluded - can't connect"
263 logger.warning(msg.format(node.get_conn_id()))
264 all_ok = False
265
266 if all_ok:
267 logger.info("All nodes connected successfully")
268
269 ctx.nodes = [node for node in ctx.nodes
270 if node.connection is not None]
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300271
272
koder aka kdanilovda45e882015-04-06 02:24:42 +0300273def discover_stage(cfg, ctx):
koder aka kdanilov652cd802015-04-13 12:21:07 +0300274 if cfg.get('discover') is not None:
koder aka kdanilovda45e882015-04-06 02:24:42 +0300275 discover_objs = [i.strip() for i in cfg['discover'].strip().split(",")]
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300276
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300277 nodes = discover(ctx,
278 discover_objs,
279 cfg['clouds'],
280 cfg['var_dir'],
281 not cfg['dont_discover_nodes'])
koder aka kdanilov168f6092015-04-19 02:33:38 +0300282
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300283 ctx.nodes.extend(nodes)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300284
285 for url, roles in cfg.get('explicit_nodes', {}).items():
286 ctx.nodes.append(Node(url, roles.split(",")))
287
288
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300289def save_nodes_stage(cfg, ctx):
290 cluster = {}
291 for node in ctx.nodes:
292 roles = node.roles[:]
293 if 'testnode' in roles:
294 roles.remove('testnode')
295
296 if len(roles) != 0:
297 cluster[node.conn_url] = roles
298
299 with open(cfg['nodes_report_file'], "w") as fd:
300 fd.write(pretty_yaml.dumps(cluster))
301
302
303def reuse_vms_stage(vm_name_pattern, conn_pattern):
304 def reuse_vms(cfg, ctx):
305 try:
306 msg = "Looking for vm with name like {0}".format(vm_name_pattern)
307 logger.debug(msg)
308
309 os_creds = get_OS_credentials(cfg, ctx, "clouds")
310 conn = start_vms.nova_connect(**os_creds)
311 for ip in start_vms.find_vms(conn, vm_name_pattern):
312 node = Node(conn_pattern.format(ip=ip), ['testnode'])
313 ctx.nodes.append(node)
314 except Exception as exc:
315 msg = "Vm like {0} lookup failed".format(vm_name_pattern)
316 logger.exception(msg)
317 raise utils.StopTestError(msg, exc)
318
319 return reuse_vms
320
321
koder aka kdanilove87ae652015-04-20 02:14:35 +0300322def get_OS_credentials(cfg, ctx, creds_type):
koder aka kdanilovcee43342015-04-14 22:52:53 +0300323 creds = None
koder aka kdanilovda45e882015-04-06 02:24:42 +0300324
koder aka kdanilovcee43342015-04-14 22:52:53 +0300325 if creds_type == 'clouds':
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300326 logger.info("Using OS credentials from 'cloud' section")
koder aka kdanilovcee43342015-04-14 22:52:53 +0300327 if 'openstack' in cfg['clouds']:
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300328 os_cfg = cfg['clouds']['openstack']
koder aka kdanilovcee43342015-04-14 22:52:53 +0300329
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300330 tenant = os_cfg['OS_TENANT_NAME'].strip()
331 user = os_cfg['OS_USERNAME'].strip()
332 passwd = os_cfg['OS_PASSWORD'].strip()
333 auth_url = os_cfg['OS_AUTH_URL'].strip()
334
koder aka kdanilovcee43342015-04-14 22:52:53 +0300335 elif 'fuel' in cfg['clouds'] and \
336 'openstack_env' in cfg['clouds']['fuel']:
337 creds = ctx.fuel_openstack_creds
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300338
koder aka kdanilovcee43342015-04-14 22:52:53 +0300339 elif creds_type == 'ENV':
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300340 logger.info("Using OS credentials from shell environment")
koder aka kdanilovcee43342015-04-14 22:52:53 +0300341 user, passwd, tenant, auth_url = start_vms.ostack_get_creds()
342 elif os.path.isfile(creds_type):
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300343 logger.info("Using OS credentials from " + creds_type)
koder aka kdanilov7306c642015-04-23 15:29:45 +0300344 fc = open(creds_type).read()
345
346 echo = 'echo "$OS_TENANT_NAME:$OS_USERNAME:$OS_PASSWORD@$OS_AUTH_URL"'
347
348 p = subprocess.Popen(['/bin/bash'], shell=False,
349 stdout=subprocess.PIPE,
350 stdin=subprocess.PIPE,
351 stderr=subprocess.STDOUT)
352 p.stdin.write(fc + "\n" + echo)
353 p.stdin.close()
354 code = p.wait()
355 data = p.stdout.read().strip()
356
357 if code != 0:
358 msg = "Failed to get creads from openrc file: " + data
359 logger.error(msg)
360 raise RuntimeError(msg)
361
362 try:
363 user, tenant, passwd_auth_url = data.split(':', 2)
364 passwd, auth_url = passwd_auth_url.rsplit("@", 1)
365 assert (auth_url.startswith("https://") or
366 auth_url.startswith("http://"))
367 except Exception:
368 msg = "Failed to get creads from openrc file: " + data
369 logger.exception(msg)
370 raise
371
koder aka kdanilovcee43342015-04-14 22:52:53 +0300372 else:
373 msg = "Creds {0!r} isn't supported".format(creds_type)
374 raise ValueError(msg)
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300375
koder aka kdanilovcee43342015-04-14 22:52:53 +0300376 if creds is None:
377 creds = {'name': user,
378 'passwd': passwd,
379 'tenant': tenant,
380 'auth_url': auth_url}
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300381
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300382 msg = "OS_CREDS: user={name} tenant={tenant} auth_url={auth_url}"
383 logger.debug(msg.format(**creds))
koder aka kdanilovcee43342015-04-14 22:52:53 +0300384 return creds
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300385
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300386
koder aka kdanilov168f6092015-04-19 02:33:38 +0300387@contextlib.contextmanager
388def create_vms_ctx(ctx, cfg, config):
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300389 params = cfg['vm_configs'][config['cfg_name']].copy()
koder aka kdanilov168f6092015-04-19 02:33:38 +0300390 os_nodes_ids = []
391
392 os_creds_type = config['creds']
koder aka kdanilove87ae652015-04-20 02:14:35 +0300393 os_creds = get_OS_credentials(cfg, ctx, os_creds_type)
koder aka kdanilov168f6092015-04-19 02:33:38 +0300394 start_vms.nova_connect(**os_creds)
395
396 logger.info("Preparing openstack")
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300397 params.update(config)
398 params['keypair_file_private'] = params['keypair_name'] + ".pem"
399 params['group_name'] = cfg_dict['run_uuid']
400
401 start_vms.prepare_os_subpr(params=params, **os_creds)
koder aka kdanilov168f6092015-04-19 02:33:38 +0300402
403 new_nodes = []
404 try:
koder aka kdanilov168f6092015-04-19 02:33:38 +0300405 for new_node, node_id in start_vms.launch_vms(params):
406 new_node.roles.append('testnode')
407 ctx.nodes.append(new_node)
408 os_nodes_ids.append(node_id)
409 new_nodes.append(new_node)
410
411 store_nodes_in_log(cfg, os_nodes_ids)
412 ctx.openstack_nodes_ids = os_nodes_ids
413
414 yield new_nodes
415
416 finally:
417 if not cfg['keep_vm']:
418 shut_down_vms_stage(cfg, ctx)
419
420
koder aka kdanilovcee43342015-04-14 22:52:53 +0300421def run_tests_stage(cfg, ctx):
422 ctx.results = []
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300423
koder aka kdanilovcee43342015-04-14 22:52:53 +0300424 if 'tests' not in cfg:
425 return
gstepanov023c1e42015-04-08 15:50:19 +0300426
koder aka kdanilovcee43342015-04-14 22:52:53 +0300427 for group in cfg['tests']:
428
429 assert len(group.items()) == 1
430 key, config = group.items()[0]
431
432 if 'start_test_nodes' == key:
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300433 if 'openstack' not in config:
434 msg = "No openstack block in config - can't spawn vm's"
435 logger.error(msg)
436 raise utils.StopTestError(msg)
437
438 with create_vms_ctx(ctx, cfg, config['openstack']) as new_nodes:
koder aka kdanilov168f6092015-04-19 02:33:38 +0300439 connect_all(new_nodes, True)
koder aka kdanilovcee43342015-04-14 22:52:53 +0300440
koder aka kdanilov168f6092015-04-19 02:33:38 +0300441 for node in new_nodes:
442 if node.connection is None:
443 msg = "Failed to connect to vm {0}"
444 raise RuntimeError(msg.format(node.get_conn_id()))
koder aka kdanilovcee43342015-04-14 22:52:53 +0300445
koder aka kdanilov168f6092015-04-19 02:33:38 +0300446 deploy_sensors_stage(cfg_dict,
447 ctx,
448 nodes=new_nodes,
449 undeploy=False)
koder aka kdanilov12ae0632015-04-15 01:13:43 +0300450
koder aka kdanilove87ae652015-04-20 02:14:35 +0300451 if not cfg['no_tests']:
452 for test_group in config.get('tests', []):
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300453 test_res = run_tests(cfg, test_group, ctx.nodes)
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300454 ctx.results.extend(test_res)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300455 else:
koder aka kdanilove87ae652015-04-20 02:14:35 +0300456 if not cfg['no_tests']:
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300457 test_res = run_tests(cfg, group, ctx.nodes)
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300458 ctx.results.extend(test_res)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300459
gstepanov023c1e42015-04-08 15:50:19 +0300460
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300461def shut_down_vms_stage(cfg, ctx):
koder aka kdanilov66839a92015-04-11 13:22:31 +0300462 vm_ids_fname = cfg_dict['vm_ids_fname']
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300463 if ctx.openstack_nodes_ids is None:
koder aka kdanilov66839a92015-04-11 13:22:31 +0300464 nodes_ids = open(vm_ids_fname).read().split()
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300465 else:
466 nodes_ids = ctx.openstack_nodes_ids
467
koder aka kdanilov652cd802015-04-13 12:21:07 +0300468 if len(nodes_ids) != 0:
469 logger.info("Removing nodes")
470 start_vms.clear_nodes(nodes_ids)
471 logger.info("Nodes has been removed")
gstepanov023c1e42015-04-08 15:50:19 +0300472
koder aka kdanilov66839a92015-04-11 13:22:31 +0300473 if os.path.exists(vm_ids_fname):
474 os.remove(vm_ids_fname)
gstepanov023c1e42015-04-08 15:50:19 +0300475
koder aka kdanilov66839a92015-04-11 13:22:31 +0300476
477def store_nodes_in_log(cfg, nodes_ids):
478 with open(cfg['vm_ids_fname'], 'w') as fd:
479 fd.write("\n".join(nodes_ids))
gstepanov023c1e42015-04-08 15:50:19 +0300480
481
482def clear_enviroment(cfg, ctx):
koder aka kdanilov66839a92015-04-11 13:22:31 +0300483 if os.path.exists(cfg_dict['vm_ids_fname']):
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300484 shut_down_vms_stage(cfg, ctx)
gstepanov023c1e42015-04-08 15:50:19 +0300485
486
koder aka kdanilovda45e882015-04-06 02:24:42 +0300487def disconnect_stage(cfg, ctx):
koder aka kdanilov652cd802015-04-13 12:21:07 +0300488 ssh_utils.close_all_sessions()
489
koder aka kdanilovda45e882015-04-06 02:24:42 +0300490 for node in ctx.nodes:
491 if node.connection is not None:
492 node.connection.close()
493
494
koder aka kdanilov66839a92015-04-11 13:22:31 +0300495def store_raw_results_stage(cfg, ctx):
496
497 raw_results = os.path.join(cfg_dict['var_dir'], 'raw_results.yaml')
498
499 if os.path.exists(raw_results):
500 cont = yaml.load(open(raw_results).read())
501 else:
502 cont = []
503
koder aka kdanilov168f6092015-04-19 02:33:38 +0300504 cont.extend(utils.yamable(ctx.results))
koder aka kdanilov66839a92015-04-11 13:22:31 +0300505 raw_data = pretty_yaml.dumps(cont)
506
507 with open(raw_results, "w") as fd:
508 fd.write(raw_data)
509
510
511def console_report_stage(cfg, ctx):
512 for tp, data in ctx.results:
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300513 if 'io' == tp and data is not None:
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300514 dinfo = report.process_disk_info(data)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300515 print("\n")
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300516 print(IOPerfTest.format_for_console(data, dinfo))
koder aka kdanilove87ae652015-04-20 02:14:35 +0300517 print("\n")
Yulia Portnova1f123962015-05-06 18:48:11 +0300518 if tp in ['mysql', 'pgbench'] and data is not None:
Yulia Portnovab1a15072015-05-06 14:59:25 +0300519 print("\n")
520 print(MysqlTest.format_for_console(data))
521 print("\n")
koder aka kdanilov66839a92015-04-11 13:22:31 +0300522
523
koder aka kdanilove87ae652015-04-20 02:14:35 +0300524def html_report_stage(cfg, ctx):
Yulia Portnova8ca20572015-04-14 14:09:39 +0300525 html_rep_fname = cfg['html_report_file']
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300526 found = False
527 for tp, data in ctx.results:
528 if 'io' == tp and data is not None:
529 if found:
530 logger.error("Making reports for more than one " +
531 "io block isn't supported! All " +
532 "report, except first are skipped")
533 continue
534 found = True
535 dinfo = report.process_disk_info(data)
536 report.make_io_report(dinfo, data, html_rep_fname,
537 lab_info=ctx.hw_info)
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300538
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300539 text_rep_fname = cfg_dict['text_report_file']
540 with open(text_rep_fname, "w") as fd:
541 fd.write(IOPerfTest.format_for_console(data, dinfo))
koder aka kdanilov652cd802015-04-13 12:21:07 +0300542 fd.write("\n")
543 fd.flush()
544
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300545 logger.info("Text report were stored in " + text_rep_fname)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300546
547
548def complete_log_nodes_statistic(cfg, ctx):
549 nodes = ctx.nodes
550 for node in nodes:
551 logger.debug(str(node))
552
553
koder aka kdanilov66839a92015-04-11 13:22:31 +0300554def load_data_from(var_dir):
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300555 def load_data_from_file(cfg, ctx):
koder aka kdanilov66839a92015-04-11 13:22:31 +0300556 raw_results = os.path.join(var_dir, 'raw_results.yaml')
557 ctx.results = yaml.load(open(raw_results).read())
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300558 return load_data_from_file
gstepanovcd256d62015-04-07 17:47:32 +0300559
560
koder aka kdanilov57ce4db2015-04-25 21:25:51 +0300561def start_web_ui(cfg, ctx):
562 if webui is None:
563 logger.error("Can't start webui. Install cherrypy module")
564 ctx.web_thread = None
565 else:
566 th = threading.Thread(None, webui.web_main_thread, "webui", (None,))
567 th.daemon = True
568 th.start()
569 ctx.web_thread = th
570
571
572def stop_web_ui(cfg, ctx):
573 webui.web_main_stop()
574 time.sleep(1)
575
576
koder aka kdanilovcee43342015-04-14 22:52:53 +0300577def parse_args(argv):
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300578 descr = "Disk io performance test suite"
579 parser = argparse.ArgumentParser(prog='wally', description=descr)
koder aka kdanilovcee43342015-04-14 22:52:53 +0300580
581 parser.add_argument("-l", dest='extra_logs',
582 action='store_true', default=False,
583 help="print some extra log info")
koder aka kdanilovcee43342015-04-14 22:52:53 +0300584 parser.add_argument("-b", '--build_description',
585 type=str, default="Build info")
586 parser.add_argument("-i", '--build_id', type=str, default="id")
587 parser.add_argument("-t", '--build_type', type=str, default="GA")
588 parser.add_argument("-u", '--username', type=str, default="admin")
koder aka kdanilove87ae652015-04-20 02:14:35 +0300589 parser.add_argument("-n", '--no-tests', action='store_true',
590 help="Don't run tests", default=False)
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300591 parser.add_argument("-p", '--post-process-only', metavar="VAR_DIR",
592 help="Only process data from previour run")
593 parser.add_argument("-k", '--keep-vm', action='store_true',
594 help="Don't remove test vm's", default=False)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300595 parser.add_argument("-d", '--dont-discover-nodes', action='store_true',
596 help="Don't connect/discover fuel nodes",
597 default=False)
koder aka kdanilova047e1b2015-04-21 23:16:59 +0300598 parser.add_argument("-r", '--no-html-report', action='store_true',
599 help="Skip html report", default=False)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300600 parser.add_argument("--params", metavar="testname.paramname",
koder aka kdanilov63ad2062015-04-27 13:11:40 +0300601 help="Test params", default=[])
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300602 parser.add_argument("--reuse-vms", default=None, metavar="vm_name_prefix")
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300603 parser.add_argument("config_file")
koder aka kdanilovcee43342015-04-14 22:52:53 +0300604
605 return parser.parse_args(argv[1:])
606
607
koder aka kdanilov3f356262015-02-13 08:06:14 -0800608def main(argv):
koder aka kdanilove06762a2015-03-22 23:32:09 +0200609 opts = parse_args(argv)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300610 load_config(opts.config_file, opts.post_process_only)
koder aka kdanilov2c473092015-03-29 17:12:13 +0300611
koder aka kdanilov66839a92015-04-11 13:22:31 +0300612 if opts.post_process_only is not None:
613 stages = [
koder aka kdanilove87ae652015-04-20 02:14:35 +0300614 load_data_from(opts.post_process_only)
koder aka kdanilov66839a92015-04-11 13:22:31 +0300615 ]
616 else:
617 stages = [
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300618 discover_stage
619 ]
620
621 if opts.reuse_vms is not None:
622 pref, ssh_templ = opts.reuse_vms.split(',', 1)
623 stages.append(reuse_vms_stage(pref, ssh_templ))
624
625 stages.extend([
koder aka kdanilov66839a92015-04-11 13:22:31 +0300626 log_nodes_statistic,
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300627 save_nodes_stage,
628 connect_stage])
629
630 if cfg_dict.get('collect_info', True):
631 stages.append(collect_hw_info_stage)
632
633 stages.extend([
koder aka kdanilov66839a92015-04-11 13:22:31 +0300634 deploy_sensors_stage,
635 run_tests_stage,
koder aka kdanilove87ae652015-04-20 02:14:35 +0300636 store_raw_results_stage
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300637 ])
koder aka kdanilov66839a92015-04-11 13:22:31 +0300638
koder aka kdanilove87ae652015-04-20 02:14:35 +0300639 report_stages = [
640 console_report_stage,
koder aka kdanilove87ae652015-04-20 02:14:35 +0300641 ]
642
koder aka kdanilova047e1b2015-04-21 23:16:59 +0300643 if not opts.no_html_report:
644 report_stages.append(html_report_stage)
645
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300646 if cfg_dict.get('logging', {}).get("extra_logs", False) or opts.extra_logs:
647 level = logging.DEBUG
648 else:
649 level = logging.WARNING
650
651 setup_loggers(level, cfg_dict['log_file'])
koder aka kdanilovf4b82c22015-04-11 13:35:25 +0300652
koder aka kdanilov652cd802015-04-13 12:21:07 +0300653 logger.info("All info would be stored into {0}".format(
654 cfg_dict['var_dir']))
gstepanovcd256d62015-04-07 17:47:32 +0300655
koder aka kdanilovda45e882015-04-06 02:24:42 +0300656 ctx = Context()
gstepanovaffcdb12015-04-07 17:18:29 +0300657 ctx.build_meta['build_id'] = opts.build_id
658 ctx.build_meta['build_descrption'] = opts.build_description
659 ctx.build_meta['build_type'] = opts.build_type
660 ctx.build_meta['username'] = opts.username
koder aka kdanilov57ce4db2015-04-25 21:25:51 +0300661 ctx.sensors_data = SensorDatastore()
koder aka kdanilove87ae652015-04-20 02:14:35 +0300662
koder aka kdanilov168f6092015-04-19 02:33:38 +0300663 cfg_dict['keep_vm'] = opts.keep_vm
koder aka kdanilove87ae652015-04-20 02:14:35 +0300664 cfg_dict['no_tests'] = opts.no_tests
665 cfg_dict['dont_discover_nodes'] = opts.dont_discover_nodes
koder aka kdanilov6c491062015-04-09 22:33:13 +0300666
koder aka kdanilov57ce4db2015-04-25 21:25:51 +0300667 if cfg_dict.get('run_web_ui', False):
668 start_web_ui(cfg_dict, ctx)
669
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300670 msg_templ = "Exception during {0.__name__}: {1!s}"
671 msg_templ_no_exc = "During {0.__name__}"
672
koder aka kdanilovda45e882015-04-06 02:24:42 +0300673 try:
674 for stage in stages:
675 logger.info("Start {0.__name__} stage".format(stage))
676 stage(cfg_dict, ctx)
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300677 except utils.StopTestError as exc:
678 logger.error(msg_templ.format(stage, exc))
679 except Exception:
680 logger.exception(msg_templ_no_exc.format(stage))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300681 finally:
682 exc, cls, tb = sys.exc_info()
683 for stage in ctx.clear_calls_stack[::-1]:
684 try:
685 logger.info("Start {0.__name__} stage".format(stage))
686 stage(cfg_dict, ctx)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300687 except utils.StopTestError as cleanup_exc:
688 logger.error(msg_templ.format(stage, cleanup_exc))
689 except Exception:
690 logger.exception(msg_templ_no_exc.format(stage))
691
692 logger.debug("Start utils.cleanup")
693 for clean_func, args, kwargs in utils.iter_clean_func():
694 try:
695 clean_func(*args, **kwargs)
696 except utils.StopTestError as cleanup_exc:
697 logger.error(msg_templ.format(stage, cleanup_exc))
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300698 except Exception:
699 logger.exception(msg_templ_no_exc.format(stage))
koder aka kdanilov2c473092015-03-29 17:12:13 +0300700
koder aka kdanilove2de58c2015-04-24 22:59:36 +0300701 if exc is None:
702 for report_stage in report_stages:
703 report_stage(cfg_dict, ctx)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300704
705 logger.info("All info stored in {0} folder".format(cfg_dict['var_dir']))
koder aka kdanilove2de58c2015-04-24 22:59:36 +0300706
koder aka kdanilov57ce4db2015-04-25 21:25:51 +0300707 if cfg_dict.get('run_web_ui', False):
708 stop_web_ui(cfg_dict, ctx)
709
koder aka kdanilove2de58c2015-04-24 22:59:36 +0300710 if exc is None:
711 logger.info("Tests finished successfully")
712 return 0
713 else:
714 logger.error("Tests are failed. See detailed error above")
715 return 1