blob: dc6637fedd54f02aed282963cb3f7e23c8fa813c [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 kdanilov7306c642015-04-23 15:29:45 +030012import subprocess
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +030013import contextlib
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 kdanilovd5ed4da2015-05-07 23:33:23 +0300155 if len(test_nodes) == 0:
156 logger.error("No test nodes found")
157 return
158
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300159 test_number_per_type = {}
koder aka kdanilov2c473092015-03-29 17:12:13 +0300160 res_q = Queue.Queue()
161
koder aka kdanilovcee43342015-04-14 22:52:53 +0300162 for name, params in test_block.items():
163 logger.info("Starting {0} tests".format(name))
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300164 test_num = test_number_per_type.get(name, 0)
165 test_number_per_type[name] = test_num + 1
koder aka kdanilovcee43342015-04-14 22:52:53 +0300166 threads = []
167 barrier = utils.Barrier(len(test_nodes))
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300168 coord_q = Queue.Queue()
169 test_cls = tool_type_mapper[name]
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300170 rem_folder = cfg['default_test_local_folder'].format(name=name)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300171
koder aka kdanilovabd6ead2015-04-24 02:03:07 +0300172 for idx, node in enumerate(test_nodes):
koder aka kdanilovcee43342015-04-14 22:52:53 +0300173 msg = "Starting {0} test on {1} node"
174 logger.debug(msg.format(name, node.conn_url))
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300175
176 dr = os.path.join(
177 cfg_dict['test_log_directory'],
178 "{0}_{1}_{2}".format(name, test_num, node.get_ip())
179 )
180
181 if not os.path.exists(dr):
182 os.makedirs(dr)
183
koder aka kdanilovabd6ead2015-04-24 02:03:07 +0300184 test = test_cls(options=params,
185 is_primary=(idx == 0),
186 on_result_cb=res_q.put,
187 test_uuid=cfg['run_uuid'],
188 node=node,
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300189 remote_dir=rem_folder,
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300190 log_directory=dr,
191 coordination_queue=coord_q)
koder aka kdanilovcee43342015-04-14 22:52:53 +0300192 th = threading.Thread(None, test_thread, None,
193 (test, node, barrier, res_q))
194 threads.append(th)
195 th.daemon = True
196 th.start()
koder aka kdanilov2c473092015-03-29 17:12:13 +0300197
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300198 th = threading.Thread(None, test_cls.coordination_th, None,
199 (coord_q, barrier, len(threads)))
200 threads.append(th)
201 th.daemon = True
202 th.start()
203
koder aka kdanilovcee43342015-04-14 22:52:53 +0300204 def gather_results(res_q, results):
205 while not res_q.empty():
206 val = res_q.get()
koder aka kdanilov66839a92015-04-11 13:22:31 +0300207
koder aka kdanilove2de58c2015-04-24 22:59:36 +0300208 if isinstance(val, utils.StopTestError):
209 raise val
210
koder aka kdanilovcee43342015-04-14 22:52:53 +0300211 if isinstance(val, Exception):
koder aka kdanilovec1b9732015-04-23 20:43:29 +0300212 msg = "Exception during test execution: {0!s}"
213 raise ValueError(msg.format(val))
koder aka kdanilov652cd802015-04-13 12:21:07 +0300214
koder aka kdanilovcee43342015-04-14 22:52:53 +0300215 results.append(val)
koder aka kdanilov652cd802015-04-13 12:21:07 +0300216
koder aka kdanilovcee43342015-04-14 22:52:53 +0300217 results = []
koder aka kdanilov652cd802015-04-13 12:21:07 +0300218
koder aka kdanilove87ae652015-04-20 02:14:35 +0300219 # MAX_WAIT_TIME = 10
220 # end_time = time.time() + MAX_WAIT_TIME
221
222 # while time.time() < end_time:
koder aka kdanilovcee43342015-04-14 22:52:53 +0300223 while True:
224 for th in threads:
225 th.join(1)
226 gather_results(res_q, results)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300227 # if time.time() > end_time:
228 # break
koder aka kdanilov652cd802015-04-13 12:21:07 +0300229
koder aka kdanilovcee43342015-04-14 22:52:53 +0300230 if all(not th.is_alive() for th in threads):
231 break
koder aka kdanilov652cd802015-04-13 12:21:07 +0300232
koder aka kdanilove87ae652015-04-20 02:14:35 +0300233 # if any(th.is_alive() for th in threads):
234 # logger.warning("Some test threads still running")
235
koder aka kdanilovcee43342015-04-14 22:52:53 +0300236 gather_results(res_q, results)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300237 result = test_cls.merge_results(results)
koder aka kdanilov63ad2062015-04-27 13:11:40 +0300238 result['__test_meta__'] = {'testnodes_count': len(test_nodes)}
239 yield name, result
koder aka kdanilov2c473092015-03-29 17:12:13 +0300240
241
koder aka kdanilovda45e882015-04-06 02:24:42 +0300242def log_nodes_statistic(_, ctx):
243 nodes = ctx.nodes
koder aka kdanilov2c473092015-03-29 17:12:13 +0300244 logger.info("Found {0} nodes total".format(len(nodes)))
245 per_role = collections.defaultdict(lambda: 0)
246 for node in nodes:
247 for role in node.roles:
248 per_role[role] += 1
249
250 for role, count in sorted(per_role.items()):
251 logger.debug("Found {0} nodes with role {1}".format(count, role))
252
253
koder aka kdanilovda45e882015-04-06 02:24:42 +0300254def connect_stage(cfg, ctx):
255 ctx.clear_calls_stack.append(disconnect_stage)
256 connect_all(ctx.nodes)
257
koder aka kdanilov168f6092015-04-19 02:33:38 +0300258 all_ok = True
koder aka kdanilovda45e882015-04-06 02:24:42 +0300259
koder aka kdanilov168f6092015-04-19 02:33:38 +0300260 for node in ctx.nodes:
261 if node.connection is None:
262 if 'testnode' in node.roles:
263 msg = "Can't connect to testnode {0}"
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300264 msg = msg.format(node.get_conn_id())
265 logger.error(msg)
266 raise utils.StopTestError(msg)
koder aka kdanilov168f6092015-04-19 02:33:38 +0300267 else:
268 msg = "Node {0} would be excluded - can't connect"
269 logger.warning(msg.format(node.get_conn_id()))
270 all_ok = False
271
272 if all_ok:
273 logger.info("All nodes connected successfully")
274
275 ctx.nodes = [node for node in ctx.nodes
276 if node.connection is not None]
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300277
278
koder aka kdanilovda45e882015-04-06 02:24:42 +0300279def discover_stage(cfg, ctx):
koder aka kdanilov652cd802015-04-13 12:21:07 +0300280 if cfg.get('discover') is not None:
koder aka kdanilovda45e882015-04-06 02:24:42 +0300281 discover_objs = [i.strip() for i in cfg['discover'].strip().split(",")]
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300282
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300283 nodes = discover(ctx,
284 discover_objs,
285 cfg['clouds'],
286 cfg['var_dir'],
287 not cfg['dont_discover_nodes'])
koder aka kdanilov168f6092015-04-19 02:33:38 +0300288
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300289 ctx.nodes.extend(nodes)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300290
291 for url, roles in cfg.get('explicit_nodes', {}).items():
292 ctx.nodes.append(Node(url, roles.split(",")))
293
294
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300295def save_nodes_stage(cfg, ctx):
296 cluster = {}
297 for node in ctx.nodes:
298 roles = node.roles[:]
299 if 'testnode' in roles:
300 roles.remove('testnode')
301
302 if len(roles) != 0:
303 cluster[node.conn_url] = roles
304
305 with open(cfg['nodes_report_file'], "w") as fd:
306 fd.write(pretty_yaml.dumps(cluster))
307
308
309def reuse_vms_stage(vm_name_pattern, conn_pattern):
310 def reuse_vms(cfg, ctx):
311 try:
312 msg = "Looking for vm with name like {0}".format(vm_name_pattern)
313 logger.debug(msg)
314
315 os_creds = get_OS_credentials(cfg, ctx, "clouds")
316 conn = start_vms.nova_connect(**os_creds)
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300317 for ip, vm_id in start_vms.find_vms(conn, vm_name_pattern):
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300318 node = Node(conn_pattern.format(ip=ip), ['testnode'])
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300319 node.os_vm_id = vm_id
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300320 ctx.nodes.append(node)
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300321 except utils.StopTestError:
322 raise
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300323 except Exception as exc:
324 msg = "Vm like {0} lookup failed".format(vm_name_pattern)
325 logger.exception(msg)
326 raise utils.StopTestError(msg, exc)
327
328 return reuse_vms
329
330
koder aka kdanilove87ae652015-04-20 02:14:35 +0300331def get_OS_credentials(cfg, ctx, creds_type):
koder aka kdanilovcee43342015-04-14 22:52:53 +0300332 creds = None
koder aka kdanilovda45e882015-04-06 02:24:42 +0300333
koder aka kdanilovcee43342015-04-14 22:52:53 +0300334 if creds_type == 'clouds':
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300335 logger.info("Using OS credentials from 'cloud' section")
koder aka kdanilovcee43342015-04-14 22:52:53 +0300336 if 'openstack' in cfg['clouds']:
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300337 os_cfg = cfg['clouds']['openstack']
koder aka kdanilovcee43342015-04-14 22:52:53 +0300338
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300339 tenant = os_cfg['OS_TENANT_NAME'].strip()
340 user = os_cfg['OS_USERNAME'].strip()
341 passwd = os_cfg['OS_PASSWORD'].strip()
342 auth_url = os_cfg['OS_AUTH_URL'].strip()
343
koder aka kdanilovcee43342015-04-14 22:52:53 +0300344 elif 'fuel' in cfg['clouds'] and \
345 'openstack_env' in cfg['clouds']['fuel']:
346 creds = ctx.fuel_openstack_creds
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300347
koder aka kdanilovcee43342015-04-14 22:52:53 +0300348 elif creds_type == 'ENV':
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300349 logger.info("Using OS credentials from shell environment")
koder aka kdanilovcee43342015-04-14 22:52:53 +0300350 user, passwd, tenant, auth_url = start_vms.ostack_get_creds()
351 elif os.path.isfile(creds_type):
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300352 logger.info("Using OS credentials from " + creds_type)
koder aka kdanilov7306c642015-04-23 15:29:45 +0300353 fc = open(creds_type).read()
354
355 echo = 'echo "$OS_TENANT_NAME:$OS_USERNAME:$OS_PASSWORD@$OS_AUTH_URL"'
356
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300357 try:
358 data = utils.run_locally(['/bin/bash'], input=fc + "\n" + echo)
359 except subprocess.CalledProcessError as exc:
koder aka kdanilov7306c642015-04-23 15:29:45 +0300360 msg = "Failed to get creads from openrc file: " + data
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300361 logger.exception(msg)
362 raise utils.StopTestError(msg, exc)
koder aka kdanilov7306c642015-04-23 15:29:45 +0300363
364 try:
365 user, tenant, passwd_auth_url = data.split(':', 2)
366 passwd, auth_url = passwd_auth_url.rsplit("@", 1)
367 assert (auth_url.startswith("https://") or
368 auth_url.startswith("http://"))
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300369 except Exception as exc:
koder aka kdanilov7306c642015-04-23 15:29:45 +0300370 msg = "Failed to get creads from openrc file: " + data
371 logger.exception(msg)
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300372 raise utils.StopTestError(msg, exc)
koder aka kdanilov7306c642015-04-23 15:29:45 +0300373
koder aka kdanilovcee43342015-04-14 22:52:53 +0300374 else:
375 msg = "Creds {0!r} isn't supported".format(creds_type)
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300376 logger.error(msg)
377 raise utils.StopTestError(msg, None)
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300378
koder aka kdanilovcee43342015-04-14 22:52:53 +0300379 if creds is None:
380 creds = {'name': user,
381 'passwd': passwd,
382 'tenant': tenant,
383 'auth_url': auth_url}
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300384
koder aka kdanilov46d4f392015-04-24 11:35:00 +0300385 msg = "OS_CREDS: user={name} tenant={tenant} auth_url={auth_url}"
386 logger.debug(msg.format(**creds))
koder aka kdanilovcee43342015-04-14 22:52:53 +0300387 return creds
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300388
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300389
koder aka kdanilov168f6092015-04-19 02:33:38 +0300390@contextlib.contextmanager
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300391def create_vms_ctx(ctx, cfg, config, already_has_count=0):
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300392 params = cfg['vm_configs'][config['cfg_name']].copy()
koder aka kdanilov168f6092015-04-19 02:33:38 +0300393 os_nodes_ids = []
394
395 os_creds_type = config['creds']
koder aka kdanilove87ae652015-04-20 02:14:35 +0300396 os_creds = get_OS_credentials(cfg, ctx, os_creds_type)
koder aka kdanilov168f6092015-04-19 02:33:38 +0300397 start_vms.nova_connect(**os_creds)
398
399 logger.info("Preparing openstack")
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300400 params.update(config)
401 params['keypair_file_private'] = params['keypair_name'] + ".pem"
402 params['group_name'] = cfg_dict['run_uuid']
403
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300404 if not config.get('skip_preparation', False):
405 start_vms.prepare_os_subpr(params=params, **os_creds)
koder aka kdanilov168f6092015-04-19 02:33:38 +0300406
407 new_nodes = []
408 try:
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300409 for new_node, node_id in start_vms.launch_vms(params,
410 already_has_count):
koder aka kdanilov168f6092015-04-19 02:33:38 +0300411 new_node.roles.append('testnode')
412 ctx.nodes.append(new_node)
413 os_nodes_ids.append(node_id)
414 new_nodes.append(new_node)
415
416 store_nodes_in_log(cfg, os_nodes_ids)
417 ctx.openstack_nodes_ids = os_nodes_ids
418
419 yield new_nodes
420
421 finally:
422 if not cfg['keep_vm']:
423 shut_down_vms_stage(cfg, ctx)
424
425
koder aka kdanilovcee43342015-04-14 22:52:53 +0300426def run_tests_stage(cfg, ctx):
427 ctx.results = []
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300428
koder aka kdanilovcee43342015-04-14 22:52:53 +0300429 if 'tests' not in cfg:
430 return
gstepanov023c1e42015-04-08 15:50:19 +0300431
koder aka kdanilovcee43342015-04-14 22:52:53 +0300432 for group in cfg['tests']:
433
434 assert len(group.items()) == 1
435 key, config = group.items()[0]
436
437 if 'start_test_nodes' == key:
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300438 if 'openstack' not in config:
439 msg = "No openstack block in config - can't spawn vm's"
440 logger.error(msg)
441 raise utils.StopTestError(msg)
442
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300443 num_test_nodes = sum(1 for node in ctx.nodes
444 if 'testnode' in node.roles)
445
446 vm_ctx = create_vms_ctx(ctx, cfg, config['openstack'],
447 num_test_nodes)
448 with vm_ctx as new_nodes:
koder aka kdanilov168f6092015-04-19 02:33:38 +0300449 connect_all(new_nodes, True)
koder aka kdanilovcee43342015-04-14 22:52:53 +0300450
koder aka kdanilov168f6092015-04-19 02:33:38 +0300451 for node in new_nodes:
452 if node.connection is None:
453 msg = "Failed to connect to vm {0}"
454 raise RuntimeError(msg.format(node.get_conn_id()))
koder aka kdanilovcee43342015-04-14 22:52:53 +0300455
koder aka kdanilov168f6092015-04-19 02:33:38 +0300456 deploy_sensors_stage(cfg_dict,
457 ctx,
458 nodes=new_nodes,
459 undeploy=False)
koder aka kdanilov12ae0632015-04-15 01:13:43 +0300460
koder aka kdanilove87ae652015-04-20 02:14:35 +0300461 if not cfg['no_tests']:
462 for test_group in config.get('tests', []):
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300463 test_res = run_tests(cfg, test_group, ctx.nodes)
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300464 ctx.results.extend(test_res)
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300465 else:
koder aka kdanilove87ae652015-04-20 02:14:35 +0300466 if not cfg['no_tests']:
koder aka kdanilov2066daf2015-04-23 21:05:41 +0300467 test_res = run_tests(cfg, group, ctx.nodes)
koder aka kdanilov4d4771c2015-04-23 01:32:02 +0300468 ctx.results.extend(test_res)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300469
gstepanov023c1e42015-04-08 15:50:19 +0300470
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300471def shut_down_vms_stage(cfg, ctx):
koder aka kdanilov66839a92015-04-11 13:22:31 +0300472 vm_ids_fname = cfg_dict['vm_ids_fname']
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300473 if ctx.openstack_nodes_ids is None:
koder aka kdanilov66839a92015-04-11 13:22:31 +0300474 nodes_ids = open(vm_ids_fname).read().split()
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300475 else:
476 nodes_ids = ctx.openstack_nodes_ids
477
koder aka kdanilov652cd802015-04-13 12:21:07 +0300478 if len(nodes_ids) != 0:
479 logger.info("Removing nodes")
480 start_vms.clear_nodes(nodes_ids)
481 logger.info("Nodes has been removed")
gstepanov023c1e42015-04-08 15:50:19 +0300482
koder aka kdanilov66839a92015-04-11 13:22:31 +0300483 if os.path.exists(vm_ids_fname):
484 os.remove(vm_ids_fname)
gstepanov023c1e42015-04-08 15:50:19 +0300485
koder aka kdanilov66839a92015-04-11 13:22:31 +0300486
487def store_nodes_in_log(cfg, nodes_ids):
488 with open(cfg['vm_ids_fname'], 'w') as fd:
489 fd.write("\n".join(nodes_ids))
gstepanov023c1e42015-04-08 15:50:19 +0300490
491
492def clear_enviroment(cfg, ctx):
koder aka kdanilov66839a92015-04-11 13:22:31 +0300493 if os.path.exists(cfg_dict['vm_ids_fname']):
koder aka kdanilov1c2b5112015-04-10 16:53:51 +0300494 shut_down_vms_stage(cfg, ctx)
gstepanov023c1e42015-04-08 15:50:19 +0300495
496
koder aka kdanilovda45e882015-04-06 02:24:42 +0300497def disconnect_stage(cfg, ctx):
koder aka kdanilov652cd802015-04-13 12:21:07 +0300498 ssh_utils.close_all_sessions()
499
koder aka kdanilovda45e882015-04-06 02:24:42 +0300500 for node in ctx.nodes:
501 if node.connection is not None:
502 node.connection.close()
503
504
koder aka kdanilov66839a92015-04-11 13:22:31 +0300505def store_raw_results_stage(cfg, ctx):
506
507 raw_results = os.path.join(cfg_dict['var_dir'], 'raw_results.yaml')
508
509 if os.path.exists(raw_results):
510 cont = yaml.load(open(raw_results).read())
511 else:
512 cont = []
513
koder aka kdanilov168f6092015-04-19 02:33:38 +0300514 cont.extend(utils.yamable(ctx.results))
koder aka kdanilov66839a92015-04-11 13:22:31 +0300515 raw_data = pretty_yaml.dumps(cont)
516
517 with open(raw_results, "w") as fd:
518 fd.write(raw_data)
519
520
521def console_report_stage(cfg, ctx):
522 for tp, data in ctx.results:
koder aka kdanilov4500a5f2015-04-17 16:55:17 +0300523 if 'io' == tp and data is not None:
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300524 dinfo = report.process_disk_info(data)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300525 print("\n")
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300526 print(IOPerfTest.format_for_console(data, dinfo))
koder aka kdanilove87ae652015-04-20 02:14:35 +0300527 print("\n")
Yulia Portnova1f123962015-05-06 18:48:11 +0300528 if tp in ['mysql', 'pgbench'] and data is not None:
Yulia Portnovab1a15072015-05-06 14:59:25 +0300529 print("\n")
530 print(MysqlTest.format_for_console(data))
531 print("\n")
koder aka kdanilov66839a92015-04-11 13:22:31 +0300532
533
koder aka kdanilove87ae652015-04-20 02:14:35 +0300534def html_report_stage(cfg, ctx):
Yulia Portnova8ca20572015-04-14 14:09:39 +0300535 html_rep_fname = cfg['html_report_file']
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300536 found = False
537 for tp, data in ctx.results:
538 if 'io' == tp and data is not None:
539 if found:
540 logger.error("Making reports for more than one " +
541 "io block isn't supported! All " +
542 "report, except first are skipped")
543 continue
544 found = True
545 dinfo = report.process_disk_info(data)
546 report.make_io_report(dinfo, data, html_rep_fname,
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300547 cfg['charts_img_path'],
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300548 lab_info=ctx.hw_info)
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300549
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300550 text_rep_fname = cfg_dict['text_report_file']
551 with open(text_rep_fname, "w") as fd:
552 fd.write(IOPerfTest.format_for_console(data, dinfo))
koder aka kdanilov652cd802015-04-13 12:21:07 +0300553 fd.write("\n")
554 fd.flush()
555
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300556 logger.info("Text report were stored in " + text_rep_fname)
koder aka kdanilovda45e882015-04-06 02:24:42 +0300557
558
559def complete_log_nodes_statistic(cfg, ctx):
560 nodes = ctx.nodes
561 for node in nodes:
562 logger.debug(str(node))
563
564
koder aka kdanilov66839a92015-04-11 13:22:31 +0300565def load_data_from(var_dir):
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300566 def load_data_from_file(cfg, ctx):
koder aka kdanilov66839a92015-04-11 13:22:31 +0300567 raw_results = os.path.join(var_dir, 'raw_results.yaml')
568 ctx.results = yaml.load(open(raw_results).read())
koder aka kdanilov4e9f3ed2015-04-14 11:26:12 +0300569 return load_data_from_file
gstepanovcd256d62015-04-07 17:47:32 +0300570
571
koder aka kdanilov57ce4db2015-04-25 21:25:51 +0300572def start_web_ui(cfg, ctx):
573 if webui is None:
574 logger.error("Can't start webui. Install cherrypy module")
575 ctx.web_thread = None
576 else:
577 th = threading.Thread(None, webui.web_main_thread, "webui", (None,))
578 th.daemon = True
579 th.start()
580 ctx.web_thread = th
581
582
583def stop_web_ui(cfg, ctx):
584 webui.web_main_stop()
585 time.sleep(1)
586
587
koder aka kdanilovcee43342015-04-14 22:52:53 +0300588def parse_args(argv):
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300589 descr = "Disk io performance test suite"
590 parser = argparse.ArgumentParser(prog='wally', description=descr)
koder aka kdanilovcee43342015-04-14 22:52:53 +0300591
592 parser.add_argument("-l", dest='extra_logs',
593 action='store_true', default=False,
594 help="print some extra log info")
koder aka kdanilovcee43342015-04-14 22:52:53 +0300595 parser.add_argument("-b", '--build_description',
596 type=str, default="Build info")
597 parser.add_argument("-i", '--build_id', type=str, default="id")
598 parser.add_argument("-t", '--build_type', type=str, default="GA")
599 parser.add_argument("-u", '--username', type=str, default="admin")
koder aka kdanilove87ae652015-04-20 02:14:35 +0300600 parser.add_argument("-n", '--no-tests', action='store_true',
601 help="Don't run tests", default=False)
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300602 parser.add_argument("-p", '--post-process-only', metavar="VAR_DIR",
603 help="Only process data from previour run")
604 parser.add_argument("-k", '--keep-vm', action='store_true',
605 help="Don't remove test vm's", default=False)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300606 parser.add_argument("-d", '--dont-discover-nodes', action='store_true',
607 help="Don't connect/discover fuel nodes",
608 default=False)
koder aka kdanilova047e1b2015-04-21 23:16:59 +0300609 parser.add_argument("-r", '--no-html-report', action='store_true',
610 help="Skip html report", default=False)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300611 parser.add_argument("--params", metavar="testname.paramname",
koder aka kdanilov63ad2062015-04-27 13:11:40 +0300612 help="Test params", default=[])
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300613 parser.add_argument("--reuse-vms", default=[], nargs='*')
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300614 parser.add_argument("config_file")
koder aka kdanilovcee43342015-04-14 22:52:53 +0300615
616 return parser.parse_args(argv[1:])
617
618
koder aka kdanilov3f356262015-02-13 08:06:14 -0800619def main(argv):
koder aka kdanilove06762a2015-03-22 23:32:09 +0200620 opts = parse_args(argv)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300621 load_config(opts.config_file, opts.post_process_only)
koder aka kdanilov2c473092015-03-29 17:12:13 +0300622
koder aka kdanilov66839a92015-04-11 13:22:31 +0300623 if opts.post_process_only is not None:
624 stages = [
koder aka kdanilove87ae652015-04-20 02:14:35 +0300625 load_data_from(opts.post_process_only)
koder aka kdanilov66839a92015-04-11 13:22:31 +0300626 ]
627 else:
628 stages = [
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300629 discover_stage
630 ]
631
koder aka kdanilovd5ed4da2015-05-07 23:33:23 +0300632 for reuse_param in opts.reuse_vms:
633 pref, ssh_templ = reuse_param.split(',', 1)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300634 stages.append(reuse_vms_stage(pref, ssh_templ))
635
636 stages.extend([
koder aka kdanilov66839a92015-04-11 13:22:31 +0300637 log_nodes_statistic,
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300638 save_nodes_stage,
639 connect_stage])
640
641 if cfg_dict.get('collect_info', True):
642 stages.append(collect_hw_info_stage)
643
644 stages.extend([
koder aka kdanilov66839a92015-04-11 13:22:31 +0300645 deploy_sensors_stage,
646 run_tests_stage,
koder aka kdanilove87ae652015-04-20 02:14:35 +0300647 store_raw_results_stage
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300648 ])
koder aka kdanilov66839a92015-04-11 13:22:31 +0300649
koder aka kdanilove87ae652015-04-20 02:14:35 +0300650 report_stages = [
651 console_report_stage,
koder aka kdanilove87ae652015-04-20 02:14:35 +0300652 ]
653
koder aka kdanilova047e1b2015-04-21 23:16:59 +0300654 if not opts.no_html_report:
655 report_stages.append(html_report_stage)
656
koder aka kdanilovcff7b2e2015-04-18 20:48:15 +0300657 if cfg_dict.get('logging', {}).get("extra_logs", False) or opts.extra_logs:
658 level = logging.DEBUG
659 else:
660 level = logging.WARNING
661
662 setup_loggers(level, cfg_dict['log_file'])
koder aka kdanilovf4b82c22015-04-11 13:35:25 +0300663
koder aka kdanilov652cd802015-04-13 12:21:07 +0300664 logger.info("All info would be stored into {0}".format(
665 cfg_dict['var_dir']))
gstepanovcd256d62015-04-07 17:47:32 +0300666
koder aka kdanilovda45e882015-04-06 02:24:42 +0300667 ctx = Context()
gstepanovaffcdb12015-04-07 17:18:29 +0300668 ctx.build_meta['build_id'] = opts.build_id
669 ctx.build_meta['build_descrption'] = opts.build_description
670 ctx.build_meta['build_type'] = opts.build_type
671 ctx.build_meta['username'] = opts.username
koder aka kdanilov57ce4db2015-04-25 21:25:51 +0300672 ctx.sensors_data = SensorDatastore()
koder aka kdanilove87ae652015-04-20 02:14:35 +0300673
koder aka kdanilov168f6092015-04-19 02:33:38 +0300674 cfg_dict['keep_vm'] = opts.keep_vm
koder aka kdanilove87ae652015-04-20 02:14:35 +0300675 cfg_dict['no_tests'] = opts.no_tests
676 cfg_dict['dont_discover_nodes'] = opts.dont_discover_nodes
koder aka kdanilov6c491062015-04-09 22:33:13 +0300677
koder aka kdanilov57ce4db2015-04-25 21:25:51 +0300678 if cfg_dict.get('run_web_ui', False):
679 start_web_ui(cfg_dict, ctx)
680
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300681 msg_templ = "Exception during {0.__name__}: {1!s}"
682 msg_templ_no_exc = "During {0.__name__}"
683
koder aka kdanilovda45e882015-04-06 02:24:42 +0300684 try:
685 for stage in stages:
686 logger.info("Start {0.__name__} stage".format(stage))
687 stage(cfg_dict, ctx)
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300688 except utils.StopTestError as exc:
689 logger.error(msg_templ.format(stage, exc))
690 except Exception:
691 logger.exception(msg_templ_no_exc.format(stage))
koder aka kdanilovda45e882015-04-06 02:24:42 +0300692 finally:
693 exc, cls, tb = sys.exc_info()
694 for stage in ctx.clear_calls_stack[::-1]:
695 try:
696 logger.info("Start {0.__name__} stage".format(stage))
697 stage(cfg_dict, ctx)
koder aka kdanilovf86d7af2015-05-06 04:01:54 +0300698 except utils.StopTestError as cleanup_exc:
699 logger.error(msg_templ.format(stage, cleanup_exc))
700 except Exception:
701 logger.exception(msg_templ_no_exc.format(stage))
702
703 logger.debug("Start utils.cleanup")
704 for clean_func, args, kwargs in utils.iter_clean_func():
705 try:
706 clean_func(*args, **kwargs)
707 except utils.StopTestError as cleanup_exc:
708 logger.error(msg_templ.format(stage, cleanup_exc))
koder aka kdanilovc368eb62015-04-28 18:22:01 +0300709 except Exception:
710 logger.exception(msg_templ_no_exc.format(stage))
koder aka kdanilov2c473092015-03-29 17:12:13 +0300711
koder aka kdanilove2de58c2015-04-24 22:59:36 +0300712 if exc is None:
713 for report_stage in report_stages:
714 report_stage(cfg_dict, ctx)
koder aka kdanilove87ae652015-04-20 02:14:35 +0300715
716 logger.info("All info stored in {0} folder".format(cfg_dict['var_dir']))
koder aka kdanilove2de58c2015-04-24 22:59:36 +0300717
koder aka kdanilov57ce4db2015-04-25 21:25:51 +0300718 if cfg_dict.get('run_web_ui', False):
719 stop_web_ui(cfg_dict, ctx)
720
koder aka kdanilove2de58c2015-04-24 22:59:36 +0300721 if exc is None:
722 logger.info("Tests finished successfully")
723 return 0
724 else:
725 logger.error("Tests are failed. See detailed error above")
726 return 1