blob: 4ce848ad879a7bc2ea715a3dfc6b320b067ae1d0 [file] [log] [blame]
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +01001#!/usr/bin/env python3
2
3""" tfm_build_manager.py:
4
5 Controlling class managing multiple build configruations for tfm """
6
7from __future__ import print_function
8
9__copyright__ = """
10/*
11 * Copyright (c) 2018-2019, Arm Limited. All rights reserved.
12 *
13 * SPDX-License-Identifier: BSD-3-Clause
14 *
15 */
16 """
17__author__ = "Minos Galanakis"
18__email__ = "minos.galanakis@linaro.org"
19__project__ = "Trusted Firmware-M Open CI"
20__status__ = "stable"
Minos Galanakisea421232019-06-20 17:11:28 +010021__version__ = "1.1"
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010022
23import os
24import sys
Minos Galanakisea421232019-06-20 17:11:28 +010025from time import time
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010026from copy import deepcopy
27from .utils import gen_cfg_combinations, list_chunks, load_json,\
Minos Galanakisea421232019-06-20 17:11:28 +010028 save_json, print_test, show_progress, \
29 resolve_rel_path
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010030from .structured_task import structuredTask
31from .tfm_builder import TFM_Builder
32
33
34class TFM_Build_Manager(structuredTask):
35 """ Class that will load a configuration out of a json file, schedule
36 the builds, and produce a report """
37
38 def __init__(self,
39 tfm_dir, # TFM root directory
40 work_dir, # Current working directory(ie logs)
41 cfg_dict, # Input config dictionary of the following form
42 # input_dict = {"PROJ_CONFIG": "ConfigRegression",
43 # "TARGET_PLATFORM": "MUSCA_A",
44 # "COMPILER": "ARMCLANG",
45 # "CMAKE_BUILD_TYPE": "Debug"}
46 report=None, # File to produce report
47 parallel_builds=3, # Number of builds to run in parallel
Minos Galanakisea421232019-06-20 17:11:28 +010048 build_threads=3, # Number of threads used per build
49 install=False, # Install libraries after build
50 img_sizes=False, # Use arm-none-eabi-size for size info
51 relative_paths=False): # Store relative paths in report
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010052 self._tbm_build_threads = build_threads
53 self._tbm_conc_builds = parallel_builds
54 self._tbm_install = install
Minos Galanakisea421232019-06-20 17:11:28 +010055 self._tbm_img_sizes = img_sizes
56 self._tbm_relative_paths = relative_paths
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010057
58 # Required by other methods, always set working directory first
59 self._tbm_work_dir = os.path.abspath(os.path.expanduser(work_dir))
60
61 self._tbm_tfm_dir = os.path.abspath(os.path.expanduser(tfm_dir))
62
Minos Galanakisea421232019-06-20 17:11:28 +010063 # Internal flag to tag simple (non combination formatted configs)
64 self.simple_config = False
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010065 self._tbm_report = report
66
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010067 self._tbm_cfg = self.load_config(cfg_dict, self._tbm_work_dir)
Minos Galanakisea421232019-06-20 17:11:28 +010068 self._tbm_build_cfg, \
69 self.tbm_common_cfg = self.parse_config(self._tbm_cfg)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010070
71 super(TFM_Build_Manager, self).__init__(name="TFM_Build_Manager")
72
Dean Birch5cb5a882020-01-24 11:37:13 +000073 def print_config(self):
74 """Prints a list of available build configurations"""
75 print("\n".join(list(self._tbm_build_cfg.keys())))
76
77 def print_config_environment(self, config):
78 """
79 For a given build configuration from output of print_config
80 method, print environment variables to build.
81 """
82 if config not in self._tbm_build_cfg:
83 print("Error: no such config {}".format(config), file=sys.stderr)
84 sys.exit(1)
85 config_details = self._tbm_build_cfg[config]
86 argument_list = [
87 "TARGET_PLATFORM={}",
88 "COMPILER={}",
89 "PROJ_CONFIG={}",
90 "CMAKE_BUILD_TYPE={}",
91 "BL2={}",
92 ]
93 print(
94 "\n".join(argument_list)
95 .format(
96 config_details.target_platform,
97 config_details.compiler,
98 config_details.proj_config,
99 config_details.cmake_build_type,
100 config_details.with_mcuboot,
101 )
102 .strip()
103 )
104
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100105 def pre_eval(self):
106 """ Tests that need to be run in set-up state """
107 return True
108
109 def pre_exec(self, eval_ret):
110 """ """
111
Minos Galanakisea421232019-06-20 17:11:28 +0100112 def override_tbm_cfg_params(self, config, override_keys, **params):
113 """ Using a dictionay as input, for each key defined in
114 override_keys it will replace the config[key] entries with
115 the key=value parameters provided """
116
117 for key in override_keys:
118 if isinstance(config[key], list):
119 config[key] = [n % params for n in config[key]]
120 elif isinstance(config[key], str):
121 config[key] = config[key] % params
122 else:
123 raise Exception("Config does not contain key %s "
124 "of type %s" % (key, config[key]))
125 return config
126
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100127 def task_exec(self):
128 """ Create a build pool and execute them in parallel """
129
130 build_pool = []
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100131
Minos Galanakisea421232019-06-20 17:11:28 +0100132 # When a config is flagged as a single build config.
133 # Name is evaluated by config type
134 if self.simple_config:
135
136 build_cfg = deepcopy(self.tbm_common_cfg)
137
138 # Extract the common for all elements of config
139 for key in ["build_cmds", "required_artefacts"]:
140 try:
141 build_cfg[key] = build_cfg[key]["all"]
142 except KeyError:
143 build_cfg[key] = []
144 name = build_cfg["config_type"]
145
146 # Override _tbm_xxx paths in commands
147 # plafrom in not guaranteed without seeds so _tbm_target_platform
148 # is ignored
149 over_dict = {"_tbm_build_dir_": os.path.join(self._tbm_work_dir,
150 name),
151 "_tbm_code_dir_": build_cfg["codebase_root_dir"]}
152
153 build_cfg = self.override_tbm_cfg_params(build_cfg,
154 ["build_cmds",
155 "required_artefacts",
156 "artifact_capture_rex"],
157 **over_dict)
158
159 # Overrides path in expected artefacts
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100160 print("Loading config %s" % name)
Minos Galanakisea421232019-06-20 17:11:28 +0100161
162 build_pool.append(TFM_Builder(
163 name=name,
164 work_dir=self._tbm_work_dir,
165 cfg_dict=build_cfg,
166 build_threads=self._tbm_build_threads,
167 img_sizes=self._tbm_img_sizes,
168 relative_paths=self._tbm_relative_paths))
169 # When a seed pool is provided iterate through the entries
170 # and update platform spefific parameters
171 elif len(self._tbm_build_cfg):
172
173 for name, i in self._tbm_build_cfg.items():
174 # Do not modify the original config
175 build_cfg = deepcopy(self.tbm_common_cfg)
176
177 # Extract the common for all elements of config
178 for key in ["build_cmds", "required_artefacts"]:
179 try:
180 build_cfg[key] = deepcopy(self.tbm_common_cfg[key]
181 ["all"])
182 except KeyError as E:
183 build_cfg[key] = []
184
185 # Extract the platform specific elements of config
186 for key in ["build_cmds", "required_artefacts"]:
187 try:
188 if i.target_platform in self.tbm_common_cfg[key].keys():
189 build_cfg[key] += deepcopy(self.tbm_common_cfg[key]
190 [i.target_platform])
191 except Exception as E:
192 pass
193
194 # Merge the two dictionaries since the template may contain
195 # fixed and combinations seed parameters
196 cmd0 = build_cfg["config_template"] % \
Dean Birchf6aa3da2020-01-24 12:29:38 +0000197 dict(dict(i._asdict()), **build_cfg)
Minos Galanakisea421232019-06-20 17:11:28 +0100198
199 # Prepend configuration commoand as the first cmd
200 build_cfg["build_cmds"] = [cmd0] + build_cfg["build_cmds"]
201
202 # Set the overrid params
203 over_dict = {"_tbm_build_dir_": os.path.join(
204 self._tbm_work_dir, name),
205 "_tbm_code_dir_": build_cfg["codebase_root_dir"],
206 "_tbm_target_platform_": i.target_platform}
207
208 over_params = ["build_cmds",
209 "required_artefacts",
210 "artifact_capture_rex"]
211 build_cfg = self.override_tbm_cfg_params(build_cfg,
212 over_params,
213 **over_dict)
214
215 # Overrides path in expected artefacts
216 print("Loading config %s" % name)
217
218 build_pool.append(TFM_Builder(
219 name=name,
220 work_dir=self._tbm_work_dir,
221 cfg_dict=build_cfg,
222 build_threads=self._tbm_build_threads,
223 img_sizes=self._tbm_img_sizes,
224 relative_paths=self._tbm_relative_paths))
225 else:
226 print("Could not find any configuration. Check the rejection list")
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100227
228 status_rep = {}
Minos Galanakisea421232019-06-20 17:11:28 +0100229 build_rep = {}
230 completed_build_count = 0
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100231 print("Build: Running %d parallel build jobs" % self._tbm_conc_builds)
232 for build_pool_slice in list_chunks(build_pool, self._tbm_conc_builds):
233
234 # Start the builds
235 for build in build_pool_slice:
236 # Only produce output for the first build
237 if build_pool_slice.index(build) != 0:
238 build.mute()
239 print("Build: Starting %s" % build.get_name())
240 build.start()
241
242 # Wait for the builds to complete
243 for build in build_pool_slice:
244 # Wait for build to finish
245 build.join()
246 # Similarly print the logs of the other builds as they complete
247 if build_pool_slice.index(build) != 0:
248 build.log()
Minos Galanakisea421232019-06-20 17:11:28 +0100249 completed_build_count += 1
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100250 print("Build: Finished %s" % build.get_name())
Minos Galanakisea421232019-06-20 17:11:28 +0100251 print("Build Progress:")
252 show_progress(completed_build_count, len(build_pool))
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100253
254 # Store status in report
255 status_rep[build.get_name()] = build.get_status()
Minos Galanakisea421232019-06-20 17:11:28 +0100256 build_rep[build.get_name()] = build.report()
257
258 # Include the original input configuration in the report
259
260 metadata = {"input_build_cfg": self._tbm_cfg,
261 "build_dir": self._tbm_work_dir
262 if not self._tbm_relative_paths
263 else resolve_rel_path(self._tbm_work_dir),
264 "time": time()}
265
266 full_rep = {"report": build_rep,
267 "_metadata_": metadata}
268
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100269 # Store the report
270 self.stash("Build Status", status_rep)
271 self.stash("Build Report", full_rep)
272
273 if self._tbm_report:
274 print("Exported build report to file:", self._tbm_report)
275 save_json(self._tbm_report, full_rep)
276
277 def post_eval(self):
278 """ If a single build failed fail the test """
279 try:
Minos Galanakisea421232019-06-20 17:11:28 +0100280 status_dict = self.unstash("Build Status")
281 if not status_dict:
282 raise Exception()
283 retcode_sum = sum(status_dict.values())
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100284 if retcode_sum != 0:
285 raise Exception()
286 return True
287 except Exception as e:
288 return False
289
290 def post_exec(self, eval_ret):
291 """ Generate a report and fail the script if build == unsuccessfull"""
292
293 self.print_summary()
294 if not eval_ret:
295 print("ERROR: ====> Build Failed! %s" % self.get_name())
296 self.set_status(1)
297 else:
298 print("SUCCESS: ====> Build Complete!")
299 self.set_status(0)
300
301 def get_report(self):
302 """ Expose the internal report to a new object for external classes """
303 return deepcopy(self.unstash("Build Report"))
304
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100305 def load_config(self, config, work_dir):
306 try:
307 # passing config_name param supersseeds fileparam
308 if isinstance(config, dict):
309 ret_cfg = deepcopy(config)
310 elif isinstance(config, str):
311 # If the string does not descrive a file try to look for it in
312 # work directory
313 if not os.path.isfile(config):
314 # remove path from file
315 config_2 = os.path.split(config)[-1]
316 # look in the current working directory
317 config_2 = os.path.join(work_dir, config_2)
318 if not os.path.isfile(config_2):
319 m = "Could not find cfg in %s or %s " % (config,
320 config_2)
321 raise Exception(m)
322 # If fille exists in working directory
323 else:
324 config = config_2
325 ret_cfg = load_json(config)
326
327 else:
328 raise Exception("Need to provide a valid config name or file."
329 "Please use --config/--config-file parameter.")
330 except Exception as e:
331 print("Error:%s \nCould not load a valid config" % e)
332 sys.exit(1)
333
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100334 return ret_cfg
335
336 def parse_config(self, cfg):
337 """ Parse a valid configuration file into a set of build dicts """
338
Minos Galanakisea421232019-06-20 17:11:28 +0100339 ret_cfg = {}
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100340
Minos Galanakisea421232019-06-20 17:11:28 +0100341 # Config entries which are not subject to changes during combinations
342 static_cfg = cfg["common_params"]
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100343
Minos Galanakisea421232019-06-20 17:11:28 +0100344 # Converth the code path to absolute path
345 abs_code_dir = static_cfg["codebase_root_dir"]
346 abs_code_dir = os.path.abspath(os.path.expanduser(abs_code_dir))
347 static_cfg["codebase_root_dir"] = abs_code_dir
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100348
Minos Galanakisea421232019-06-20 17:11:28 +0100349 # seed_params is an optional field. Do not proccess if it is missing
350 if "seed_params" in cfg:
351 comb_cfg = cfg["seed_params"]
352 # Generate a list of all possible confugration combinations
353 ret_cfg = TFM_Build_Manager.generate_config_list(comb_cfg,
354 static_cfg)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100355
Minos Galanakisea421232019-06-20 17:11:28 +0100356 # invalid is an optional field. Do not proccess if it is missing
357 if "invalid" in cfg:
358 # Invalid configurations(Do not build)
359 invalid_cfg = cfg["invalid"]
360 # Remove the rejected entries from the test list
361 rejection_cfg = TFM_Build_Manager.generate_rejection_list(
362 comb_cfg,
363 static_cfg,
364 invalid_cfg)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100365
Minos Galanakisea421232019-06-20 17:11:28 +0100366 # Subtract the two configurations
367 ret_cfg = {k: v for k, v in ret_cfg.items()
368 if k not in rejection_cfg}
369 self.simple_config = False
370 else:
371 self.simple_config = True
372 return ret_cfg, static_cfg
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100373
Minos Galanakisea421232019-06-20 17:11:28 +0100374 # ----- Override bellow methods when subclassing for other projects ----- #
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100375
Minos Galanakisea421232019-06-20 17:11:28 +0100376 def print_summary(self):
377 """ Print an comprehensive list of the build jobs with their status """
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100378
Minos Galanakisea421232019-06-20 17:11:28 +0100379 try:
380 full_rep = self.unstash("Build Report")["report"]
381 fl = ([k for k, v in full_rep.items() if v['status'] == 'Failed'])
382 ps = ([k for k, v in full_rep.items() if v['status'] == 'Success'])
383 except Exception as E:
384 print("No report generated")
385 return
386 if fl:
387 print_test(t_list=fl, status="failed", tname="Builds")
388 if ps:
389 print_test(t_list=ps, status="passed", tname="Builds")
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100390
Minos Galanakisea421232019-06-20 17:11:28 +0100391 @staticmethod
392 def generate_config_list(seed_config, static_config):
393 """ Generate all possible configuration combinations from a group of
394 lists of compiler options"""
395 config_list = []
396
397 if static_config["config_type"] == "tf-m":
398 cfg_name = "TFM_Build_CFG"
399 # Ensure the fieds are sorted in the desired order
400 # seed_config can be a subset of sort order for configurations with
401 # optional parameters.
402 tags = [n for n in static_config["sort_order"]
403 if n in seed_config.keys()]
404
405 data = []
406 for key in tags:
407 data.append(seed_config[key])
408 config_list = gen_cfg_combinations(cfg_name,
409 " ".join(tags),
410 *data)
411 else:
412 print("Not information for project type: %s."
413 " Please check config" % static_config["config_type"])
414
415 ret_cfg = {}
416 # Notify the user for the rejected configuations
417 for i in config_list:
418 # Convert named tuples to string with boolean support
419 i_str = "_".join(map(lambda x: repr(x)
420 if isinstance(x, bool) else x, list(i)))
421
422 # Replace bollean vaiables with more BL2/NOBL2 and use it as"
423 # configuration name.
424 ret_cfg[i_str.replace("True", "BL2").replace("False", "NOBL2")] = i
425
426 return ret_cfg
427
428 @staticmethod
429 def generate_rejection_list(seed_config,
430 static_config,
431 rejection_list):
432 rejection_cfg = {}
433
434 if static_config["config_type"] == "tf-m":
435
436 # If rejection list is empty do nothing
437 if not rejection_list:
438 return rejection_cfg
439
440 tags = [n for n in static_config["sort_order"]
441 if n in seed_config.keys()]
442 sorted_default_lst = [seed_config[k] for k in tags]
443
444 # If tags are not alligned with rejection list entries quit
445 if len(tags) != len(rejection_list[0]):
446 print(len(tags), len(rejection_list[0]))
447 print("Error, tags should be assigned to each "
448 "of the rejection inputs")
449 return []
450
451 # Replace wildcard ( "*") entries with every
452 # inluded in cfg variant
453 for k in rejection_list:
454 # Pad the omitted values with wildcard char *
455 res_list = list(k) + ["*"] * (5 - len(k))
456 print("Working on rejection input: %s" % (res_list))
457
458 for n in range(len(res_list)):
459
460 res_list[n] = [res_list[n]] if res_list[n] != "*" \
461 else sorted_default_lst[n]
462
463 # Generate a configuration and a name for the completed array
464 rj_cfg = TFM_Build_Manager.generate_config_list(
465 dict(zip(tags, res_list)),
466 static_config)
467
468 # Append the configuration to the existing ones
Dean Birchf6aa3da2020-01-24 12:29:38 +0000469 rejection_cfg = dict(rejection_cfg, **rj_cfg)
Minos Galanakisea421232019-06-20 17:11:28 +0100470
471 # Notfy the user for the rejected configuations
472 for i in rejection_cfg.keys():
473 print("Rejecting config %s" % i)
474 else:
475 print("Not information for project type: %s."
476 " Please check config" % static_config["config_type"])
477 return rejection_cfg