Minos Galanakis | f4ca6ac | 2017-12-11 02:39:21 +0100 | [diff] [blame] | 1 | #!/usr/bin/env python3 -u |
| 2 | |
| 3 | """ lava_helper.py: |
| 4 | |
| 5 | Generate custom defined LAVA definitions redered from Jinja2 templates. |
| 6 | It can also parse the yaml output of LAVA and verify the test outcome """ |
| 7 | |
| 8 | from __future__ import print_function |
| 9 | |
| 10 | __copyright__ = """ |
| 11 | /* |
| 12 | * Copyright (c) 2018-2019, Arm Limited. All rights reserved. |
| 13 | * |
| 14 | * SPDX-License-Identifier: BSD-3-Clause |
| 15 | * |
| 16 | */ |
| 17 | """ |
| 18 | __author__ = "Minos Galanakis" |
| 19 | __email__ = "minos.galanakis@linaro.org" |
| 20 | __project__ = "Trusted Firmware-M Open CI" |
| 21 | __status__ = "stable" |
| 22 | __version__ = "1.0" |
| 23 | |
| 24 | import os |
| 25 | import sys |
| 26 | import argparse |
| 27 | from copy import deepcopy |
| 28 | from collections import OrderedDict |
| 29 | from jinja2 import Environment, FileSystemLoader |
| 30 | from lava_helper_configs import * |
| 31 | |
| 32 | try: |
| 33 | from tfm_ci_pylib.utils import save_json, load_json, sort_dict,\ |
| 34 | load_yaml, test |
| 35 | from tfm_ci_pylib.lava_rpc_connector import LAVA_RPC_connector |
| 36 | except ImportError: |
| 37 | dir_path = os.path.dirname(os.path.realpath(__file__)) |
| 38 | sys.path.append(os.path.join(dir_path, "../")) |
| 39 | from tfm_ci_pylib.utils import save_json, load_json, sort_dict,\ |
| 40 | load_yaml, test |
| 41 | from tfm_ci_pylib.lava_rpc_connector import LAVA_RPC_connector |
| 42 | |
| 43 | |
| 44 | def sort_lavagen_config(cfg): |
| 45 | """ Create a constact dictionary object. This method is tailored for |
| 46 | the complicated configuration structure of this module """ |
| 47 | |
| 48 | res = OrderedDict() |
| 49 | if sorted(lavagen_config_sort_order) == sorted(cfg.keys()): |
| 50 | item_list = sorted(cfg.keys(), |
| 51 | key=lambda x: lavagen_config_sort_order.index(x)) |
| 52 | else: |
| 53 | item_list = sorted(cfg.keys(), key=len) |
| 54 | for k in item_list: |
| 55 | v = cfg[k] |
| 56 | if isinstance(v, dict): |
| 57 | res[k] = sort_lavagen_config(v) |
| 58 | elif isinstance(v, list) and isinstance(v[0], dict): |
| 59 | res[k] = [sort_dict(e, lava_gen_monitor_sort_order) for e in v] |
| 60 | else: |
| 61 | res[k] = v |
| 62 | return res |
| 63 | |
| 64 | |
| 65 | def save_config(cfg_f, cfg_obj): |
| 66 | """ Export configuration to json file """ |
| 67 | save_json(cfg_f, sort_lavagen_config(cfg_obj)) |
| 68 | |
| 69 | |
| 70 | def print_configs(): |
| 71 | """ Print supported configurations """ |
| 72 | |
| 73 | print("%(pad)s Built-in configurations: %(pad)s" % {"pad": "*" * 10}) |
| 74 | for k in lava_gen_config_map.keys(): |
| 75 | print("\t * %s" % k) |
| 76 | |
| 77 | |
| 78 | def generate_test_definitions(config, work_dir): |
| 79 | """ Get a dictionary configuration, and an existing jinja2 template |
| 80 | and generate a LAVA compatbile yaml definition """ |
| 81 | |
| 82 | template_loader = FileSystemLoader(searchpath=work_dir) |
| 83 | template_env = Environment(loader=template_loader) |
| 84 | |
| 85 | # Ensure that the jinja2 template is always rendered the same way |
| 86 | config = sort_lavagen_config(config) |
| 87 | |
| 88 | template_file = config.pop("templ") |
| 89 | |
| 90 | definition = template_env.get_template(template_file).render(**config) |
| 91 | return definition |
| 92 | |
| 93 | |
| 94 | def generate_lava_job_defs(user_args, config): |
| 95 | """ Create a LAVA test job definition file """ |
| 96 | |
| 97 | # Evaluate current directory |
| 98 | if user_args.work_dir: |
| 99 | work_dir = os.path.abspath(user_args.work_dir) |
| 100 | else: |
| 101 | work_dir = os.path.abspath(os.path.dirname(__file__)) |
| 102 | |
| 103 | # If a single platform is requested and it exists in the platform |
| 104 | if user_args.platform and user_args.platform in config["platforms"]: |
| 105 | # Only test this platform |
| 106 | platform = user_args.platform |
| 107 | config["platforms"] = {platform: config["platforms"][platform]} |
| 108 | |
| 109 | # Generate the ouptut definition |
| 110 | definition = generate_test_definitions(config, work_dir) |
| 111 | |
| 112 | # Write it into a file |
| 113 | out_file = os.path.abspath(user_args.lava_def_output) |
| 114 | with open(out_file, "w") as F: |
| 115 | F.write(definition) |
| 116 | |
| 117 | print("Definition created at %s" % out_file) |
| 118 | |
| 119 | |
| 120 | def test_map_from_config(lvg_cfg=tfm_mps2_sse_200): |
| 121 | """ Extract all required information from a lavagen config map |
| 122 | and generate a map of required tests, indexed by test name """ |
| 123 | |
| 124 | test_map = {} |
| 125 | suffix_l = [] |
| 126 | for p in lvg_cfg["platforms"]: |
| 127 | for c in lvg_cfg["compilers"]: |
| 128 | for bd in lvg_cfg["build_types"]: |
| 129 | for bt in lvg_cfg["boot_types"]: |
| 130 | suffix_l.append("%s_%s_%s_%s_%s" % (p, c, "%s", bd, bt)) |
| 131 | |
| 132 | for test_cfg_name, tst in lvg_cfg["tests"].items(): |
| 133 | for monitor in tst["monitors"]: |
| 134 | for suffix in suffix_l: |
| 135 | key = (monitor["name"] + "_" + suffix % test_cfg_name).lower() |
| 136 | # print (monitor['required']) |
| 137 | test_map[key] = monitor['required'] |
| 138 | |
| 139 | return deepcopy(test_map) |
| 140 | |
| 141 | |
| 142 | def test_lava_results(user_args, config): |
| 143 | """ Uses input of a test config dictionary and a LAVA summary Files |
| 144 | and determines if the test is a successful or not """ |
| 145 | |
| 146 | # Parse command line arguments to override config |
| 147 | result_raw = load_yaml(user_args.lava_results) |
| 148 | |
| 149 | test_map = test_map_from_config(config) |
| 150 | t_dict = {k: {} for k in test_map} |
| 151 | |
| 152 | # Return true if test is contained in test_groups |
| 153 | def test_filter(x): |
| 154 | return x["metadata"]['definition'] in test_map |
| 155 | |
| 156 | # Create a dictionary with common keys as the test map and test results |
| 157 | # {test_suite: {test_name: pass/fail}} |
| 158 | def format_results(x): |
| 159 | t_dict[x["metadata"]["definition"]].update({x["metadata"]["case"]: |
| 160 | x["metadata"]["result"]}) |
| 161 | |
| 162 | # Remove all irelevant entries from data |
| 163 | test_results = list(filter(test_filter, result_raw)) |
| 164 | |
| 165 | # Call the formatter |
| 166 | list(map(format_results, test_results)) |
| 167 | |
| 168 | # We need to check that each of the tests contained in the test_map exist |
| 169 | # AND that they have a passed status |
| 170 | t_sum = 0 |
| 171 | for k, v in t_dict.items(): |
| 172 | try: |
| 173 | t_sum += int(test(test_map[k], |
| 174 | v, |
| 175 | pass_text=["pass"], |
| 176 | error_on_failed=False, |
| 177 | test_name=k, |
| 178 | summary=user_args.lava_summary)["success"]) |
| 179 | # Status can be None if a test did't fully run/complete |
| 180 | except TypeError as E: |
| 181 | t_sum = 1 |
| 182 | |
| 183 | # Every single of the tests need to have passed for group to succeed |
| 184 | if t_sum != len(t_dict): |
| 185 | print("Group Testing FAILED!") |
| 186 | sys.exit(1) |
| 187 | print("Group Testing PASS!") |
| 188 | |
| 189 | |
| 190 | def test_lava_dispatch_credentials(user_args): |
| 191 | """ Will validate if provided token/credentials are valid. It will return |
| 192 | a valid connection or exit program if not""" |
| 193 | |
| 194 | # Collect the authentication tokens |
| 195 | try: |
| 196 | if user_args.token_from_env: |
| 197 | usr = os.environ['LAVA_USER'] |
| 198 | secret = os.environ['LAVA_TOKEN'] |
| 199 | elif user_args.token_usr and user_args.token_secret: |
| 200 | usr = user_args.token_usr |
| 201 | secret = user_args.token_secret |
| 202 | |
| 203 | # Do not submit job without complete credentials |
| 204 | if not len(usr) or not len(secret): |
| 205 | raise Exception("Credentials not set") |
| 206 | |
| 207 | lava = LAVA_RPC_connector(usr, |
| 208 | secret, |
| 209 | user_args.lava_url, |
| 210 | user_args.lava_rpc) |
| 211 | |
| 212 | # Test the credentials againist the backend |
| 213 | if not lava.test_credentials(): |
| 214 | raise Exception("Server rejected user authentication") |
| 215 | except Exception as e: |
| 216 | print("Credential validation failed with : %s" % e) |
| 217 | print("Did you set set --lava_token_usr, --lava_token_secret?") |
| 218 | sys.exit(1) |
| 219 | return lava |
| 220 | |
| 221 | |
| 222 | def lava_dispatch(user_args): |
| 223 | """ Submit a job to LAVA backend, block untill it is completed, and |
| 224 | fetch the results files if successful. If not, calls sys exit with 1 |
| 225 | return code """ |
| 226 | |
| 227 | lava = test_lava_dispatch_credentials(user_args) |
| 228 | job_id, job_url = lava.submit_job(user_args.dispatch) |
| 229 | print("Job submitted at: " + job_url) |
| 230 | with open("lava_job.id", "w") as F: |
| 231 | F.write(str(job_id)) |
| 232 | print("Job id %s stored at lava_job.id file." % job_id) |
| 233 | |
| 234 | # Wait for the job to complete |
| 235 | status = lava.block_wait_for_job(job_id, int(user_args.dispatch_timeout)) |
| 236 | print("Job %s returned with status: %s" % (job_id, status)) |
| 237 | if status == "Complete": |
| 238 | lava.get_job_results(job_id, user_args.lava_job_results) |
| 239 | print("Job results exported at: %s" % user_args.lava_job_results) |
| 240 | sys.exit(0) |
| 241 | sys.exit(1) |
| 242 | |
| 243 | |
| 244 | def dispatch_cancel(user_args): |
| 245 | """ Sends a cancell request for user provided job id (dispatch_cancel)""" |
| 246 | lava = test_lava_dispatch_credentials(user_args) |
| 247 | id = user_args.dispatch_cancel |
| 248 | result = lava.cancel_job(id) |
| 249 | print("Request to cancell job: %s returned with status %s" % (id, result)) |
| 250 | |
| 251 | |
| 252 | def load_config_overrides(user_args): |
| 253 | """ Load a configuration from multiple locations and override it with |
| 254 | user provided arguemnts """ |
| 255 | |
| 256 | if user_args.config_file: |
| 257 | print("Loading config from file %s" % user_args.config_file) |
| 258 | try: |
| 259 | config = load_json(user_args.config_file) |
| 260 | except Exception: |
| 261 | print("Failed to load config from: %s ." % user_args.config_file) |
| 262 | sys.exit(1) |
| 263 | else: |
| 264 | print("Using built-in config: %s" % user_args.config_key) |
| 265 | try: |
| 266 | config = lava_gen_config_map[user_args.config_key] |
| 267 | except KeyError: |
| 268 | print("No template found for config: %s" % user_args.config_key) |
| 269 | sys.exit(1) |
| 270 | |
| 271 | config["build_no"] = user_args.build_no |
| 272 | |
| 273 | # Add the template folder |
| 274 | config["templ"] = os.path.join(user_args.template_dir, config["templ"]) |
| 275 | return config |
| 276 | |
| 277 | |
| 278 | def main(user_args): |
| 279 | """ Main logic, forked according to task arguments """ |
| 280 | |
| 281 | # If a configuration listing is requested |
| 282 | if user_args.ls_config: |
| 283 | print_configs() |
| 284 | return |
| 285 | elif user_args.cconfig: |
| 286 | config_key = user_args.cconfig |
| 287 | if config_key in lava_gen_config_map.keys(): |
| 288 | config_file = "lava_job_gen_cfg_%s.json" % config_key |
| 289 | save_config(config_file, lava_gen_config_map[config_key]) |
| 290 | print("Configuration exported at %s" % config_file) |
| 291 | return |
| 292 | else: |
| 293 | config = load_config_overrides(user_args) |
| 294 | |
| 295 | # Configuration is assumed fixed at this point |
| 296 | if user_args.lava_results: |
| 297 | print("Evaluating File", user_args.lava_results) |
| 298 | test_lava_results(user_args, config) |
| 299 | elif user_args.dispatch: |
| 300 | lava_dispatch(user_args) |
| 301 | elif user_args.dispatch_cancel: |
| 302 | dispatch_cancel(user_args) |
| 303 | elif user_args.create_definition: |
| 304 | print("Generating Lava") |
| 305 | generate_lava_job_defs(user_args, config) |
| 306 | else: |
| 307 | print("Nothing to do, please select a task") |
| 308 | |
| 309 | |
| 310 | def get_cmd_args(): |
| 311 | """ Parse command line arguments """ |
| 312 | |
| 313 | # Parse command line arguments to override config |
| 314 | parser = argparse.ArgumentParser(description="Lava Helper") |
| 315 | |
| 316 | def_g = parser.add_argument_group('Create LAVA Definition') |
| 317 | disp_g = parser.add_argument_group('Dispatch LAVA job') |
| 318 | parse_g = parser.add_argument_group('Parse LAVA results') |
| 319 | config_g = parser.add_argument_group('Configuration handling') |
| 320 | over_g = parser.add_argument_group('Overrides') |
| 321 | |
| 322 | # Configuration control |
| 323 | config_g.add_argument("-cn", "--config-name", |
| 324 | dest="config_key", |
| 325 | action="store", |
| 326 | default="tfm_mps2_sse_200", |
| 327 | help="Select built-in configuration by name") |
| 328 | config_g.add_argument("-cf", "--config-file", |
| 329 | dest="config_file", |
| 330 | action="store", |
| 331 | help="Load config from external file in JSON format") |
| 332 | config_g.add_argument("-te", "--task-config-export", |
| 333 | dest="cconfig", |
| 334 | action="store", |
| 335 | help="Export a json file with the current config " |
| 336 | "parameters") |
| 337 | config_g.add_argument("-tl", "--task-config-list", |
| 338 | dest="ls_config", |
| 339 | action="store_true", |
| 340 | default=False, |
| 341 | help="List built-in configurations") |
| 342 | |
| 343 | def_g.add_argument("-tc", "--task-create-definition", |
| 344 | dest="create_definition", |
| 345 | action="store_true", |
| 346 | default=False, |
| 347 | help="Used in conjunction with --config parameters. " |
| 348 | "A LAVA compatible job definition will be created") |
| 349 | def_g.add_argument("-cb", "--create-definition-build-no", |
| 350 | dest="build_no", |
| 351 | action="store", |
| 352 | default="lastSuccessfulBuild", |
| 353 | help="JENKINGS Build number selector. " |
| 354 | "Default: lastSuccessfulBuild") |
| 355 | def_g.add_argument("-co", "--create-definition-output-file", |
| 356 | dest="lava_def_output", |
| 357 | action="store", |
| 358 | default="job_results.yaml", |
| 359 | help="Set LAVA compatible .yaml output file") |
| 360 | |
| 361 | # Parameter override commands |
| 362 | over_g.add_argument("-ow", "--override-work-path", |
| 363 | dest="work_dir", |
| 364 | action="store", |
| 365 | help="Working Directory (absolute path)") |
| 366 | over_g.add_argument("-ot", "--override-template-dir", |
| 367 | dest="template_dir", |
| 368 | action="store", |
| 369 | default="jinja2_templates", |
| 370 | help="Set directory where Jinja2 templates are stored") |
| 371 | over_g.add_argument("-op", "--override-platform", |
| 372 | dest="platform", |
| 373 | action="store", |
| 374 | help="Override platform.Only the provided one " |
| 375 | "will be tested ") |
| 376 | parse_g.add_argument("-tp", "--task-lava-parse", |
| 377 | dest="lava_results", |
| 378 | action="store", |
| 379 | help="Parse provided yaml file, using a configuration" |
| 380 | " as reference to determine the outpcome" |
| 381 | " of testing") |
| 382 | parse_g.add_argument("-ls", "--lava-parse-summary", |
| 383 | dest="lava_summary", |
| 384 | default=True, |
| 385 | action="store_true", |
| 386 | help="Print full test summary") |
| 387 | |
| 388 | # Lava job control commands |
| 389 | disp_g.add_argument("-td", "--task-dispatch", |
| 390 | dest="dispatch", |
| 391 | action="store", |
| 392 | help="Submit yaml file defined job to backend, and " |
| 393 | "wait for it to complete. \nRequires:" |
| 394 | " --lava_url --lava_token_usr/pass/--" |
| 395 | "lava_token_from_environ arguments, with optional" |
| 396 | "\n--lava_rpc_prefix\n--lava-job-results\n" |
| 397 | "parameters. \nIf not set they get RPC2 and " |
| 398 | "lava_job_results.yaml default values.\n" |
| 399 | "The number job id will be stored at lava_job.id") |
| 400 | disp_g.add_argument("-dc", "--dispatch-cancel", |
| 401 | dest="dispatch_cancel", |
| 402 | action="store", |
| 403 | help="Send a cancell request for job with provided id") |
| 404 | disp_g.add_argument("-dt", "--dispatch-timeout", |
| 405 | dest="dispatch_timeout", |
| 406 | default="3600", |
| 407 | action="store", |
| 408 | help="Maximum Time to block for job" |
| 409 | " submission to complete") |
| 410 | disp_g.add_argument("-dl", "--dispatch-lava-url", |
| 411 | dest="lava_url", |
| 412 | action="store", |
| 413 | help="Sets the lava hostname during job dispatch") |
| 414 | disp_g.add_argument("-dr", "--dispatch-lava-rpc-prefix", |
| 415 | dest="lava_rpc", |
| 416 | action="store", |
| 417 | default="RPC2", |
| 418 | help="Application prefix on Backend" |
| 419 | "(i.e www.domain.com/APP)\n" |
| 420 | "By default set to RPC2") |
| 421 | disp_g.add_argument("-du", "--dispatch-lava_token_usr", |
| 422 | dest="token_usr", |
| 423 | action="store", |
| 424 | help="Lava user submitting the job") |
| 425 | disp_g.add_argument("-ds", "--dispatch-lava_token_secret", |
| 426 | dest="token_secret", |
| 427 | action="store", |
| 428 | help="Hash token used to authenticate" |
| 429 | "user during job submission") |
| 430 | disp_g.add_argument("-de", "--dispatch-lava_token_from_environ", |
| 431 | dest="token_from_env", |
| 432 | action="store_true", |
| 433 | help="If set dispatcher will use the enviroment" |
| 434 | "stored $LAVA_USER, $LAVA_TOKEN for credentials") |
| 435 | disp_g.add_argument("-df", "--dispatch-lava-job-results-file", |
| 436 | dest="lava_job_results", |
| 437 | action="store", |
| 438 | default="lava_job_results.yaml", |
| 439 | help="Name of the job results file after job is " |
| 440 | "complete. Default: lava_job_results.yaml") |
| 441 | return parser.parse_args() |
| 442 | |
| 443 | |
| 444 | if __name__ == "__main__": |
| 445 | main(get_cmd_args()) |