blob: 165000f979a3c936ff74a3801a657c66eb81cb90 [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):
110 if not config.sw_config.firmware:
111 return {
112 'no-firmware': True,
113 }
114 fw = config.sw_config.firmware
115 main_ro = fw.main_ro_payload
116 main_rw = fw.main_rw_payload
117 ec_ro = fw.ec_ro_payload
118 pd_ro = fw.pd_ro_payload
119
120 build_targets = {}
121 _Set(_FwBuildTarget(main_ro), build_targets, 'depthcharge')
122 # Default to RO build target if no RW set
123 _Set(_FwBuildTarget(main_rw) or _FwBuildTarget(main_ro),
124 build_targets,
125 'coreboot')
126 _Set(_FwBuildTarget(ec_ro), build_targets, 'ec')
127 _Set(list(fw.ec_extras), build_targets, 'ec_extras')
128 # Default to EC build target if no PD set
129 _Set(_FwBuildTarget(pd_ro) or _FwBuildTarget(ec_ro),
130 build_targets,
131 'libpayload')
132
133 result = {
134 'bcs-overlay': config.build_target.overlay_name,
135 'build-targets': build_targets,
136 'image-name': main_ro.firmware_image_name.lower(),
137 }
138 _Set(_FwBcsPath(fw.main_ro_payload), result, 'main-ro-image')
139 _Set(_FwBcsPath(fw.main_rw_payload), result, 'main-rw-image')
140 _Set(_FwBcsPath(fw.ec_ro_payload), result, 'ec-ro-image')
141 _Set(_FwBcsPath(fw.pd_ro_payload), result, 'pd-ro-image')
142
143 return result
144
145
146def _BuildFwSigning(config):
147 if not config.sw_config.firmware:
148 return {}
149 # TODO(shapiroc): Source signing config from separate private repo
150 return {
151 'key-id': 'DEFAULT',
152 'signature-id': config.hw_design.name.lower(),
153 }
154
155
156def _File(source, destination):
157 return {
158 'destination': destination,
159 'source': source
160 }
161
162
163def _BuildAudio(config):
164 alsa_path = '/usr/share/alsa/ucm'
165 cras_path = '/etc/cras'
166 project_name = config.hw_design.name.lower()
167 if not config.sw_config.audio_config:
168 return {}
169 audio = config.sw_config.audio_config
170 card = audio.card_name
171 files = []
172 if audio.ucm_file:
173 files.append(_File(audio.ucm_file, '%s/%s/HiFi.conf' % (alsa_path, card)))
174 if audio.ucm_master_file:
175 files.append(_File(
176 audio.ucm_master_file, '%s/%s/%s.conf' % (alsa_path, card, card)))
177 if audio.card_config_file:
178 files.append(_File(
179 audio.card_config_file, '%s/%s/%s' % (cras_path, project_name, card)))
180 if audio.dsp_file:
181 files.append(
David Burger2e254902020-04-02 16:56:01 -0600182 _File(audio.dsp_file, '%s/%s/dsp.ini' % (cras_path, project_name)))
David Burger7fd1dbe2020-03-26 09:26:55 -0600183 return {
184 'main': {
185 'cras-config-dir': project_name,
186 'files': files,
187 }
188 }
189
190
191def _BuildIdentity(hw_scan_config, brand_scan_config=None):
192 identity = {}
193 _Set(hw_scan_config.firmware_sku, identity, 'sku-id')
194 _Set(hw_scan_config.smbios_name_match, identity, 'smbios-name-match')
195 # Platform name is a redundant relic of mosys
196 _Set(hw_scan_config.smbios_name_match, identity, 'platform-name')
197 # ARM architecture
198 _Set(hw_scan_config.device_tree_compatible_match, identity,
199 'device-tree-compatible-match')
200
201 if brand_scan_config:
202 _Set(brand_scan_config.whitelabel_tag, identity, 'whitelabel-tag')
203
204 return identity
205
206
207def _Lookup(id_value, id_map):
208 if id_value.value:
209 key = id_value.value
210 if key in id_map:
211 return id_map[id_value.value]
212 error = 'Failed to lookup %s with value: %s' % (
213 id_value.__class__.__name__.replace('Id', ''), key)
214 print(error)
215 print('Check the config contents provided:')
216 pp = pprint.PrettyPrinter(indent=4)
217 pp.pprint(id_map)
218 raise Exception(error)
219
220
221def _TransformBuildConfigs(config):
222 partners = dict([(x.id.value, x) for x in config.partners.value])
223 programs = dict([(x.id.value, x) for x in config.programs.value])
David Burger7fd1dbe2020-03-26 09:26:55 -0600224 sw_configs = list(config.software_configs)
225 brand_configs = dict([(x.brand_id.value, x) for x in config.brand_configs])
226
C Shapiroa0b766c2020-03-31 08:35:28 -0500227 if len(config.build_targets) != 1:
228 # Artifact of sharing the config_bundle for analysis and transforms.
229 # Integrated analysis of multiple programs/projects it the only time
230 # having multiple build targets would be valid.
231 raise Exception('Single build_target required for transform')
232
David Burger7fd1dbe2020-03-26 09:26:55 -0600233 results = {}
234 for hw_design in config.designs.value:
235 if config.device_brands.value:
236 device_brands = [x for x in config.device_brands.value
237 if x.design_id.value == hw_design.id.value]
238 else:
239 device_brands = [device_brand_pb2.DeviceBrand()]
240
241 for device_brand in device_brands:
242 # Brand config can be empty since platform JSON config allows it
243 brand_config = brand_config_pb2.BrandConfig()
244 if device_brand.id.value in brand_configs:
245 brand_config = brand_configs[device_brand.id.value]
246
247 for hw_design_config in hw_design.configs:
248 design_id = hw_design_config.id.value
249 sw_config_matches = [x for x in sw_configs
250 if x.design_config_id.value == design_id]
251 if len(sw_config_matches) == 1:
252 sw_config = sw_config_matches[0]
253 elif len(sw_config_matches) > 1:
254 raise Exception('Multiple software configs found for: %s' % design_id)
255 else:
256 raise Exception('Software config is required for: %s' % design_id)
257
258 transformed_config = _TransformBuildConfig(Config(
259 program=_Lookup(hw_design.program_id, programs),
260 hw_design=hw_design,
261 odm=_Lookup(hw_design.odm_id, partners),
262 hw_design_config=hw_design_config,
263 device_brand=device_brand,
264 oem=_Lookup(device_brand.oem_id, partners),
265 sw_config=sw_config,
266 brand_config=brand_config,
C Shapiroa0b766c2020-03-31 08:35:28 -0500267 build_target=config.build_targets[0]))
David Burger7fd1dbe2020-03-26 09:26:55 -0600268
269 config_json = json.dumps(transformed_config,
270 sort_keys=True,
271 indent=2,
272 separators=(',', ': '))
273
274 if config_json not in results:
275 results[config_json] = transformed_config
276
277 return list(results.values())
278
279
280def _TransformBuildConfig(config):
281 """Transforms Config instance into target platform JSON schema.
282
283 Args:
284 config: Config namedtuple
285
286 Returns:
287 Unique config payload based on the platform JSON schema.
288 """
289 result = {
290 'identity': _BuildIdentity(
291 config.sw_config.id_scan_config,
292 config.brand_config.scan_config),
293 'name': config.hw_design.name.lower(),
294 }
295
296 _Set(_BuildArc(config), result, 'arc')
297 _Set(_BuildAudio(config), result, 'audio')
298 _Set(config.device_brand.brand_code, result, 'brand-code')
299 _Set(_BuildFirmware(config), result, 'firmware')
300 _Set(_BuildFwSigning(config), result, 'firmware-signing')
301 _Set(_BuildFingerprint(
302 config.hw_design_config.hardware_topology), result, 'fingerprint')
303 power_prefs = config.sw_config.power_config.preferences
304 power_prefs_map = dict(
305 (x.replace('_', '-'),
306 power_prefs[x]) for x in power_prefs)
307 _Set(power_prefs_map, result, 'power')
308
309 return result
310
311
312def WriteOutput(configs, output=None):
313 """Writes a list of configs to platform JSON format.
314
315 Args:
316 configs: List of config dicts defined in cros_config_schema.yaml
317 output: Target file output (if None, prints to stdout)
318 """
319 json_output = json.dumps(
320 {'chromeos': {
321 'configs': configs,
322 }},
323 sort_keys=True,
324 indent=2,
325 separators=(',', ': '))
326 if output:
327 with open(output, 'w') as output_stream:
328 # Using print function adds proper trailing newline.
329 print(json_output, file=output_stream)
330 else:
331 print(json_output)
332
333
334def _ReadConfig(path):
335 """Reads a binary proto from a file.
336
337 Args:
338 path: Path to the binary proto.
339 """
340 config = config_bundle_pb2.ConfigBundle()
341 with open(path, 'rb') as f:
342 config.ParseFromString(f.read())
343 return config
344
345
346def _MergeConfigs(configs):
347 result = config_bundle_pb2.ConfigBundle()
348 for config in configs:
349 result.MergeFrom(config)
350
351 return result
352
353
354def Main(project_configs,
355 program_config,
356 output):
357 """Transforms source proto config into platform JSON.
358
359 Args:
360 project_configs: List of source project configs to transform.
361 program_config: Program config for the given set of projects.
362 output: Output file that will be generated by the transform.
363 """
364 WriteOutput(
365 _TransformBuildConfigs(
366 _MergeConfigs(
367 [_ReadConfig(program_config)] +
368 [_ReadConfig(config) for config in project_configs],)
369 ,),
370 output)
371
372
373def main(argv=None):
374 """Main program which parses args and runs
375
376 Args:
377 argv: List of command line arguments, if None uses sys.argv.
378 """
379 if argv is None:
380 argv = sys.argv[1:]
381 opts = ParseArgs(argv)
382 Main(opts.project_configs, opts.program_config, opts.output)
383
384
385if __name__ == '__main__':
386 sys.exit(main(sys.argv[1:]))