blob: 646a2bc28954baa4243f5be84177043a1e73a00f [file] [log] [blame]
Mike Frysingerd13faeb2013-09-05 16:00:46 -04001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""ChromeOS image pusher (from cbuildbot to signer).
6
7This pushes files from the archive bucket to the signer bucket and marks
8artifacts for signing (which a signing process will look for).
9"""
10
Mike Frysingere852b072021-05-21 12:39:03 -040011import configparser
Mike Frysingerd13faeb2013-09-05 16:00:46 -040012import getpass
Mike Frysingere852b072021-05-21 12:39:03 -040013import io
Chris McDonald59650c32021-07-20 15:29:28 -060014import logging
Mike Frysingerd13faeb2013-09-05 16:00:46 -040015import os
16import re
Mike Frysinger09fe0122014-02-09 02:44:05 -050017import textwrap
Mike Frysingerd13faeb2013-09-05 16:00:46 -040018
Mike Frysingerd13faeb2013-09-05 16:00:46 -040019from chromite.lib import commandline
Chris McDonald59650c32021-07-20 15:29:28 -060020from chromite.lib import constants
Mike Frysingerd13faeb2013-09-05 16:00:46 -040021from chromite.lib import cros_build_lib
Mike Frysingerd13faeb2013-09-05 16:00:46 -040022from chromite.lib import gs
23from chromite.lib import osutils
24from chromite.lib import signing
25
26
27# This will split a fully qualified ChromeOS version string up.
28# R34-5126.0.0 will break into "34" and "5126.0.0".
29VERSION_REGEX = r'^R([0-9]+)-([^-]+)'
30
Mike Frysingerdad40d62014-02-09 02:18:02 -050031# The test signers will scan this dir looking for test work.
32# Keep it in sync with the signer config files [gs_test_buckets].
33TEST_SIGN_BUCKET_BASE = 'gs://chromeos-throw-away-bucket/signer-tests'
34
David Rileyf8205122015-09-04 13:46:36 -070035# Keysets that are only valid in the above test bucket.
36TEST_KEYSET_PREFIX = 'test-keys'
37TEST_KEYSETS = set((
38 'mp',
39 'premp',
40 'nvidia-premp',
41))
Mike Frysingerdad40d62014-02-09 02:18:02 -050042
Amey Deshpandea936c622015-08-12 17:27:54 -070043# Supported image types for signing.
44_SUPPORTED_IMAGE_TYPES = (
45 constants.IMAGE_TYPE_RECOVERY,
46 constants.IMAGE_TYPE_FACTORY,
47 constants.IMAGE_TYPE_FIRMWARE,
Vincent Palatind599c662015-10-26 09:51:41 -070048 constants.IMAGE_TYPE_ACCESSORY_USBPD,
Evan Benn4d061102022-02-14 12:50:45 +110049 constants.IMAGE_TYPE_HPS_FIRMWARE,
Vincent Palatind599c662015-10-26 09:51:41 -070050 constants.IMAGE_TYPE_ACCESSORY_RWSIG,
Amey Deshpandea936c622015-08-12 17:27:54 -070051 constants.IMAGE_TYPE_BASE,
Vadim Bendeburyfe37f282020-11-04 19:05:49 -080052 constants.IMAGE_TYPE_GSC_FIRMWARE,
Amey Deshpandea936c622015-08-12 17:27:54 -070053)
54
Mike Frysingerd13faeb2013-09-05 16:00:46 -040055
Mike Frysinger4495b032014-03-05 17:24:03 -050056class PushError(Exception):
57 """When an (unknown) error happened while trying to push artifacts."""
58
59
Mike Frysingerd13faeb2013-09-05 16:00:46 -040060class MissingBoardInstructions(Exception):
61 """Raised when a board lacks any signer instructions."""
62
Mike Frysingerd84d91e2015-11-05 18:02:24 -050063 def __init__(self, board, image_type, input_insns):
64 Exception.__init__(self, 'Board %s lacks insns for %s image: %s not found' %
65 (board, image_type, input_insns))
66
Mike Frysingerd13faeb2013-09-05 16:00:46 -040067
68class InputInsns(object):
69 """Object to hold settings for a signable board.
70
71 Note: The format of the instruction file pushimage outputs (and the signer
72 reads) is not exactly the same as the instruction file pushimage reads.
73 """
74
Don Garrett3cf5f9a2018-08-14 13:14:47 -070075 def __init__(self, board, image_type=None, buildroot=None):
Mike Frysingerd84d91e2015-11-05 18:02:24 -050076 """Initialization.
77
78 Args:
79 board: The board to look up details.
80 image_type: The type of image we will be signing (see --sign-types).
Don Garrett3cf5f9a2018-08-14 13:14:47 -070081 buildroot: Buildroot in which to look for signing instructions.
Mike Frysingerd84d91e2015-11-05 18:02:24 -050082 """
Mike Frysingerd13faeb2013-09-05 16:00:46 -040083 self.board = board
Don Garrett3cf5f9a2018-08-14 13:14:47 -070084 self.buildroot = buildroot or constants.SOURCE_ROOT
Mike Frysingerd13faeb2013-09-05 16:00:46 -040085
Mike Frysingerb43142e2019-08-27 17:50:44 -040086 config = configparser.ConfigParser()
Mike Frysingerd7c93092019-10-14 00:12:50 -040087 with open(self.GetInsnFile('DEFAULT')) as fp:
Mike Frysingerb6ce0222020-05-09 00:50:06 -040088 config.read_file(fp)
Mike Frysingerd84d91e2015-11-05 18:02:24 -050089
Amey Deshpandea936c622015-08-12 17:27:54 -070090 # What pushimage internally refers to as 'recovery', are the basic signing
91 # instructions in practice, and other types are stacked on top.
Mike Frysingerd84d91e2015-11-05 18:02:24 -050092 if image_type is None:
93 image_type = constants.IMAGE_TYPE_RECOVERY
94 self.image_type = image_type
Amey Deshpandea936c622015-08-12 17:27:54 -070095 input_insns = self.GetInsnFile(constants.IMAGE_TYPE_RECOVERY)
96 if not os.path.exists(input_insns):
97 # This board doesn't have any signing instructions.
Mike Frysingerd84d91e2015-11-05 18:02:24 -050098 raise MissingBoardInstructions(self.board, image_type, input_insns)
Mike Frysingerd7c93092019-10-14 00:12:50 -040099 with open(input_insns) as fp:
Mike Frysingerb6ce0222020-05-09 00:50:06 -0400100 config.read_file(fp)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500101
102 if image_type is not None:
103 input_insns = self.GetInsnFile(image_type)
104 if not os.path.exists(input_insns):
105 # This type doesn't have any signing instructions.
106 raise MissingBoardInstructions(self.board, image_type, input_insns)
107
108 self.image_type = image_type
Mike Frysingerd7c93092019-10-14 00:12:50 -0400109 with open(input_insns) as fp:
Mike Frysingerb6ce0222020-05-09 00:50:06 -0400110 config.read_file(fp)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500111
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400112 self.cfg = config
113
114 def GetInsnFile(self, image_type):
115 """Find the signer instruction files for this board/image type.
116
117 Args:
118 image_type: The type of instructions to load. It can be a common file
119 (like "DEFAULT"), or one of the --sign-types.
120
121 Returns:
122 Full path to the instruction file using |image_type| and |self.board|.
123 """
124 if image_type == image_type.upper():
125 name = image_type
Amey Deshpandea936c622015-08-12 17:27:54 -0700126 elif image_type in (constants.IMAGE_TYPE_RECOVERY,
127 constants.IMAGE_TYPE_BASE):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400128 name = self.board
129 else:
130 name = '%s.%s' % (self.board, image_type)
131
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700132 return os.path.join(
133 self.buildroot, signing.INPUT_INSN_DIR_REL, '%s.instructions' % name)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400134
135 @staticmethod
136 def SplitCfgField(val):
137 """Split a string into multiple elements.
138
139 This centralizes our convention for multiple elements in the input files
140 being delimited by either a space or comma.
141
142 Args:
143 val: The string to split.
144
145 Returns:
146 The list of elements from having done split the string.
147 """
148 return val.replace(',', ' ').split()
149
150 def GetChannels(self):
151 """Return the list of channels to sign for this board.
152
153 If the board-specific config doesn't specify a preference, we'll use the
154 common settings.
155 """
156 return self.SplitCfgField(self.cfg.get('insns', 'channel'))
157
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500158 def GetKeysets(self, insns_merge=None):
159 """Return the list of keysets to sign for this board.
160
161 Args:
162 insns_merge: The additional section to look at over [insns].
163 """
164 # First load the default value from [insns.keyset] if available.
165 sections = ['insns']
166 # Then overlay the [insns.xxx.keyset] if requested.
167 if insns_merge is not None:
168 sections += [insns_merge]
169
170 keyset = ''
171 for section in sections:
172 try:
173 keyset = self.cfg.get(section, 'keyset')
Mike Frysingerb43142e2019-08-27 17:50:44 -0400174 except (configparser.NoSectionError, configparser.NoOptionError):
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500175 pass
176
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500177 # We do not perturb the order (e.g. using sorted() or making a set())
178 # because we want the behavior stable, and we want the input insns to
179 # explicitly control the order (since it has an impact on naming).
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500180 return self.SplitCfgField(keyset)
181
182 def GetAltInsnSets(self):
183 """Return the list of alternative insn sections."""
184 # We do not perturb the order (e.g. using sorted() or making a set())
185 # because we want the behavior stable, and we want the input insns to
186 # explicitly control the order (since it has an impact on naming).
187 ret = [x for x in self.cfg.sections() if x.startswith('insns.')]
188 return ret if ret else [None]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400189
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500190 @staticmethod
191 def CopyConfigParser(config):
192 """Return a copy of a ConfigParser object.
193
Thiemo Nagel9fb99722017-05-26 16:26:40 +0200194 The python folks broke the ability to use something like deepcopy:
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500195 https://bugs.python.org/issue16058
196 """
197 # Write the current config to a string io object.
Mike Frysingere852b072021-05-21 12:39:03 -0400198 data = io.StringIO()
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500199 config.write(data)
200 data.seek(0)
201
202 # Create a new ConfigParser from the serialized data.
Mike Frysingerb43142e2019-08-27 17:50:44 -0400203 ret = configparser.ConfigParser()
Mike Frysingerb6ce0222020-05-09 00:50:06 -0400204 ret.read_file(data)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500205
206 return ret
207
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500208 def OutputInsns(self, output_file, sect_insns, sect_general,
209 insns_merge=None):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400210 """Generate the output instruction file for sending to the signer.
211
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500212 The override order is (later has precedence):
213 [insns]
214 [insns_merge] (should be named "insns.xxx")
215 sect_insns
216
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400217 Note: The format of the instruction file pushimage outputs (and the signer
218 reads) is not exactly the same as the instruction file pushimage reads.
219
220 Args:
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400221 output_file: The file to write the new instruction file to.
222 sect_insns: Items to set/override in the [insns] section.
223 sect_general: Items to set/override in the [general] section.
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500224 insns_merge: The alternative insns.xxx section to merge.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400225 """
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500226 # Create a copy so we can clobber certain fields.
227 config = self.CopyConfigParser(self.cfg)
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500228 sect_insns = sect_insns.copy()
229
230 # Merge in the alternative insns section if need be.
231 if insns_merge is not None:
232 for k, v in config.items(insns_merge):
233 sect_insns.setdefault(k, v)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400234
235 # Clear channel entry in instructions file, ensuring we only get
236 # one channel for the signer to look at. Then provide all the
237 # other details for this signing request to avoid any ambiguity
238 # and to avoid relying on encoding data into filenames.
239 for sect, fields in zip(('insns', 'general'), (sect_insns, sect_general)):
240 if not config.has_section(sect):
241 config.add_section(sect)
Mike Frysinger0bdbc102019-06-13 15:27:29 -0400242 for k, v in fields.items():
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400243 config.set(sect, k, v)
244
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500245 # Now prune the alternative sections.
246 for alt in self.GetAltInsnSets():
247 config.remove_section(alt)
248
Mike Frysingere852b072021-05-21 12:39:03 -0400249 output = io.StringIO()
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400250 config.write(output)
251 data = output.getvalue()
252 osutils.WriteFile(output_file, data)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500253 logging.debug('generated insns file for %s:\n%s', self.image_type, data)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400254
255
256def MarkImageToBeSigned(ctx, tbs_base, insns_path, priority):
257 """Mark an instructions file for signing.
258
259 This will upload a file to the GS bucket flagging an image for signing by
260 the signers.
261
262 Args:
263 ctx: A viable gs.GSContext.
264 tbs_base: The full path to where the tobesigned directory lives.
265 insns_path: The path (relative to |tbs_base|) of the file to sign.
266 priority: Set the signing priority (lower == higher prio).
267
268 Returns:
269 The full path to the remote tobesigned file.
270 """
271 if priority < 0 or priority > 99:
272 raise ValueError('priority must be [0, 99] inclusive')
273
274 if insns_path.startswith(tbs_base):
275 insns_path = insns_path[len(tbs_base):].lstrip('/')
276
277 tbs_path = '%s/tobesigned/%02i,%s' % (tbs_base, priority,
278 insns_path.replace('/', ','))
279
Mike Frysinger6430d132014-10-27 23:43:30 -0400280 # The caller will catch gs.GSContextException for us.
281 ctx.Copy('-', tbs_path, input=cros_build_lib.MachineDetails())
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400282
283 return tbs_path
284
285
286def PushImage(src_path, board, versionrev=None, profile=None, priority=50,
Mike Frysinger77912102017-08-30 18:35:46 -0400287 sign_types=None, dry_run=False, mock=False, force_keysets=(),
Jack Neus485a9d22020-12-21 03:15:15 +0000288 force_channels=None, buildroot=constants.SOURCE_ROOT,
289 dest_bucket=constants.RELEASE_BUCKET):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400290 """Push the image from the archive bucket to the release bucket.
291
292 Args:
293 src_path: Where to copy the files from; can be a local path or gs:// URL.
294 Should be a full path to the artifacts in either case.
295 board: The board we're uploading artifacts for (e.g. $BOARD).
296 versionrev: The full Chromium OS version string (e.g. R34-5126.0.0).
297 profile: The board profile in use (e.g. "asan").
298 priority: Set the signing priority (lower == higher prio).
299 sign_types: If set, a set of types which we'll restrict ourselves to
300 signing. See the --sign-types option for more details.
301 dry_run: Show what would be done, but do not upload anything.
302 mock: Upload to a testing bucket rather than the real one.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500303 force_keysets: Set of keysets to use rather than what the inputs say.
Mike Frysinger77912102017-08-30 18:35:46 -0400304 force_channels: Set of channels to use rather than what the inputs say.
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700305 buildroot: Buildroot in which to look for signing instructions.
Jack Neus485a9d22020-12-21 03:15:15 +0000306 dest_bucket: Bucket to push results to.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400307
308 Returns:
Don Garrett9459c2f2014-01-22 18:20:24 -0800309 A dictionary that maps 'channel' -> ['gs://signer_instruction_uri1',
310 'gs://signer_instruction_uri2',
311 ...]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400312 """
Mike Frysinger4495b032014-03-05 17:24:03 -0500313 # Whether we hit an unknown error. If so, we'll throw an error, but only
314 # at the end (so that we still upload as many files as possible).
Amey Deshpandea936c622015-08-12 17:27:54 -0700315 # It's implemented using a list to deal with variable scopes in nested
316 # functions below.
317 unknown_error = [False]
Mike Frysinger4495b032014-03-05 17:24:03 -0500318
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400319 if versionrev is None:
320 # Extract milestone/version from the directory name.
321 versionrev = os.path.basename(src_path)
322
323 # We only support the latest format here. Older releases can use pushimage
324 # from the respective branch which deals with legacy cruft.
325 m = re.match(VERSION_REGEX, versionrev)
326 if not m:
327 raise ValueError('version %s does not match %s' %
328 (versionrev, VERSION_REGEX))
329 milestone = m.group(1)
330 version = m.group(2)
331
332 # Normalize board to always use dashes not underscores. This is mostly a
333 # historical artifact at this point, but we can't really break it since the
334 # value is used in URLs.
335 boardpath = board.replace('_', '-')
336 if profile is not None:
337 boardpath += '-%s' % profile.replace('_', '-')
338
339 ctx = gs.GSContext(dry_run=dry_run)
340
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400341 try:
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700342 input_insns = InputInsns(board, buildroot=buildroot)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400343 except MissingBoardInstructions as e:
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500344 logging.warning('Missing base instruction file: %s', e)
Ralph Nathan446aee92015-03-23 14:44:56 -0700345 logging.warning('not uploading anything for signing')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400346 return
Mike Frysinger77912102017-08-30 18:35:46 -0400347
348 if force_channels is None:
349 channels = input_insns.GetChannels()
350 else:
351 # Filter out duplicates.
352 channels = sorted(set(force_channels))
Mike Frysingerdad40d62014-02-09 02:18:02 -0500353
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500354 # We want force_keysets as a set.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500355 force_keysets = set(force_keysets)
Mike Frysingerdad40d62014-02-09 02:18:02 -0500356
357 if mock:
Ralph Nathan03047282015-03-23 11:09:32 -0700358 logging.info('Upload mode: mock; signers will not process anything')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500359 tbs_base = gs_base = os.path.join(constants.TRASH_BUCKET, 'pushimage-tests',
360 getpass.getuser())
David Rileyf8205122015-09-04 13:46:36 -0700361 elif set(['%s-%s' % (TEST_KEYSET_PREFIX, x)
362 for x in TEST_KEYSETS]) & force_keysets:
Ralph Nathan03047282015-03-23 11:09:32 -0700363 logging.info('Upload mode: test; signers will process test keys')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500364 # We need the tbs_base to be in the place the signer will actually scan.
365 tbs_base = TEST_SIGN_BUCKET_BASE
366 gs_base = os.path.join(tbs_base, getpass.getuser())
367 else:
Ralph Nathan03047282015-03-23 11:09:32 -0700368 logging.info('Upload mode: normal; signers will process the images')
Jack Neus485a9d22020-12-21 03:15:15 +0000369 tbs_base = gs_base = dest_bucket
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400370
371 sect_general = {
372 'config_board': board,
373 'board': boardpath,
374 'version': version,
375 'versionrev': versionrev,
376 'milestone': milestone,
377 }
378 sect_insns = {}
379
380 if dry_run:
Ralph Nathan03047282015-03-23 11:09:32 -0700381 logging.info('DRY RUN MODE ACTIVE: NOTHING WILL BE UPLOADED')
382 logging.info('Signing for channels: %s', ' '.join(channels))
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400383
Don Garrett9459c2f2014-01-22 18:20:24 -0800384 instruction_urls = {}
385
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400386 def _ImageNameBase(image_type=None):
387 lmid = ('%s-' % image_type) if image_type else ''
388 return 'ChromeOS-%s%s-%s' % (lmid, versionrev, boardpath)
389
Amey Deshpandea936c622015-08-12 17:27:54 -0700390 # These variables are defined outside the loop so that the nested functions
391 # below can access them without 'cell-var-from-loop' linter warning.
Mike Frysinger80de5012019-08-01 14:10:53 -0400392 dst_path = ''
Amey Deshpandea936c622015-08-12 17:27:54 -0700393 files_to_sign = []
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400394 for channel in channels:
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700395 logging.debug('\n\n#### CHANNEL: %s ####\n', channel)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400396 sect_insns['channel'] = channel
397 sub_path = '%s-channel/%s/%s' % (channel, boardpath, version)
398 dst_path = '%s/%s' % (gs_base, sub_path)
Ralph Nathan03047282015-03-23 11:09:32 -0700399 logging.info('Copying images to %s', dst_path)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400400
Amey Deshpandea936c622015-08-12 17:27:54 -0700401 recovery_basename = _ImageNameBase(constants.IMAGE_TYPE_RECOVERY)
402 factory_basename = _ImageNameBase(constants.IMAGE_TYPE_FACTORY)
403 firmware_basename = _ImageNameBase(constants.IMAGE_TYPE_FIRMWARE)
Evan Benn4d061102022-02-14 12:50:45 +1100404 hps_firmware_basename = _ImageNameBase(constants.IMAGE_TYPE_HPS_FIRMWARE)
Vincent Palatind599c662015-10-26 09:51:41 -0700405 acc_usbpd_basename = _ImageNameBase(constants.IMAGE_TYPE_ACCESSORY_USBPD)
406 acc_rwsig_basename = _ImageNameBase(constants.IMAGE_TYPE_ACCESSORY_RWSIG)
Vadim Bendeburyfe37f282020-11-04 19:05:49 -0800407 gsc_firmware_basename = _ImageNameBase(constants.IMAGE_TYPE_GSC_FIRMWARE)
Amey Deshpandea936c622015-08-12 17:27:54 -0700408 test_basename = _ImageNameBase(constants.IMAGE_TYPE_TEST)
409 base_basename = _ImageNameBase(constants.IMAGE_TYPE_BASE)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400410 hwqual_tarball = 'chromeos-hwqual-%s-%s.tar.bz2' % (board, versionrev)
411
Amey Deshpandea936c622015-08-12 17:27:54 -0700412 # The following build artifacts, if present, are always copied regardless of
413 # requested signing types.
414 files_to_copy_only = (
415 # (<src>, <dst>, <suffix>),
416 ('image.zip', _ImageNameBase(), 'zip'),
417 (constants.TEST_IMAGE_TAR, test_basename, 'tar.xz'),
418 ('debug.tgz', 'debug-%s' % boardpath, 'tgz'),
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800419 (hwqual_tarball, None, None),
420 ('stateful.tgz', None, None),
421 ('dlc', None, None),
Amin Hassani21e0ed12019-11-04 14:24:36 -0800422 (constants.QUICK_PROVISION_PAYLOAD_KERNEL, None, None),
423 (constants.QUICK_PROVISION_PAYLOAD_ROOTFS, None, None),
Jae Hoon Kim2ed1f0b2021-10-06 10:54:48 -0700424 (constants.QUICK_PROVISION_PAYLOAD_MINIOS, None, None),
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400425 )
Amey Deshpandea936c622015-08-12 17:27:54 -0700426
427 # The following build artifacts, if present, are always copied.
428 # If |sign_types| is None, all of them are marked for signing, otherwise
429 # only the image types specified in |sign_types| are marked for signing.
430 files_to_copy_and_maybe_sign = (
431 # (<src>, <dst>, <suffix>, <signing type>),
432 (constants.RECOVERY_IMAGE_TAR, recovery_basename, 'tar.xz',
433 constants.IMAGE_TYPE_RECOVERY),
434
435 ('factory_image.zip', factory_basename, 'zip',
436 constants.IMAGE_TYPE_FACTORY),
437
438 ('firmware_from_source.tar.bz2', firmware_basename, 'tar.bz2',
439 constants.IMAGE_TYPE_FIRMWARE),
David Rileya04d19d2015-09-04 16:11:50 -0700440
Evan Benn4d061102022-02-14 12:50:45 +1100441 ('firmware_from_source.tar.bz2', hps_firmware_basename, 'tar.bz2',
442 constants.IMAGE_TYPE_HPS_FIRMWARE),
443
Vincent Palatind599c662015-10-26 09:51:41 -0700444 ('firmware_from_source.tar.bz2', acc_usbpd_basename, 'tar.bz2',
445 constants.IMAGE_TYPE_ACCESSORY_USBPD),
446
447 ('firmware_from_source.tar.bz2', acc_rwsig_basename, 'tar.bz2',
448 constants.IMAGE_TYPE_ACCESSORY_RWSIG),
LaMont Jones7d6c98f2019-09-27 12:37:33 -0600449
Vadim Bendeburyfe37f282020-11-04 19:05:49 -0800450 ('firmware_from_source.tar.bz2', gsc_firmware_basename, 'tar.bz2',
451 constants.IMAGE_TYPE_GSC_FIRMWARE),
Amey Deshpandea936c622015-08-12 17:27:54 -0700452 )
453
454 # The following build artifacts are copied and marked for signing, if
455 # they are present *and* if the image type is specified via |sign_types|.
456 files_to_maybe_copy_and_sign = (
457 # (<src>, <dst>, <suffix>, <signing type>),
458 (constants.BASE_IMAGE_TAR, base_basename, 'tar.xz',
459 constants.IMAGE_TYPE_BASE),
460 )
461
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800462 def _CopyFileToGS(src, dst=None, suffix=None):
Amey Deshpandea936c622015-08-12 17:27:54 -0700463 """Returns |dst| file name if the copying was successful."""
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800464 if dst is None:
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400465 dst = src
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800466 elif suffix is not None:
Amey Deshpandea936c622015-08-12 17:27:54 -0700467 dst = '%s.%s' % (dst, suffix)
468 success = False
Mike Frysingere51a2652014-01-18 02:36:16 -0500469 try:
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800470 ctx.Copy(os.path.join(src_path, src), os.path.join(dst_path, dst),
471 recursive=True)
Amey Deshpandea936c622015-08-12 17:27:54 -0700472 success = True
Mike Frysingere51a2652014-01-18 02:36:16 -0500473 except gs.GSNoSuchKey:
Ralph Nathan446aee92015-03-23 14:44:56 -0700474 logging.warning('Skipping %s as it does not exist', src)
Mike Frysinger4495b032014-03-05 17:24:03 -0500475 except gs.GSContextException:
Amey Deshpandea936c622015-08-12 17:27:54 -0700476 unknown_error[0] = True
Ralph Nathan59900422015-03-24 10:41:17 -0700477 logging.error('Skipping %s due to unknown GS error', src, exc_info=True)
Amey Deshpandea936c622015-08-12 17:27:54 -0700478 return dst if success else None
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400479
Amey Deshpandea936c622015-08-12 17:27:54 -0700480 for src, dst, suffix in files_to_copy_only:
481 _CopyFileToGS(src, dst, suffix)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400482
Amey Deshpandea936c622015-08-12 17:27:54 -0700483 # Clear the list of files to sign before adding new artifacts.
484 files_to_sign = []
485
486 def _AddToFilesToSign(image_type, dst, suffix):
487 assert dst.endswith('.' + suffix), (
488 'dst: %s, suffix: %s' % (dst, suffix))
489 dst_base = dst[:-(len(suffix) + 1)]
490 files_to_sign.append([image_type, dst_base, suffix])
491
492 for src, dst, suffix, image_type in files_to_copy_and_maybe_sign:
493 dst = _CopyFileToGS(src, dst, suffix)
494 if dst and (not sign_types or image_type in sign_types):
495 _AddToFilesToSign(image_type, dst, suffix)
496
497 for src, dst, suffix, image_type in files_to_maybe_copy_and_sign:
498 if sign_types and image_type in sign_types:
499 dst = _CopyFileToGS(src, dst, suffix)
500 if dst:
501 _AddToFilesToSign(image_type, dst, suffix)
502
503 logging.debug('Files to sign: %s', files_to_sign)
Evan Bennb9dfaf42022-02-14 17:38:26 +1100504 unused_sign_types = set(sign_types or []) - set(
505 x for x, _, _ in files_to_sign)
506 if unused_sign_types:
507 logging.warning('Some sign types were unused: %s',
508 ' '.join(unused_sign_types))
509
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400510 # Now go through the subset for signing.
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500511 for image_type, dst_name, suffix in files_to_sign:
512 try:
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700513 input_insns = InputInsns(board, image_type=image_type,
514 buildroot=buildroot)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500515 except MissingBoardInstructions as e:
516 logging.info('Nothing to sign: %s', e)
517 continue
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400518
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500519 dst_archive = '%s.%s' % (dst_name, suffix)
520 sect_general['archive'] = dst_archive
521 sect_general['type'] = image_type
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400522
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500523 # In the default/automatic mode, only flag files for signing if the
524 # archives were actually uploaded in a previous stage. This additional
525 # check can be removed in future once |sign_types| becomes a required
526 # argument.
527 # TODO: Make |sign_types| a required argument.
528 gs_artifact_path = os.path.join(dst_path, dst_archive)
529 exists = False
530 try:
531 exists = ctx.Exists(gs_artifact_path)
532 except gs.GSContextException:
533 unknown_error[0] = True
534 logging.error('Unknown error while checking %s', gs_artifact_path,
535 exc_info=True)
536 if not exists:
537 logging.info('%s does not exist. Nothing to sign.',
538 gs_artifact_path)
539 continue
540
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500541 first_image = True
542 for alt_insn_set in input_insns.GetAltInsnSets():
543 # Figure out which keysets have been requested for this type.
544 # We sort the forced set so tests/runtime behavior is stable.
545 keysets = sorted(force_keysets)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500546 if not keysets:
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500547 keysets = input_insns.GetKeysets(insns_merge=alt_insn_set)
548 if not keysets:
549 logging.warning('Skipping %s image signing due to no keysets',
550 image_type)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500551
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500552 for keyset in keysets:
553 sect_insns['keyset'] = keyset
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400554
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500555 # Generate the insn file for this artifact that the signer will use,
556 # and flag it for signing.
Mike Frysinger59babdb2019-09-06 06:25:50 -0400557 with cros_build_lib.UnbufferedNamedTemporaryFile(
558 prefix='pushimage.insns.') as insns_path:
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500559 input_insns.OutputInsns(insns_path.name, sect_insns, sect_general,
560 insns_merge=alt_insn_set)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400561
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500562 gs_insns_path = '%s/%s' % (dst_path, dst_name)
563 if not first_image:
564 gs_insns_path += '-%s' % keyset
565 first_image = False
566 gs_insns_path += '.instructions'
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400567
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500568 try:
569 ctx.Copy(insns_path.name, gs_insns_path)
570 except gs.GSContextException:
571 unknown_error[0] = True
572 logging.error('Unknown error while uploading insns %s',
573 gs_insns_path, exc_info=True)
574 continue
Mike Frysinger4495b032014-03-05 17:24:03 -0500575
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500576 try:
577 MarkImageToBeSigned(ctx, tbs_base, gs_insns_path, priority)
578 except gs.GSContextException:
579 unknown_error[0] = True
580 logging.error('Unknown error while marking for signing %s',
581 gs_insns_path, exc_info=True)
582 continue
583 logging.info('Signing %s image with keyset %s at %s', image_type,
584 keyset, gs_insns_path)
585 instruction_urls.setdefault(channel, []).append(gs_insns_path)
Don Garrett9459c2f2014-01-22 18:20:24 -0800586
Amey Deshpandea936c622015-08-12 17:27:54 -0700587 if unknown_error[0]:
Mike Frysinger4495b032014-03-05 17:24:03 -0500588 raise PushError('hit some unknown error(s)', instruction_urls)
589
Don Garrett9459c2f2014-01-22 18:20:24 -0800590 return instruction_urls
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400591
592
Mike Frysinger26144192017-08-30 18:26:46 -0400593def GetParser():
594 """Creates the argparse parser."""
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400595 parser = commandline.ArgumentParser(description=__doc__)
596
597 # The type of image_dir will strip off trailing slashes (makes later
598 # processing simpler and the display prettier).
599 parser.add_argument('image_dir', default=None, type='local_or_gs_path',
600 help='full path of source artifacts to upload')
601 parser.add_argument('--board', default=None, required=True,
602 help='board to generate symbols for')
603 parser.add_argument('--profile', default=None,
604 help='board profile in use (e.g. "asan")')
605 parser.add_argument('--version', default=None,
606 help='version info (normally extracted from image_dir)')
Mike Frysinger77912102017-08-30 18:35:46 -0400607 parser.add_argument('--channels', default=None, action='split_extend',
608 help='override list of channels to process')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400609 parser.add_argument('-n', '--dry-run', default=False, action='store_true',
610 help='show what would be done, but do not upload')
611 parser.add_argument('-M', '--mock', default=False, action='store_true',
612 help='upload things to a testing bucket (dev testing)')
David Rileyf8205122015-09-04 13:46:36 -0700613 parser.add_argument('--test-sign', default=[], action='append',
614 choices=TEST_KEYSETS,
615 help='mung signing behavior to sign w/ test keys')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400616 parser.add_argument('--priority', type=int, default=50,
617 help='set signing priority (lower == higher prio)')
618 parser.add_argument('--sign-types', default=None, nargs='+',
Amey Deshpandea936c622015-08-12 17:27:54 -0700619 choices=_SUPPORTED_IMAGE_TYPES,
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400620 help='only sign specified image types')
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700621 parser.add_argument('--buildroot', default=constants.SOURCE_ROOT, type='path',
622 help='Buildroot to use. Defaults to current.')
Mike Frysinger09fe0122014-02-09 02:44:05 -0500623 parser.add_argument('--yes', action='store_true', default=False,
624 help='answer yes to all prompts')
Jack Neus485a9d22020-12-21 03:15:15 +0000625 parser.add_argument('--dest-bucket', default=constants.RELEASE_BUCKET,
626 help='dest bucket. Default to %(default)s')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400627
Mike Frysinger26144192017-08-30 18:26:46 -0400628 return parser
629
630
631def main(argv):
632 parser = GetParser()
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400633 opts = parser.parse_args(argv)
634 opts.Freeze()
635
David Rileyf8205122015-09-04 13:46:36 -0700636 force_keysets = set(['%s-%s' % (TEST_KEYSET_PREFIX, x)
637 for x in opts.test_sign])
Mike Frysingerdad40d62014-02-09 02:18:02 -0500638
Mike Frysinger09fe0122014-02-09 02:44:05 -0500639 # If we aren't using mock or test or dry run mode, then let's prompt the user
640 # to make sure they actually want to do this. It's rare that people want to
641 # run this directly and hit the release bucket.
642 if not (opts.mock or force_keysets or opts.dry_run) and not opts.yes:
643 prolog = '\n'.join(textwrap.wrap(textwrap.dedent(
644 'Uploading images for signing to the *release* bucket is not something '
645 'you generally should be doing yourself.'), 80)).strip()
646 if not cros_build_lib.BooleanPrompt(
647 prompt='Are you sure you want to sign these images',
648 default=False, prolog=prolog):
649 cros_build_lib.Die('better safe than sorry')
650
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400651 PushImage(opts.image_dir, opts.board, versionrev=opts.version,
652 profile=opts.profile, priority=opts.priority,
Mike Frysingerdad40d62014-02-09 02:18:02 -0500653 sign_types=opts.sign_types, dry_run=opts.dry_run, mock=opts.mock,
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700654 force_keysets=force_keysets, force_channels=opts.channels,
Jack Neus485a9d22020-12-21 03:15:15 +0000655 buildroot=opts.buildroot, dest_bucket=opts.dest_bucket)