blob: a2963a5bfac2c241456b5101ef3dccf3ed22a8bd [file] [log] [blame]
Moshe0bb532c2018-02-26 13:39:57 +02001##############################################################################
2# Copyright 2018 EuropeanSoftwareMarketingLtd.
3# ===================================================================
4# Licensed under the ApacheLicense, Version2.0 (the"License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# software distributed under the License is distributed on an "AS IS" BASIS,
10# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11# See the License for the specific language governing permissions and limitations under
12# the License
13##############################################################################
14# vnftest comment: this is a modified copy of
15# yardstick/benchmark/core/task.py
16
17""" Handler for vnftest command 'task' """
18
19from __future__ import absolute_import
20from __future__ import print_function
Moshe30497ac2018-03-14 14:22:13 +020021
22import atexit
23import collections
24import copy
25import logging
Moshe0bb532c2018-02-26 13:39:57 +020026import sys
Moshe30497ac2018-03-14 14:22:13 +020027import time
28import uuid
Moshe0bb532c2018-02-26 13:39:57 +020029from collections import OrderedDict
30
Moshe0bb532c2018-02-26 13:39:57 +020031import ipaddress
Moshe30497ac2018-03-14 14:22:13 +020032import os
33import yaml
Moshe0bb532c2018-02-26 13:39:57 +020034from jinja2 import Environment
Moshe30497ac2018-03-14 14:22:13 +020035from six.moves import filter
36from vnftest.runners import base as base_runner
Moshe0bb532c2018-02-26 13:39:57 +020037
Moshe30497ac2018-03-14 14:22:13 +020038from vnftest.contexts.base import Context
39from vnftest.contexts.csar import CSARContext
40from vnftest.runners import base as base_runner
41from vnftest.runners.duration import DurationRunner
42from vnftest.runners.iteration import IterationRunner
Moshe0bb532c2018-02-26 13:39:57 +020043from vnftest.common.constants import CONF_FILE
Moshe30497ac2018-03-14 14:22:13 +020044from vnftest.common.html_template import report_template
45from vnftest.common.task_template import TaskTemplate
Moshe0bb532c2018-02-26 13:39:57 +020046from vnftest.common.yaml_loader import yaml_load
Moshe30497ac2018-03-14 14:22:13 +020047from vnftest.contexts.base import Context
Moshe0bb532c2018-02-26 13:39:57 +020048from vnftest.dispatcher.base import Base as DispatcherBase
49from vnftest.common.task_template import TaskTemplate
50from vnftest.common import utils
51from vnftest.common import constants
52from vnftest.common.html_template import report_template
53
54output_file_default = "/tmp/vnftest.out"
55test_cases_dir_default = "tests/onap/test_cases/"
56LOG = logging.getLogger(__name__)
57
58
59class Task(object): # pragma: no cover
60 """Task commands.
61
62 Set of commands to manage benchmark tasks.
63 """
64
65 def __init__(self):
66 self.context = None
67 self.outputs = {}
68
69 def _set_dispatchers(self, output_config):
70 dispatchers = output_config.get('DEFAULT', {}).get('dispatcher',
71 'file')
72 out_types = [s.strip() for s in dispatchers.split(',')]
73 output_config['DEFAULT']['dispatcher'] = out_types
74
75 def start(self, args, **kwargs):
Moshe30497ac2018-03-14 14:22:13 +020076 Context.load_vnf_descriptor(args.vnfdescriptor)
Moshe0bb532c2018-02-26 13:39:57 +020077 atexit.register(self.atexit_handler)
78
79 task_id = getattr(args, 'task_id')
80 self.task_id = task_id if task_id else str(uuid.uuid4())
81
82 self._set_log()
83
84 try:
85 output_config = utils.parse_ini_file(CONF_FILE)
86 except Exception:
87 # all error will be ignore, the default value is {}
88 output_config = {}
89
90 self._init_output_config(output_config)
91 self._set_output_config(output_config, args.output_file)
92 LOG.debug('Output configuration is: %s', output_config)
93
94 self._set_dispatchers(output_config)
95
96 # update dispatcher list
97 if 'file' in output_config['DEFAULT']['dispatcher']:
98 result = {'status': 0, 'result': {}}
99 utils.write_json_to_file(args.output_file, result)
100
101 total_start_time = time.time()
Moshe30497ac2018-03-14 14:22:13 +0200102 parser = TaskParser(args.inputfile)
Moshe0bb532c2018-02-26 13:39:57 +0200103
104 if args.suite:
105 # 1.parse suite, return suite_params info
106 task_files, task_args, task_args_fnames = \
107 parser.parse_suite()
108 else:
109 task_files = [parser.path]
110 task_args = [args.task_args]
111 task_args_fnames = [args.task_args_file]
112
113 LOG.debug("task_files:%s, task_args:%s, task_args_fnames:%s",
114 task_files, task_args, task_args_fnames)
115
116 if args.parse_only:
117 sys.exit(0)
118
119 testcases = {}
120 # parse task_files
121 for i in range(0, len(task_files)):
122 one_task_start_time = time.time()
123 parser.path = task_files[i]
124 steps, run_in_parallel, meet_precondition, ret_context = \
125 parser.parse_task(self.task_id, task_args[i],
126 task_args_fnames[i])
127
128 self.context = ret_context
129
130 if not meet_precondition:
131 LOG.info("meet_precondition is %s, please check envrionment",
132 meet_precondition)
133 continue
134
135 case_name = os.path.splitext(os.path.basename(task_files[i]))[0]
136 try:
137 data = self._run(steps, run_in_parallel, args.output_file)
138 except KeyboardInterrupt:
139 raise
140 except Exception:
141 LOG.error('Testcase: "%s" FAILED!!!', case_name, exc_info=True)
142 testcases[case_name] = {'criteria': 'FAIL', 'tc_data': []}
143 else:
Moshe976c2a92018-03-06 18:50:02 +0200144 criteria = self.evaluate_task_criteria(data)
Moshe05acf082018-03-20 10:51:42 +0200145 testcases[case_name] = {'criteria': criteria, 'tc_data': data, 'output': self.outputs}
Moshe0bb532c2018-02-26 13:39:57 +0200146
147 if args.keep_deploy:
148 # keep deployment, forget about stack
149 # (hide it for exit handler)
150 self.context = None
151 else:
152 self.context.undeploy()
153 self.context = None
154 one_task_end_time = time.time()
155 LOG.info("Task %s finished in %d secs", task_files[i],
156 one_task_end_time - one_task_start_time)
157
158 result = self._get_format_result(testcases)
159
160 self._do_output(output_config, result)
161 self._generate_reporting(result)
162
163 total_end_time = time.time()
164 LOG.info("Total finished in %d secs",
165 total_end_time - total_start_time)
166
167 step = steps[0]
168 LOG.info("To generate report, execute command "
169 "'vnftest report generate %(task_id)s %(tc)s'", step)
170 LOG.info("Task ALL DONE, exiting")
171 return result
172
173 def _generate_reporting(self, result):
174 env = Environment()
175 with open(constants.REPORTING_FILE, 'w') as f:
176 f.write(env.from_string(report_template).render(result))
177
178 LOG.info("Report can be found in '%s'", constants.REPORTING_FILE)
179
180 def _set_log(self):
181 log_format = '%(asctime)s %(name)s %(filename)s:%(lineno)d %(levelname)s %(message)s'
182 log_formatter = logging.Formatter(log_format)
183
184 utils.makedirs(constants.TASK_LOG_DIR)
185 log_path = os.path.join(constants.TASK_LOG_DIR, '{}.log'.format(self.task_id))
186 log_handler = logging.FileHandler(log_path)
187 log_handler.setFormatter(log_formatter)
188 log_handler.setLevel(logging.DEBUG)
189
190 logging.root.addHandler(log_handler)
191
192 def _init_output_config(self, output_config):
193 output_config.setdefault('DEFAULT', {})
194 output_config.setdefault('dispatcher_http', {})
195 output_config.setdefault('dispatcher_file', {})
196 output_config.setdefault('dispatcher_influxdb', {})
197 output_config.setdefault('nsb', {})
198
199 def _set_output_config(self, output_config, file_path):
200 try:
201 out_type = os.environ['DISPATCHER']
202 except KeyError:
203 output_config['DEFAULT'].setdefault('dispatcher', 'file')
204 else:
205 output_config['DEFAULT']['dispatcher'] = out_type
206
207 output_config['dispatcher_file']['file_path'] = file_path
208
209 try:
210 target = os.environ['TARGET']
211 except KeyError:
212 pass
213 else:
214 k = 'dispatcher_{}'.format(output_config['DEFAULT']['dispatcher'])
215 output_config[k]['target'] = target
216
217 def _get_format_result(self, testcases):
218 criteria = self._get_task_criteria(testcases)
219
220 info = {
221 'deploy_step': os.environ.get('DEPLOY_STEP', 'unknown'),
222 'installer': os.environ.get('INSTALLER_TYPE', 'unknown'),
223 'pod_name': os.environ.get('NODE_NAME', 'unknown'),
224 'version': os.environ.get('VNFTEST_BRANCH', 'unknown')
225 }
226
227 result = {
228 'status': 1,
229 'result': {
230 'criteria': criteria,
231 'task_id': self.task_id,
232 'info': info,
233 'testcases': testcases
234 }
235 }
236
237 return result
238
239 def _get_task_criteria(self, testcases):
240 criteria = any(t.get('criteria') != 'PASS' for t in testcases.values())
241 if criteria:
242 return 'FAIL'
243 else:
244 return 'PASS'
245
Moshe976c2a92018-03-06 18:50:02 +0200246 def evaluate_task_criteria(self, steps_result_list):
247 for step_result in steps_result_list:
248 errors_list = step_result['errors']
249 if errors_list is not None and len(errors_list) > 0:
250 return 'FAIL'
251 return 'PASS'
252
Moshe0bb532c2018-02-26 13:39:57 +0200253 def _do_output(self, output_config, result):
254 dispatchers = DispatcherBase.get(output_config)
255
256 for dispatcher in dispatchers:
257 dispatcher.flush_result_data(result)
258
259 def _run(self, steps, run_in_parallel, output_file):
260 """Deploys context and calls runners"""
261 self.context.deploy()
262 background_runners = []
263
264 result = []
265 # Start all background steps
266 for step in filter(_is_background_step, steps):
267 step["runner"] = dict(type="Duration", duration=1000000000)
268 runner = self.run_one_step(step, output_file)
269 background_runners.append(runner)
270
271 runners = []
272 if run_in_parallel:
273 for step in steps:
274 if not _is_background_step(step):
275 runner = self.run_one_step(step, output_file)
276 runners.append(runner)
277
278 # Wait for runners to finish
279 for runner in runners:
280 status = runner_join(runner, background_runners, self.outputs, result)
281 if status != 0:
282 raise RuntimeError(
283 "{0} runner status {1}".format(runner.__execution_type__, status))
284 LOG.info("Runner ended, output in %s", output_file)
285 else:
286 # run serially
287 for step in steps:
288 if not _is_background_step(step):
289 runner = self.run_one_step(step, output_file)
290 status = runner_join(runner, background_runners, self.outputs, result)
291 if status != 0:
292 LOG.error('Step NO.%s: "%s" ERROR!',
293 steps.index(step) + 1,
294 step.get('type'))
295 raise RuntimeError(
296 "{0} runner status {1}".format(runner.__execution_type__, status))
297 LOG.info("Runner ended, output in %s", output_file)
298
299 # Abort background runners
300 for runner in background_runners:
301 runner.abort()
302
303 # Wait for background runners to finish
304 for runner in background_runners:
305 status = runner.join(self.outputs, result)
306 if status is None:
307 # Nuke if it did not stop nicely
308 base_runner.Runner.terminate(runner)
309 runner.join(self.outputs, result)
310 base_runner.Runner.release(runner)
311
312 print("Background task ended")
313 return result
314
315 def atexit_handler(self):
316 """handler for process termination"""
317 base_runner.Runner.terminate_all()
318
319 if self.context:
320 LOG.info("Undeploying context")
321 self.context.undeploy()
322
323 def _parse_options(self, op):
324 if isinstance(op, dict):
325 return {k: self._parse_options(v) for k, v in op.items()}
326 elif isinstance(op, list):
327 return [self._parse_options(v) for v in op]
328 elif isinstance(op, str):
329 return self.outputs.get(op[1:]) if op.startswith('$') else op
330 else:
331 return op
332
333 def run_one_step(self, step_cfg, output_file):
334 """run one step using context"""
Moshe976c2a92018-03-06 18:50:02 +0200335 # default runner is Iteration
Moshe0bb532c2018-02-26 13:39:57 +0200336 if 'runner' not in step_cfg:
Moshe976c2a92018-03-06 18:50:02 +0200337 step_cfg['runner'] = dict(type="Iteration", iterations=1)
Moshe0bb532c2018-02-26 13:39:57 +0200338 runner_cfg = step_cfg['runner']
339 runner_cfg['output_filename'] = output_file
340 options = step_cfg.get('options', {})
341 step_cfg['options'] = self._parse_options(options)
342 runner = base_runner.Runner.get(runner_cfg)
343
344 LOG.info("Starting runner of type '%s'", runner_cfg["type"])
Moshee01f7062018-03-11 16:18:20 +0200345 # Previous steps output is the input of the next step.
346 input_params = copy.deepcopy(self.outputs)
347 runner.run(step_cfg, self.context, input_params)
Moshe0bb532c2018-02-26 13:39:57 +0200348 return runner
349
350
351class TaskParser(object): # pragma: no cover
352 """Parser for task config files in yaml format"""
353
354 def __init__(self, path):
355 self.path = path
356
357 def _meet_constraint(self, task, cur_pod, cur_installer):
358 if "constraint" in task:
359 constraint = task.get('constraint', None)
360 if constraint is not None:
361 tc_fit_pod = constraint.get('pod', None)
362 tc_fit_installer = constraint.get('installer', None)
363 LOG.info("cur_pod:%s, cur_installer:%s,tc_constraints:%s",
364 cur_pod, cur_installer, constraint)
365 if (cur_pod is None) or (tc_fit_pod and cur_pod not in tc_fit_pod):
366 return False
367 if (cur_installer is None) or (tc_fit_installer and cur_installer
368 not in tc_fit_installer):
369 return False
370 return True
371
372 def _get_task_para(self, task, cur_pod):
373 task_args = task.get('task_args', None)
374 if task_args is not None:
375 task_args = task_args.get(cur_pod, task_args.get('default'))
376 task_args_fnames = task.get('task_args_fnames', None)
377 if task_args_fnames is not None:
378 task_args_fnames = task_args_fnames.get(cur_pod, None)
379 return task_args, task_args_fnames
380
381 def parse_suite(self):
382 """parse the suite file and return a list of task config file paths
383 and lists of optional parameters if present"""
384 LOG.info("\nParsing suite file:%s", self.path)
385
386 try:
387 with open(self.path) as stream:
388 cfg = yaml_load(stream)
389 except IOError as ioerror:
390 sys.exit(ioerror)
391
392 self._check_schema(cfg["schema"], "suite")
393 LOG.info("\nStarting step:%s", cfg["name"])
394
395 test_cases_dir = cfg.get("test_cases_dir", test_cases_dir_default)
396 test_cases_dir = os.path.join(constants.VNFTEST_ROOT_PATH,
397 test_cases_dir)
398 if test_cases_dir[-1] != os.sep:
399 test_cases_dir += os.sep
400
401 cur_pod = os.environ.get('NODE_NAME', None)
402 cur_installer = os.environ.get('INSTALLER_TYPE', None)
403
404 valid_task_files = []
405 valid_task_args = []
406 valid_task_args_fnames = []
407
408 for task in cfg["test_cases"]:
409 # 1.check file_name
410 if "file_name" in task:
411 task_fname = task.get('file_name', None)
412 if task_fname is None:
413 continue
414 else:
415 continue
416 # 2.check constraint
417 if self._meet_constraint(task, cur_pod, cur_installer):
418 valid_task_files.append(test_cases_dir + task_fname)
419 else:
420 continue
421 # 3.fetch task parameters
422 task_args, task_args_fnames = self._get_task_para(task, cur_pod)
423 valid_task_args.append(task_args)
424 valid_task_args_fnames.append(task_args_fnames)
425
426 return valid_task_files, valid_task_args, valid_task_args_fnames
427
428 def parse_task(self, task_id, task_args=None, task_args_file=None):
429 """parses the task file and return an context and step instances"""
430 LOG.info("Parsing task config: %s", self.path)
431
432 try:
433 kw = {}
434 if task_args_file:
435 with open(task_args_file) as f:
436 kw.update(parse_task_args("task_args_file", f.read()))
437 kw.update(parse_task_args("task_args", task_args))
438 except TypeError:
439 raise TypeError()
440
441 try:
442 with open(self.path) as f:
443 try:
444 input_task = f.read()
445 rendered_task = TaskTemplate.render(input_task, **kw)
446 except Exception as e:
447 LOG.exception('Failed to render template:\n%s\n', input_task)
448 raise e
449 LOG.debug("Input task is:\n%s\n", rendered_task)
450
451 cfg = yaml_load(rendered_task)
452 except IOError as ioerror:
453 sys.exit(ioerror)
454
455 self._check_schema(cfg["schema"], "task")
456 meet_precondition = self._check_precondition(cfg)
457
458 if "context" in cfg:
459 context_cfg = cfg["context"]
460 else:
461 context_cfg = {"type": "Dummy"}
462
463 name_suffix = '-{}'.format(task_id[:8])
464 try:
465 context_cfg['name'] = '{}{}'.format(context_cfg['name'],
466 name_suffix)
467 except KeyError:
468 pass
469 # default to CSAR context
470 context_type = context_cfg.get("type", "CSAR")
471 context = Context.get(context_type)
472 context.init(context_cfg)
473
474 run_in_parallel = cfg.get("run_in_parallel", False)
475
476 # add tc and task id for influxdb extended tags
477 for step in cfg["steps"]:
478 task_name = os.path.splitext(os.path.basename(self.path))[0]
479 step["tc"] = task_name
480 step["task_id"] = task_id
481 # embed task path into step so we can load other files
482 # relative to task path
483 step["task_path"] = os.path.dirname(self.path)
484
485 # TODO we need something better here, a class that represent the file
486 return cfg["steps"], run_in_parallel, meet_precondition, context
487
488 def _check_schema(self, cfg_schema, schema_type):
489 """Check if config file is using the correct schema type"""
490
491 if cfg_schema != "vnftest:" + schema_type + ":0.1":
492 sys.exit("error: file %s has unknown schema %s" % (self.path,
493 cfg_schema))
494
495 def _check_precondition(self, cfg):
496 """Check if the environment meet the precondition"""
497
498 if "precondition" in cfg:
499 precondition = cfg["precondition"]
500 installer_type = precondition.get("installer_type", None)
501 deploy_steps = precondition.get("deploy_steps", None)
502 tc_fit_pods = precondition.get("pod_name", None)
503 installer_type_env = os.environ.get('INSTALL_TYPE', None)
504 deploy_step_env = os.environ.get('DEPLOY_STEP', None)
505 pod_name_env = os.environ.get('NODE_NAME', None)
506
507 LOG.info("installer_type: %s, installer_type_env: %s",
508 installer_type, installer_type_env)
509 LOG.info("deploy_steps: %s, deploy_step_env: %s",
510 deploy_steps, deploy_step_env)
511 LOG.info("tc_fit_pods: %s, pod_name_env: %s",
512 tc_fit_pods, pod_name_env)
513 if installer_type and installer_type_env:
514 if installer_type_env not in installer_type:
515 return False
516 if deploy_steps and deploy_step_env:
517 deploy_steps_list = deploy_steps.split(',')
518 for deploy_step in deploy_steps_list:
519 if deploy_step_env.startswith(deploy_step):
520 return True
521 return False
522 if tc_fit_pods and pod_name_env:
523 if pod_name_env not in tc_fit_pods:
524 return False
525 return True
526
527
528def is_ip_addr(addr):
529 """check if string addr is an IP address"""
530 try:
531 addr = addr.get('public_ip_attr', addr.get('private_ip_attr'))
532 except AttributeError:
533 pass
534
535 try:
536 ipaddress.ip_address(addr.encode('utf-8'))
537 except ValueError:
538 return False
539 else:
540 return True
541
542
543def _is_background_step(step):
544 if "run_in_background" in step:
545 return step["run_in_background"]
546 else:
547 return False
548
549
550def parse_nodes_with_context(step_cfg):
551 """parse the 'nodes' fields in step """
552 # ensure consistency in node instantiation order
553 return OrderedDict((nodename, Context.get_server(step_cfg["nodes"][nodename]))
554 for nodename in sorted(step_cfg["nodes"]))
555
556
557def get_networks_from_nodes(nodes):
558 """parse the 'nodes' fields in step """
559 networks = {}
560 for node in nodes.values():
561 if not node:
562 continue
563 interfaces = node.get('interfaces', {})
564 for interface in interfaces.values():
565 # vld_id is network_name
566 network_name = interface.get('network_name')
567 if not network_name:
568 continue
569 network = Context.get_network(network_name)
570 if network:
571 networks[network['name']] = network
572 return networks
573
574
575def runner_join(runner, background_runners, outputs, result):
576 """join (wait for) a runner, exit process at runner failure
577 :param background_runners:
578 :type background_runners:
579 :param outputs:
580 :type outputs: dict
581 :param result:
582 :type result: list
583 """
584 while runner.poll() is None:
585 outputs.update(runner.get_output())
586 result.extend(runner.get_result())
587 # drain all the background runner queues
588 for background in background_runners:
589 outputs.update(background.get_output())
590 result.extend(background.get_result())
591 status = runner.join(outputs, result)
592 base_runner.Runner.release(runner)
593 return status
594
595
596def print_invalid_header(source_name, args):
597 print("Invalid %(source)s passed:\n\n %(args)s\n"
598 % {"source": source_name, "args": args})
599
600
601def parse_task_args(src_name, args):
602 if isinstance(args, collections.Mapping):
603 return args
604
605 try:
606 kw = args and yaml_load(args)
607 kw = {} if kw is None else kw
608 except yaml.parser.ParserError as e:
609 print_invalid_header(src_name, args)
610 print("%(source)s has to be YAML. Details:\n\n%(err)s\n"
611 % {"source": src_name, "err": e})
612 raise TypeError()
613
614 if not isinstance(kw, dict):
615 print_invalid_header(src_name, args)
616 print("%(src)s had to be dict, actually %(src_type)s\n"
617 % {"src": src_name, "src_type": type(kw)})
618 raise TypeError()
619 return kw