blob: 282341bcc64b034cd2604ef35a5695c63e0bdbc9 [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(),
Andrew Lambb47b7dc2020-04-07 10:20:32 -060075 'product': config.build_target.id.value,
David Burger7fd1dbe2020-03-26 09:26:55 -060076 }
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 )):
Andrew Lambb9e660f2020-04-06 11:37:22 -0600142 result['no-firmware'] = True
Andrew Lamb883fa042020-04-06 11:37:22 -0600143
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()
Andrew Lamb7d536782020-04-07 10:23:55 -0600173 if not config.sw_config.HasField('audio_config'):
David Burger7fd1dbe2020-03-26 09:26:55 -0600174 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
Andrew Lamb7806ce92020-04-07 10:22:17 -0600197def _BuildIdentity(hw_scan_config, program, brand_scan_config=None):
David Burger7fd1dbe2020-03-26 09:26:55 -0600198 identity = {}
199 _Set(hw_scan_config.firmware_sku, identity, 'sku-id')
200 _Set(hw_scan_config.smbios_name_match, identity, 'smbios-name-match')
Andrew Lamb7806ce92020-04-07 10:22:17 -0600201 # 'platform-name' is needed to support 'mosys platform name'. Clients should
202 # longer require platform name, but set it here for backwards compatibility.
203 _Set(program.name, identity, 'platform-name')
David Burger7fd1dbe2020-03-26 09:26:55 -0600204 # ARM architecture
205 _Set(hw_scan_config.device_tree_compatible_match, identity,
206 'device-tree-compatible-match')
207
208 if brand_scan_config:
209 _Set(brand_scan_config.whitelabel_tag, identity, 'whitelabel-tag')
210
211 return identity
212
213
214def _Lookup(id_value, id_map):
215 if id_value.value:
216 key = id_value.value
217 if key in id_map:
218 return id_map[id_value.value]
219 error = 'Failed to lookup %s with value: %s' % (
220 id_value.__class__.__name__.replace('Id', ''), key)
221 print(error)
222 print('Check the config contents provided:')
223 pp = pprint.PrettyPrinter(indent=4)
224 pp.pprint(id_map)
225 raise Exception(error)
226
227
228def _TransformBuildConfigs(config):
229 partners = dict([(x.id.value, x) for x in config.partners.value])
230 programs = dict([(x.id.value, x) for x in config.programs.value])
David Burger7fd1dbe2020-03-26 09:26:55 -0600231 sw_configs = list(config.software_configs)
232 brand_configs = dict([(x.brand_id.value, x) for x in config.brand_configs])
233
C Shapiroa0b766c2020-03-31 08:35:28 -0500234 if len(config.build_targets) != 1:
235 # Artifact of sharing the config_bundle for analysis and transforms.
236 # Integrated analysis of multiple programs/projects it the only time
237 # having multiple build targets would be valid.
238 raise Exception('Single build_target required for transform')
239
David Burger7fd1dbe2020-03-26 09:26:55 -0600240 results = {}
241 for hw_design in config.designs.value:
242 if config.device_brands.value:
243 device_brands = [x for x in config.device_brands.value
244 if x.design_id.value == hw_design.id.value]
245 else:
246 device_brands = [device_brand_pb2.DeviceBrand()]
247
248 for device_brand in device_brands:
249 # Brand config can be empty since platform JSON config allows it
250 brand_config = brand_config_pb2.BrandConfig()
251 if device_brand.id.value in brand_configs:
252 brand_config = brand_configs[device_brand.id.value]
253
254 for hw_design_config in hw_design.configs:
255 design_id = hw_design_config.id.value
256 sw_config_matches = [x for x in sw_configs
257 if x.design_config_id.value == design_id]
258 if len(sw_config_matches) == 1:
259 sw_config = sw_config_matches[0]
260 elif len(sw_config_matches) > 1:
261 raise Exception('Multiple software configs found for: %s' % design_id)
262 else:
263 raise Exception('Software config is required for: %s' % design_id)
264
265 transformed_config = _TransformBuildConfig(Config(
266 program=_Lookup(hw_design.program_id, programs),
267 hw_design=hw_design,
268 odm=_Lookup(hw_design.odm_id, partners),
269 hw_design_config=hw_design_config,
270 device_brand=device_brand,
271 oem=_Lookup(device_brand.oem_id, partners),
272 sw_config=sw_config,
273 brand_config=brand_config,
C Shapiroa0b766c2020-03-31 08:35:28 -0500274 build_target=config.build_targets[0]))
David Burger7fd1dbe2020-03-26 09:26:55 -0600275
276 config_json = json.dumps(transformed_config,
277 sort_keys=True,
278 indent=2,
279 separators=(',', ': '))
280
281 if config_json not in results:
282 results[config_json] = transformed_config
283
284 return list(results.values())
285
286
287def _TransformBuildConfig(config):
288 """Transforms Config instance into target platform JSON schema.
289
290 Args:
291 config: Config namedtuple
292
293 Returns:
294 Unique config payload based on the platform JSON schema.
295 """
296 result = {
297 'identity': _BuildIdentity(
298 config.sw_config.id_scan_config,
Andrew Lamb7806ce92020-04-07 10:22:17 -0600299 config.program,
David Burger7fd1dbe2020-03-26 09:26:55 -0600300 config.brand_config.scan_config),
301 'name': config.hw_design.name.lower(),
302 }
303
304 _Set(_BuildArc(config), result, 'arc')
305 _Set(_BuildAudio(config), result, 'audio')
306 _Set(config.device_brand.brand_code, result, 'brand-code')
307 _Set(_BuildFirmware(config), result, 'firmware')
308 _Set(_BuildFwSigning(config), result, 'firmware-signing')
309 _Set(_BuildFingerprint(
310 config.hw_design_config.hardware_topology), result, 'fingerprint')
311 power_prefs = config.sw_config.power_config.preferences
312 power_prefs_map = dict(
313 (x.replace('_', '-'),
314 power_prefs[x]) for x in power_prefs)
315 _Set(power_prefs_map, result, 'power')
316
317 return result
318
319
320def WriteOutput(configs, output=None):
321 """Writes a list of configs to platform JSON format.
322
323 Args:
324 configs: List of config dicts defined in cros_config_schema.yaml
325 output: Target file output (if None, prints to stdout)
326 """
327 json_output = json.dumps(
328 {'chromeos': {
329 'configs': configs,
330 }},
331 sort_keys=True,
332 indent=2,
333 separators=(',', ': '))
334 if output:
335 with open(output, 'w') as output_stream:
336 # Using print function adds proper trailing newline.
337 print(json_output, file=output_stream)
338 else:
339 print(json_output)
340
341
342def _ReadConfig(path):
343 """Reads a binary proto from a file.
344
345 Args:
346 path: Path to the binary proto.
347 """
348 config = config_bundle_pb2.ConfigBundle()
349 with open(path, 'rb') as f:
350 config.ParseFromString(f.read())
351 return config
352
353
354def _MergeConfigs(configs):
355 result = config_bundle_pb2.ConfigBundle()
356 for config in configs:
357 result.MergeFrom(config)
358
359 return result
360
361
362def Main(project_configs,
363 program_config,
364 output):
365 """Transforms source proto config into platform JSON.
366
367 Args:
368 project_configs: List of source project configs to transform.
369 program_config: Program config for the given set of projects.
370 output: Output file that will be generated by the transform.
371 """
372 WriteOutput(
373 _TransformBuildConfigs(
374 _MergeConfigs(
375 [_ReadConfig(program_config)] +
376 [_ReadConfig(config) for config in project_configs],)
377 ,),
378 output)
379
380
381def main(argv=None):
382 """Main program which parses args and runs
383
384 Args:
385 argv: List of command line arguments, if None uses sys.argv.
386 """
387 if argv is None:
388 argv = sys.argv[1:]
389 opts = ParseArgs(argv)
390 Main(opts.project_configs, opts.program_config, opts.output)
391
392
393if __name__ == '__main__':
394 sys.exit(main(sys.argv[1:]))