blob: 0849a4b35ded6342dd5b616d5935b89ae9e07856 [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
73 def pre_eval(self):
74 """ Tests that need to be run in set-up state """
75 return True
76
77 def pre_exec(self, eval_ret):
78 """ """
79
Minos Galanakisea421232019-06-20 17:11:28 +010080 def override_tbm_cfg_params(self, config, override_keys, **params):
81 """ Using a dictionay as input, for each key defined in
82 override_keys it will replace the config[key] entries with
83 the key=value parameters provided """
84
85 for key in override_keys:
86 if isinstance(config[key], list):
87 config[key] = [n % params for n in config[key]]
88 elif isinstance(config[key], str):
89 config[key] = config[key] % params
90 else:
91 raise Exception("Config does not contain key %s "
92 "of type %s" % (key, config[key]))
93 return config
94
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010095 def task_exec(self):
96 """ Create a build pool and execute them in parallel """
97
98 build_pool = []
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010099
Minos Galanakisea421232019-06-20 17:11:28 +0100100 # When a config is flagged as a single build config.
101 # Name is evaluated by config type
102 if self.simple_config:
103
104 build_cfg = deepcopy(self.tbm_common_cfg)
105
106 # Extract the common for all elements of config
107 for key in ["build_cmds", "required_artefacts"]:
108 try:
109 build_cfg[key] = build_cfg[key]["all"]
110 except KeyError:
111 build_cfg[key] = []
112 name = build_cfg["config_type"]
113
114 # Override _tbm_xxx paths in commands
115 # plafrom in not guaranteed without seeds so _tbm_target_platform
116 # is ignored
117 over_dict = {"_tbm_build_dir_": os.path.join(self._tbm_work_dir,
118 name),
119 "_tbm_code_dir_": build_cfg["codebase_root_dir"]}
120
121 build_cfg = self.override_tbm_cfg_params(build_cfg,
122 ["build_cmds",
123 "required_artefacts",
124 "artifact_capture_rex"],
125 **over_dict)
126
127 # Overrides path in expected artefacts
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100128 print("Loading config %s" % name)
Minos Galanakisea421232019-06-20 17:11:28 +0100129
130 build_pool.append(TFM_Builder(
131 name=name,
132 work_dir=self._tbm_work_dir,
133 cfg_dict=build_cfg,
134 build_threads=self._tbm_build_threads,
135 img_sizes=self._tbm_img_sizes,
136 relative_paths=self._tbm_relative_paths))
137 # When a seed pool is provided iterate through the entries
138 # and update platform spefific parameters
139 elif len(self._tbm_build_cfg):
140
141 for name, i in self._tbm_build_cfg.items():
142 # Do not modify the original config
143 build_cfg = deepcopy(self.tbm_common_cfg)
144
145 # Extract the common for all elements of config
146 for key in ["build_cmds", "required_artefacts"]:
147 try:
148 build_cfg[key] = deepcopy(self.tbm_common_cfg[key]
149 ["all"])
150 except KeyError as E:
151 build_cfg[key] = []
152
153 # Extract the platform specific elements of config
154 for key in ["build_cmds", "required_artefacts"]:
155 try:
156 if i.target_platform in self.tbm_common_cfg[key].keys():
157 build_cfg[key] += deepcopy(self.tbm_common_cfg[key]
158 [i.target_platform])
159 except Exception as E:
160 pass
161
162 # Merge the two dictionaries since the template may contain
163 # fixed and combinations seed parameters
164 cmd0 = build_cfg["config_template"] % \
165 {**dict(i._asdict()), **build_cfg}
166
167 # Prepend configuration commoand as the first cmd
168 build_cfg["build_cmds"] = [cmd0] + build_cfg["build_cmds"]
169
170 # Set the overrid params
171 over_dict = {"_tbm_build_dir_": os.path.join(
172 self._tbm_work_dir, name),
173 "_tbm_code_dir_": build_cfg["codebase_root_dir"],
174 "_tbm_target_platform_": i.target_platform}
175
176 over_params = ["build_cmds",
177 "required_artefacts",
178 "artifact_capture_rex"]
179 build_cfg = self.override_tbm_cfg_params(build_cfg,
180 over_params,
181 **over_dict)
182
183 # Overrides path in expected artefacts
184 print("Loading config %s" % name)
185
186 build_pool.append(TFM_Builder(
187 name=name,
188 work_dir=self._tbm_work_dir,
189 cfg_dict=build_cfg,
190 build_threads=self._tbm_build_threads,
191 img_sizes=self._tbm_img_sizes,
192 relative_paths=self._tbm_relative_paths))
193 else:
194 print("Could not find any configuration. Check the rejection list")
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100195
196 status_rep = {}
Minos Galanakisea421232019-06-20 17:11:28 +0100197 build_rep = {}
198 completed_build_count = 0
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100199 print("Build: Running %d parallel build jobs" % self._tbm_conc_builds)
200 for build_pool_slice in list_chunks(build_pool, self._tbm_conc_builds):
201
202 # Start the builds
203 for build in build_pool_slice:
204 # Only produce output for the first build
205 if build_pool_slice.index(build) != 0:
206 build.mute()
207 print("Build: Starting %s" % build.get_name())
208 build.start()
209
210 # Wait for the builds to complete
211 for build in build_pool_slice:
212 # Wait for build to finish
213 build.join()
214 # Similarly print the logs of the other builds as they complete
215 if build_pool_slice.index(build) != 0:
216 build.log()
Minos Galanakisea421232019-06-20 17:11:28 +0100217 completed_build_count += 1
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100218 print("Build: Finished %s" % build.get_name())
Minos Galanakisea421232019-06-20 17:11:28 +0100219 print("Build Progress:")
220 show_progress(completed_build_count, len(build_pool))
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100221
222 # Store status in report
223 status_rep[build.get_name()] = build.get_status()
Minos Galanakisea421232019-06-20 17:11:28 +0100224 build_rep[build.get_name()] = build.report()
225
226 # Include the original input configuration in the report
227
228 metadata = {"input_build_cfg": self._tbm_cfg,
229 "build_dir": self._tbm_work_dir
230 if not self._tbm_relative_paths
231 else resolve_rel_path(self._tbm_work_dir),
232 "time": time()}
233
234 full_rep = {"report": build_rep,
235 "_metadata_": metadata}
236
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100237 # Store the report
238 self.stash("Build Status", status_rep)
239 self.stash("Build Report", full_rep)
240
241 if self._tbm_report:
242 print("Exported build report to file:", self._tbm_report)
243 save_json(self._tbm_report, full_rep)
244
245 def post_eval(self):
246 """ If a single build failed fail the test """
247 try:
Minos Galanakisea421232019-06-20 17:11:28 +0100248 status_dict = self.unstash("Build Status")
249 if not status_dict:
250 raise Exception()
251 retcode_sum = sum(status_dict.values())
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100252 if retcode_sum != 0:
253 raise Exception()
254 return True
255 except Exception as e:
256 return False
257
258 def post_exec(self, eval_ret):
259 """ Generate a report and fail the script if build == unsuccessfull"""
260
261 self.print_summary()
262 if not eval_ret:
263 print("ERROR: ====> Build Failed! %s" % self.get_name())
264 self.set_status(1)
265 else:
266 print("SUCCESS: ====> Build Complete!")
267 self.set_status(0)
268
269 def get_report(self):
270 """ Expose the internal report to a new object for external classes """
271 return deepcopy(self.unstash("Build Report"))
272
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100273 def load_config(self, config, work_dir):
274 try:
275 # passing config_name param supersseeds fileparam
276 if isinstance(config, dict):
277 ret_cfg = deepcopy(config)
278 elif isinstance(config, str):
279 # If the string does not descrive a file try to look for it in
280 # work directory
281 if not os.path.isfile(config):
282 # remove path from file
283 config_2 = os.path.split(config)[-1]
284 # look in the current working directory
285 config_2 = os.path.join(work_dir, config_2)
286 if not os.path.isfile(config_2):
287 m = "Could not find cfg in %s or %s " % (config,
288 config_2)
289 raise Exception(m)
290 # If fille exists in working directory
291 else:
292 config = config_2
293 ret_cfg = load_json(config)
294
295 else:
296 raise Exception("Need to provide a valid config name or file."
297 "Please use --config/--config-file parameter.")
298 except Exception as e:
299 print("Error:%s \nCould not load a valid config" % e)
300 sys.exit(1)
301
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100302 return ret_cfg
303
304 def parse_config(self, cfg):
305 """ Parse a valid configuration file into a set of build dicts """
306
Minos Galanakisea421232019-06-20 17:11:28 +0100307 ret_cfg = {}
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100308
Minos Galanakisea421232019-06-20 17:11:28 +0100309 # Config entries which are not subject to changes during combinations
310 static_cfg = cfg["common_params"]
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100311
Minos Galanakisea421232019-06-20 17:11:28 +0100312 # Converth the code path to absolute path
313 abs_code_dir = static_cfg["codebase_root_dir"]
314 abs_code_dir = os.path.abspath(os.path.expanduser(abs_code_dir))
315 static_cfg["codebase_root_dir"] = abs_code_dir
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100316
Minos Galanakisea421232019-06-20 17:11:28 +0100317 # seed_params is an optional field. Do not proccess if it is missing
318 if "seed_params" in cfg:
319 comb_cfg = cfg["seed_params"]
320 # Generate a list of all possible confugration combinations
321 ret_cfg = TFM_Build_Manager.generate_config_list(comb_cfg,
322 static_cfg)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100323
Minos Galanakisea421232019-06-20 17:11:28 +0100324 # invalid is an optional field. Do not proccess if it is missing
325 if "invalid" in cfg:
326 # Invalid configurations(Do not build)
327 invalid_cfg = cfg["invalid"]
328 # Remove the rejected entries from the test list
329 rejection_cfg = TFM_Build_Manager.generate_rejection_list(
330 comb_cfg,
331 static_cfg,
332 invalid_cfg)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100333
Minos Galanakisea421232019-06-20 17:11:28 +0100334 # Subtract the two configurations
335 ret_cfg = {k: v for k, v in ret_cfg.items()
336 if k not in rejection_cfg}
337 self.simple_config = False
338 else:
339 self.simple_config = True
340 return ret_cfg, static_cfg
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100341
Minos Galanakisea421232019-06-20 17:11:28 +0100342 # ----- Override bellow methods when subclassing for other projects ----- #
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100343
Minos Galanakisea421232019-06-20 17:11:28 +0100344 def print_summary(self):
345 """ Print an comprehensive list of the build jobs with their status """
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100346
Minos Galanakisea421232019-06-20 17:11:28 +0100347 try:
348 full_rep = self.unstash("Build Report")["report"]
349 fl = ([k for k, v in full_rep.items() if v['status'] == 'Failed'])
350 ps = ([k for k, v in full_rep.items() if v['status'] == 'Success'])
351 except Exception as E:
352 print("No report generated")
353 return
354 if fl:
355 print_test(t_list=fl, status="failed", tname="Builds")
356 if ps:
357 print_test(t_list=ps, status="passed", tname="Builds")
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100358
Minos Galanakisea421232019-06-20 17:11:28 +0100359 @staticmethod
360 def generate_config_list(seed_config, static_config):
361 """ Generate all possible configuration combinations from a group of
362 lists of compiler options"""
363 config_list = []
364
365 if static_config["config_type"] == "tf-m":
366 cfg_name = "TFM_Build_CFG"
367 # Ensure the fieds are sorted in the desired order
368 # seed_config can be a subset of sort order for configurations with
369 # optional parameters.
370 tags = [n for n in static_config["sort_order"]
371 if n in seed_config.keys()]
372
373 data = []
374 for key in tags:
375 data.append(seed_config[key])
376 config_list = gen_cfg_combinations(cfg_name,
377 " ".join(tags),
378 *data)
379 else:
380 print("Not information for project type: %s."
381 " Please check config" % static_config["config_type"])
382
383 ret_cfg = {}
384 # Notify the user for the rejected configuations
385 for i in config_list:
386 # Convert named tuples to string with boolean support
387 i_str = "_".join(map(lambda x: repr(x)
388 if isinstance(x, bool) else x, list(i)))
389
390 # Replace bollean vaiables with more BL2/NOBL2 and use it as"
391 # configuration name.
392 ret_cfg[i_str.replace("True", "BL2").replace("False", "NOBL2")] = i
393
394 return ret_cfg
395
396 @staticmethod
397 def generate_rejection_list(seed_config,
398 static_config,
399 rejection_list):
400 rejection_cfg = {}
401
402 if static_config["config_type"] == "tf-m":
403
404 # If rejection list is empty do nothing
405 if not rejection_list:
406 return rejection_cfg
407
408 tags = [n for n in static_config["sort_order"]
409 if n in seed_config.keys()]
410 sorted_default_lst = [seed_config[k] for k in tags]
411
412 # If tags are not alligned with rejection list entries quit
413 if len(tags) != len(rejection_list[0]):
414 print(len(tags), len(rejection_list[0]))
415 print("Error, tags should be assigned to each "
416 "of the rejection inputs")
417 return []
418
419 # Replace wildcard ( "*") entries with every
420 # inluded in cfg variant
421 for k in rejection_list:
422 # Pad the omitted values with wildcard char *
423 res_list = list(k) + ["*"] * (5 - len(k))
424 print("Working on rejection input: %s" % (res_list))
425
426 for n in range(len(res_list)):
427
428 res_list[n] = [res_list[n]] if res_list[n] != "*" \
429 else sorted_default_lst[n]
430
431 # Generate a configuration and a name for the completed array
432 rj_cfg = TFM_Build_Manager.generate_config_list(
433 dict(zip(tags, res_list)),
434 static_config)
435
436 # Append the configuration to the existing ones
437 rejection_cfg = {**rejection_cfg, **rj_cfg}
438
439 # Notfy the user for the rejected configuations
440 for i in rejection_cfg.keys():
441 print("Rejecting config %s" % i)
442 else:
443 print("Not information for project type: %s."
444 " Please check config" % static_config["config_type"])
445 return rejection_cfg