blob: 944410655d240d9666ccbac0c22490ff21dea7fe [file] [log] [blame]
David Burger7fd1dbe2020-03-26 09:26:55 -06001#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright 2020 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6"""Transforms config from /config/proto/api proto format to platform JSON."""
7
8import argparse
9import json
10import pprint
11import sys
12
13from collections import namedtuple
14
C Shapirofd83a5f2020-03-31 08:56:20 -050015from config.payload import config_bundle_pb2
David Burger7fd1dbe2020-03-26 09:26:55 -060016from config.api import device_brand_pb2
17from config.api.software import brand_config_pb2
18
19Config = namedtuple('Config',
20 ['program',
21 'hw_design',
22 'odm',
23 'hw_design_config',
24 'device_brand',
25 'oem',
26 'sw_config',
27 'brand_config',
28 'build_target'])
29
30
31def ParseArgs(argv):
32 """Parse the available arguments.
33
34 Invalid arguments or -h cause this function to print a message and exit.
35
36 Args:
37 argv: List of string arguments (excluding program name / argv[0])
38
39 Returns:
40 argparse.Namespace object containing the attributes.
41 """
42 parser = argparse.ArgumentParser(
43 description='Converts source proto config into platform JSON config.')
44 parser.add_argument(
45 '-c',
46 '--project_configs',
47 nargs='+',
48 type=str,
49 help='Space delimited list of source protobinary project config files.')
50 parser.add_argument(
51 '-p',
52 '--program_config',
53 type=str,
54 help='Path to the source program-level protobinary file')
55 parser.add_argument(
56 '-o',
57 '--output',
58 type=str,
59 help='Output file that will be generated')
60 return parser.parse_args(argv)
61
62
63def _Set(field, target, target_name):
64 if field:
65 target[target_name] = field
66
67
68def _BuildArc(config):
69 if config.build_target.arc:
70 build_properties = {
71 'device': config.build_target.arc.device,
72 'first-api-level': config.build_target.arc.first_api_level,
73 'marketing-name': config.device_brand.brand_name,
74 'metrics-tag': config.hw_design.name.lower(),
75 'product': config.hw_design.name.lower(),
76 }
77 if config.oem:
78 build_properties['oem'] = config.oem.name
79 return {
80 'build-properties': build_properties
81 }
82
83
84def _BuildFingerprint(hw_topology):
Andrew Lambc2c55462020-04-06 08:43:34 -060085 if hw_topology.HasField('fingerprint'):
David Burger7fd1dbe2020-03-26 09:26:55 -060086 fp = hw_topology.fingerprint.hardware_feature.fingerprint
87 location = fp.Location.DESCRIPTOR.values_by_number[fp.location].name
88 result = {
89 'sensor-location': location.lower().replace('_', '-'),
90 }
91 if fp.board:
92 result['board'] = fp.board
93 return result
94
95
96def _FwBcsPath(payload):
97 if payload and payload.firmware_image_name:
98 return 'bcs://%s.%d.%d.0.tbz2' % (
99 payload.firmware_image_name,
100 payload.version.major,
101 payload.version.minor)
102
103
104def _FwBuildTarget(payload):
105 if payload:
106 return payload.build_target_name
107
108
109def _BuildFirmware(config):
David Burger7fd1dbe2020-03-26 09:26:55 -0600110 fw = config.sw_config.firmware
111 main_ro = fw.main_ro_payload
112 main_rw = fw.main_rw_payload
113 ec_ro = fw.ec_ro_payload
114 pd_ro = fw.pd_ro_payload
115
116 build_targets = {}
117 _Set(_FwBuildTarget(main_ro), build_targets, 'depthcharge')
118 # Default to RO build target if no RW set
119 _Set(_FwBuildTarget(main_rw) or _FwBuildTarget(main_ro),
120 build_targets,
121 'coreboot')
122 _Set(_FwBuildTarget(ec_ro), build_targets, 'ec')
123 _Set(list(fw.ec_extras), build_targets, 'ec_extras')
124 # Default to EC build target if no PD set
125 _Set(_FwBuildTarget(pd_ro) or _FwBuildTarget(ec_ro),
126 build_targets,
127 'libpayload')
128
129 result = {
130 'bcs-overlay': config.build_target.overlay_name,
131 'build-targets': build_targets,
David Burger7fd1dbe2020-03-26 09:26:55 -0600132 }
Andrew Lamb883fa042020-04-06 11:37:22 -0600133
134 _Set(main_ro.firmware_image_name.lower(), result, 'image-name')
135
136 if not any((
137 main_ro.firmware_image_name,
138 main_rw.firmware_image_name,
139 ec_ro.firmware_image_name,
140 pd_ro.firmware_image_name,
141 )):
142 result['no-firmware']: True
143
144 _Set(_FwBcsPath(main_ro), result, 'main-ro-image')
145 _Set(_FwBcsPath(main_rw), result, 'main-rw-image')
146 _Set(_FwBcsPath(ec_ro), result, 'ec-ro-image')
147 _Set(_FwBcsPath(pd_ro), result, 'pd-ro-image')
David Burger7fd1dbe2020-03-26 09:26:55 -0600148
149 return result
150
151
152def _BuildFwSigning(config):
153 if not config.sw_config.firmware:
154 return {}
155 # TODO(shapiroc): Source signing config from separate private repo
156 return {
157 'key-id': 'DEFAULT',
158 'signature-id': config.hw_design.name.lower(),
159 }
160
161
162def _File(source, destination):
163 return {
164 'destination': destination,
165 'source': source
166 }
167
168
169def _BuildAudio(config):
170 alsa_path = '/usr/share/alsa/ucm'
171 cras_path = '/etc/cras'
172 project_name = config.hw_design.name.lower()
173 if not config.sw_config.audio_config:
174 return {}
175 audio = config.sw_config.audio_config
176 card = audio.card_name
177 files = []
178 if audio.ucm_file:
179 files.append(_File(audio.ucm_file, '%s/%s/HiFi.conf' % (alsa_path, card)))
180 if audio.ucm_master_file:
181 files.append(_File(
182 audio.ucm_master_file, '%s/%s/%s.conf' % (alsa_path, card, card)))
183 if audio.card_config_file:
184 files.append(_File(
185 audio.card_config_file, '%s/%s/%s' % (cras_path, project_name, card)))
186 if audio.dsp_file:
187 files.append(
David Burger2e254902020-04-02 16:56:01 -0600188 _File(audio.dsp_file, '%s/%s/dsp.ini' % (cras_path, project_name)))
David Burger7fd1dbe2020-03-26 09:26:55 -0600189 return {
190 'main': {
191 'cras-config-dir': project_name,
192 'files': files,
193 }
194 }
195
196
197def _BuildIdentity(hw_scan_config, brand_scan_config=None):
198 identity = {}
199 _Set(hw_scan_config.firmware_sku, identity, 'sku-id')
200 _Set(hw_scan_config.smbios_name_match, identity, 'smbios-name-match')
201 # Platform name is a redundant relic of mosys
202 _Set(hw_scan_config.smbios_name_match, identity, 'platform-name')
203 # ARM architecture
204 _Set(hw_scan_config.device_tree_compatible_match, identity,
205 'device-tree-compatible-match')
206
207 if brand_scan_config:
208 _Set(brand_scan_config.whitelabel_tag, identity, 'whitelabel-tag')
209
210 return identity
211
212
213def _Lookup(id_value, id_map):
214 if id_value.value:
215 key = id_value.value
216 if key in id_map:
217 return id_map[id_value.value]
218 error = 'Failed to lookup %s with value: %s' % (
219 id_value.__class__.__name__.replace('Id', ''), key)
220 print(error)
221 print('Check the config contents provided:')
222 pp = pprint.PrettyPrinter(indent=4)
223 pp.pprint(id_map)
224 raise Exception(error)
225
226
227def _TransformBuildConfigs(config):
228 partners = dict([(x.id.value, x) for x in config.partners.value])
229 programs = dict([(x.id.value, x) for x in config.programs.value])
David Burger7fd1dbe2020-03-26 09:26:55 -0600230 sw_configs = list(config.software_configs)
231 brand_configs = dict([(x.brand_id.value, x) for x in config.brand_configs])
232
C Shapiroa0b766c2020-03-31 08:35:28 -0500233 if len(config.build_targets) != 1:
234 # Artifact of sharing the config_bundle for analysis and transforms.
235 # Integrated analysis of multiple programs/projects it the only time
236 # having multiple build targets would be valid.
237 raise Exception('Single build_target required for transform')
238
David Burger7fd1dbe2020-03-26 09:26:55 -0600239 results = {}
240 for hw_design in config.designs.value:
241 if config.device_brands.value:
242 device_brands = [x for x in config.device_brands.value
243 if x.design_id.value == hw_design.id.value]
244 else:
245 device_brands = [device_brand_pb2.DeviceBrand()]
246
247 for device_brand in device_brands:
248 # Brand config can be empty since platform JSON config allows it
249 brand_config = brand_config_pb2.BrandConfig()
250 if device_brand.id.value in brand_configs:
251 brand_config = brand_configs[device_brand.id.value]
252
253 for hw_design_config in hw_design.configs:
254 design_id = hw_design_config.id.value
255 sw_config_matches = [x for x in sw_configs
256 if x.design_config_id.value == design_id]
257 if len(sw_config_matches) == 1:
258 sw_config = sw_config_matches[0]
259 elif len(sw_config_matches) > 1:
260 raise Exception('Multiple software configs found for: %s' % design_id)
261 else:
262 raise Exception('Software config is required for: %s' % design_id)
263
264 transformed_config = _TransformBuildConfig(Config(
265 program=_Lookup(hw_design.program_id, programs),
266 hw_design=hw_design,
267 odm=_Lookup(hw_design.odm_id, partners),
268 hw_design_config=hw_design_config,
269 device_brand=device_brand,
270 oem=_Lookup(device_brand.oem_id, partners),
271 sw_config=sw_config,
272 brand_config=brand_config,
C Shapiroa0b766c2020-03-31 08:35:28 -0500273 build_target=config.build_targets[0]))
David Burger7fd1dbe2020-03-26 09:26:55 -0600274
275 config_json = json.dumps(transformed_config,
276 sort_keys=True,
277 indent=2,
278 separators=(',', ': '))
279
280 if config_json not in results:
281 results[config_json] = transformed_config
282
283 return list(results.values())
284
285
286def _TransformBuildConfig(config):
287 """Transforms Config instance into target platform JSON schema.
288
289 Args:
290 config: Config namedtuple
291
292 Returns:
293 Unique config payload based on the platform JSON schema.
294 """
295 result = {
296 'identity': _BuildIdentity(
297 config.sw_config.id_scan_config,
298 config.brand_config.scan_config),
299 'name': config.hw_design.name.lower(),
300 }
301
302 _Set(_BuildArc(config), result, 'arc')
303 _Set(_BuildAudio(config), result, 'audio')
304 _Set(config.device_brand.brand_code, result, 'brand-code')
305 _Set(_BuildFirmware(config), result, 'firmware')
306 _Set(_BuildFwSigning(config), result, 'firmware-signing')
307 _Set(_BuildFingerprint(
308 config.hw_design_config.hardware_topology), result, 'fingerprint')
309 power_prefs = config.sw_config.power_config.preferences
310 power_prefs_map = dict(
311 (x.replace('_', '-'),
312 power_prefs[x]) for x in power_prefs)
313 _Set(power_prefs_map, result, 'power')
314
315 return result
316
317
318def WriteOutput(configs, output=None):
319 """Writes a list of configs to platform JSON format.
320
321 Args:
322 configs: List of config dicts defined in cros_config_schema.yaml
323 output: Target file output (if None, prints to stdout)
324 """
325 json_output = json.dumps(
326 {'chromeos': {
327 'configs': configs,
328 }},
329 sort_keys=True,
330 indent=2,
331 separators=(',', ': '))
332 if output:
333 with open(output, 'w') as output_stream:
334 # Using print function adds proper trailing newline.
335 print(json_output, file=output_stream)
336 else:
337 print(json_output)
338
339
340def _ReadConfig(path):
341 """Reads a binary proto from a file.
342
343 Args:
344 path: Path to the binary proto.
345 """
346 config = config_bundle_pb2.ConfigBundle()
347 with open(path, 'rb') as f:
348 config.ParseFromString(f.read())
349 return config
350
351
352def _MergeConfigs(configs):
353 result = config_bundle_pb2.ConfigBundle()
354 for config in configs:
355 result.MergeFrom(config)
356
357 return result
358
359
360def Main(project_configs,
361 program_config,
362 output):
363 """Transforms source proto config into platform JSON.
364
365 Args:
366 project_configs: List of source project configs to transform.
367 program_config: Program config for the given set of projects.
368 output: Output file that will be generated by the transform.
369 """
370 WriteOutput(
371 _TransformBuildConfigs(
372 _MergeConfigs(
373 [_ReadConfig(program_config)] +
374 [_ReadConfig(config) for config in project_configs],)
375 ,),
376 output)
377
378
379def main(argv=None):
380 """Main program which parses args and runs
381
382 Args:
383 argv: List of command line arguments, if None uses sys.argv.
384 """
385 if argv is None:
386 argv = sys.argv[1:]
387 opts = ParseArgs(argv)
388 Main(opts.project_configs, opts.program_config, opts.output)
389
390
391if __name__ == '__main__':
392 sys.exit(main(sys.argv[1:]))