blob: 8fd43beeb008203f049e00797cd960bbeed2b00d [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
Mike Frysingerd13faeb2013-09-05 16:00:46 -040014import os
15import re
Mike Frysinger09fe0122014-02-09 02:44:05 -050016import textwrap
Mike Frysingerd13faeb2013-09-05 16:00:46 -040017
Aviv Keshetb7519e12016-10-04 00:50:00 -070018from chromite.lib import constants
Mike Frysingerd13faeb2013-09-05 16:00:46 -040019from chromite.lib import commandline
20from chromite.lib import cros_build_lib
Ralph Nathan5a582ff2015-03-20 18:18:30 -070021from chromite.lib import cros_logging as logging
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,
49 constants.IMAGE_TYPE_ACCESSORY_RWSIG,
Amey Deshpandea936c622015-08-12 17:27:54 -070050 constants.IMAGE_TYPE_BASE,
Vadim Bendeburyfe37f282020-11-04 19:05:49 -080051 constants.IMAGE_TYPE_GSC_FIRMWARE,
Amey Deshpandea936c622015-08-12 17:27:54 -070052)
53
Mike Frysingerd13faeb2013-09-05 16:00:46 -040054
Mike Frysinger4495b032014-03-05 17:24:03 -050055class PushError(Exception):
56 """When an (unknown) error happened while trying to push artifacts."""
57
58
Mike Frysingerd13faeb2013-09-05 16:00:46 -040059class MissingBoardInstructions(Exception):
60 """Raised when a board lacks any signer instructions."""
61
Mike Frysingerd84d91e2015-11-05 18:02:24 -050062 def __init__(self, board, image_type, input_insns):
63 Exception.__init__(self, 'Board %s lacks insns for %s image: %s not found' %
64 (board, image_type, input_insns))
65
Mike Frysingerd13faeb2013-09-05 16:00:46 -040066
67class InputInsns(object):
68 """Object to hold settings for a signable board.
69
70 Note: The format of the instruction file pushimage outputs (and the signer
71 reads) is not exactly the same as the instruction file pushimage reads.
72 """
73
Don Garrett3cf5f9a2018-08-14 13:14:47 -070074 def __init__(self, board, image_type=None, buildroot=None):
Mike Frysingerd84d91e2015-11-05 18:02:24 -050075 """Initialization.
76
77 Args:
78 board: The board to look up details.
79 image_type: The type of image we will be signing (see --sign-types).
Don Garrett3cf5f9a2018-08-14 13:14:47 -070080 buildroot: Buildroot in which to look for signing instructions.
Mike Frysingerd84d91e2015-11-05 18:02:24 -050081 """
Mike Frysingerd13faeb2013-09-05 16:00:46 -040082 self.board = board
Don Garrett3cf5f9a2018-08-14 13:14:47 -070083 self.buildroot = buildroot or constants.SOURCE_ROOT
Mike Frysingerd13faeb2013-09-05 16:00:46 -040084
Mike Frysingerb43142e2019-08-27 17:50:44 -040085 config = configparser.ConfigParser()
Mike Frysingerd7c93092019-10-14 00:12:50 -040086 with open(self.GetInsnFile('DEFAULT')) as fp:
Mike Frysingerb6ce0222020-05-09 00:50:06 -040087 config.read_file(fp)
Mike Frysingerd84d91e2015-11-05 18:02:24 -050088
Amey Deshpandea936c622015-08-12 17:27:54 -070089 # What pushimage internally refers to as 'recovery', are the basic signing
90 # instructions in practice, and other types are stacked on top.
Mike Frysingerd84d91e2015-11-05 18:02:24 -050091 if image_type is None:
92 image_type = constants.IMAGE_TYPE_RECOVERY
93 self.image_type = image_type
Amey Deshpandea936c622015-08-12 17:27:54 -070094 input_insns = self.GetInsnFile(constants.IMAGE_TYPE_RECOVERY)
95 if not os.path.exists(input_insns):
96 # This board doesn't have any signing instructions.
Mike Frysingerd84d91e2015-11-05 18:02:24 -050097 raise MissingBoardInstructions(self.board, image_type, input_insns)
Mike Frysingerd7c93092019-10-14 00:12:50 -040098 with open(input_insns) as fp:
Mike Frysingerb6ce0222020-05-09 00:50:06 -040099 config.read_file(fp)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500100
101 if image_type is not None:
102 input_insns = self.GetInsnFile(image_type)
103 if not os.path.exists(input_insns):
104 # This type doesn't have any signing instructions.
105 raise MissingBoardInstructions(self.board, image_type, input_insns)
106
107 self.image_type = image_type
Mike Frysingerd7c93092019-10-14 00:12:50 -0400108 with open(input_insns) as fp:
Mike Frysingerb6ce0222020-05-09 00:50:06 -0400109 config.read_file(fp)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500110
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400111 self.cfg = config
112
113 def GetInsnFile(self, image_type):
114 """Find the signer instruction files for this board/image type.
115
116 Args:
117 image_type: The type of instructions to load. It can be a common file
118 (like "DEFAULT"), or one of the --sign-types.
119
120 Returns:
121 Full path to the instruction file using |image_type| and |self.board|.
122 """
123 if image_type == image_type.upper():
124 name = image_type
Amey Deshpandea936c622015-08-12 17:27:54 -0700125 elif image_type in (constants.IMAGE_TYPE_RECOVERY,
126 constants.IMAGE_TYPE_BASE):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400127 name = self.board
128 else:
129 name = '%s.%s' % (self.board, image_type)
130
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700131 return os.path.join(
132 self.buildroot, signing.INPUT_INSN_DIR_REL, '%s.instructions' % name)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400133
134 @staticmethod
135 def SplitCfgField(val):
136 """Split a string into multiple elements.
137
138 This centralizes our convention for multiple elements in the input files
139 being delimited by either a space or comma.
140
141 Args:
142 val: The string to split.
143
144 Returns:
145 The list of elements from having done split the string.
146 """
147 return val.replace(',', ' ').split()
148
149 def GetChannels(self):
150 """Return the list of channels to sign for this board.
151
152 If the board-specific config doesn't specify a preference, we'll use the
153 common settings.
154 """
155 return self.SplitCfgField(self.cfg.get('insns', 'channel'))
156
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500157 def GetKeysets(self, insns_merge=None):
158 """Return the list of keysets to sign for this board.
159
160 Args:
161 insns_merge: The additional section to look at over [insns].
162 """
163 # First load the default value from [insns.keyset] if available.
164 sections = ['insns']
165 # Then overlay the [insns.xxx.keyset] if requested.
166 if insns_merge is not None:
167 sections += [insns_merge]
168
169 keyset = ''
170 for section in sections:
171 try:
172 keyset = self.cfg.get(section, 'keyset')
Mike Frysingerb43142e2019-08-27 17:50:44 -0400173 except (configparser.NoSectionError, configparser.NoOptionError):
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500174 pass
175
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500176 # We do not perturb the order (e.g. using sorted() or making a set())
177 # because we want the behavior stable, and we want the input insns to
178 # explicitly control the order (since it has an impact on naming).
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500179 return self.SplitCfgField(keyset)
180
181 def GetAltInsnSets(self):
182 """Return the list of alternative insn sections."""
183 # We do not perturb the order (e.g. using sorted() or making a set())
184 # because we want the behavior stable, and we want the input insns to
185 # explicitly control the order (since it has an impact on naming).
186 ret = [x for x in self.cfg.sections() if x.startswith('insns.')]
187 return ret if ret else [None]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400188
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500189 @staticmethod
190 def CopyConfigParser(config):
191 """Return a copy of a ConfigParser object.
192
Thiemo Nagel9fb99722017-05-26 16:26:40 +0200193 The python folks broke the ability to use something like deepcopy:
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500194 https://bugs.python.org/issue16058
195 """
196 # Write the current config to a string io object.
Mike Frysingere852b072021-05-21 12:39:03 -0400197 data = io.StringIO()
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500198 config.write(data)
199 data.seek(0)
200
201 # Create a new ConfigParser from the serialized data.
Mike Frysingerb43142e2019-08-27 17:50:44 -0400202 ret = configparser.ConfigParser()
Mike Frysingerb6ce0222020-05-09 00:50:06 -0400203 ret.read_file(data)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500204
205 return ret
206
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500207 def OutputInsns(self, output_file, sect_insns, sect_general,
208 insns_merge=None):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400209 """Generate the output instruction file for sending to the signer.
210
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500211 The override order is (later has precedence):
212 [insns]
213 [insns_merge] (should be named "insns.xxx")
214 sect_insns
215
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400216 Note: The format of the instruction file pushimage outputs (and the signer
217 reads) is not exactly the same as the instruction file pushimage reads.
218
219 Args:
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400220 output_file: The file to write the new instruction file to.
221 sect_insns: Items to set/override in the [insns] section.
222 sect_general: Items to set/override in the [general] section.
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500223 insns_merge: The alternative insns.xxx section to merge.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400224 """
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500225 # Create a copy so we can clobber certain fields.
226 config = self.CopyConfigParser(self.cfg)
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500227 sect_insns = sect_insns.copy()
228
229 # Merge in the alternative insns section if need be.
230 if insns_merge is not None:
231 for k, v in config.items(insns_merge):
232 sect_insns.setdefault(k, v)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400233
234 # Clear channel entry in instructions file, ensuring we only get
235 # one channel for the signer to look at. Then provide all the
236 # other details for this signing request to avoid any ambiguity
237 # and to avoid relying on encoding data into filenames.
238 for sect, fields in zip(('insns', 'general'), (sect_insns, sect_general)):
239 if not config.has_section(sect):
240 config.add_section(sect)
Mike Frysinger0bdbc102019-06-13 15:27:29 -0400241 for k, v in fields.items():
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400242 config.set(sect, k, v)
243
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500244 # Now prune the alternative sections.
245 for alt in self.GetAltInsnSets():
246 config.remove_section(alt)
247
Mike Frysingere852b072021-05-21 12:39:03 -0400248 output = io.StringIO()
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400249 config.write(output)
250 data = output.getvalue()
251 osutils.WriteFile(output_file, data)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500252 logging.debug('generated insns file for %s:\n%s', self.image_type, data)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400253
254
255def MarkImageToBeSigned(ctx, tbs_base, insns_path, priority):
256 """Mark an instructions file for signing.
257
258 This will upload a file to the GS bucket flagging an image for signing by
259 the signers.
260
261 Args:
262 ctx: A viable gs.GSContext.
263 tbs_base: The full path to where the tobesigned directory lives.
264 insns_path: The path (relative to |tbs_base|) of the file to sign.
265 priority: Set the signing priority (lower == higher prio).
266
267 Returns:
268 The full path to the remote tobesigned file.
269 """
270 if priority < 0 or priority > 99:
271 raise ValueError('priority must be [0, 99] inclusive')
272
273 if insns_path.startswith(tbs_base):
274 insns_path = insns_path[len(tbs_base):].lstrip('/')
275
276 tbs_path = '%s/tobesigned/%02i,%s' % (tbs_base, priority,
277 insns_path.replace('/', ','))
278
Mike Frysinger6430d132014-10-27 23:43:30 -0400279 # The caller will catch gs.GSContextException for us.
280 ctx.Copy('-', tbs_path, input=cros_build_lib.MachineDetails())
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400281
282 return tbs_path
283
284
285def PushImage(src_path, board, versionrev=None, profile=None, priority=50,
Mike Frysinger77912102017-08-30 18:35:46 -0400286 sign_types=None, dry_run=False, mock=False, force_keysets=(),
Jack Neus485a9d22020-12-21 03:15:15 +0000287 force_channels=None, buildroot=constants.SOURCE_ROOT,
288 dest_bucket=constants.RELEASE_BUCKET):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400289 """Push the image from the archive bucket to the release bucket.
290
291 Args:
292 src_path: Where to copy the files from; can be a local path or gs:// URL.
293 Should be a full path to the artifacts in either case.
294 board: The board we're uploading artifacts for (e.g. $BOARD).
295 versionrev: The full Chromium OS version string (e.g. R34-5126.0.0).
296 profile: The board profile in use (e.g. "asan").
297 priority: Set the signing priority (lower == higher prio).
298 sign_types: If set, a set of types which we'll restrict ourselves to
299 signing. See the --sign-types option for more details.
300 dry_run: Show what would be done, but do not upload anything.
301 mock: Upload to a testing bucket rather than the real one.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500302 force_keysets: Set of keysets to use rather than what the inputs say.
Mike Frysinger77912102017-08-30 18:35:46 -0400303 force_channels: Set of channels to use rather than what the inputs say.
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700304 buildroot: Buildroot in which to look for signing instructions.
Jack Neus485a9d22020-12-21 03:15:15 +0000305 dest_bucket: Bucket to push results to.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400306
307 Returns:
Don Garrett9459c2f2014-01-22 18:20:24 -0800308 A dictionary that maps 'channel' -> ['gs://signer_instruction_uri1',
309 'gs://signer_instruction_uri2',
310 ...]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400311 """
Mike Frysinger4495b032014-03-05 17:24:03 -0500312 # Whether we hit an unknown error. If so, we'll throw an error, but only
313 # at the end (so that we still upload as many files as possible).
Amey Deshpandea936c622015-08-12 17:27:54 -0700314 # It's implemented using a list to deal with variable scopes in nested
315 # functions below.
316 unknown_error = [False]
Mike Frysinger4495b032014-03-05 17:24:03 -0500317
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400318 if versionrev is None:
319 # Extract milestone/version from the directory name.
320 versionrev = os.path.basename(src_path)
321
322 # We only support the latest format here. Older releases can use pushimage
323 # from the respective branch which deals with legacy cruft.
324 m = re.match(VERSION_REGEX, versionrev)
325 if not m:
326 raise ValueError('version %s does not match %s' %
327 (versionrev, VERSION_REGEX))
328 milestone = m.group(1)
329 version = m.group(2)
330
331 # Normalize board to always use dashes not underscores. This is mostly a
332 # historical artifact at this point, but we can't really break it since the
333 # value is used in URLs.
334 boardpath = board.replace('_', '-')
335 if profile is not None:
336 boardpath += '-%s' % profile.replace('_', '-')
337
338 ctx = gs.GSContext(dry_run=dry_run)
339
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400340 try:
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700341 input_insns = InputInsns(board, buildroot=buildroot)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400342 except MissingBoardInstructions as e:
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500343 logging.warning('Missing base instruction file: %s', e)
Ralph Nathan446aee92015-03-23 14:44:56 -0700344 logging.warning('not uploading anything for signing')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400345 return
Mike Frysinger77912102017-08-30 18:35:46 -0400346
347 if force_channels is None:
348 channels = input_insns.GetChannels()
349 else:
350 # Filter out duplicates.
351 channels = sorted(set(force_channels))
Mike Frysingerdad40d62014-02-09 02:18:02 -0500352
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500353 # We want force_keysets as a set.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500354 force_keysets = set(force_keysets)
Mike Frysingerdad40d62014-02-09 02:18:02 -0500355
356 if mock:
Ralph Nathan03047282015-03-23 11:09:32 -0700357 logging.info('Upload mode: mock; signers will not process anything')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500358 tbs_base = gs_base = os.path.join(constants.TRASH_BUCKET, 'pushimage-tests',
359 getpass.getuser())
David Rileyf8205122015-09-04 13:46:36 -0700360 elif set(['%s-%s' % (TEST_KEYSET_PREFIX, x)
361 for x in TEST_KEYSETS]) & force_keysets:
Ralph Nathan03047282015-03-23 11:09:32 -0700362 logging.info('Upload mode: test; signers will process test keys')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500363 # We need the tbs_base to be in the place the signer will actually scan.
364 tbs_base = TEST_SIGN_BUCKET_BASE
365 gs_base = os.path.join(tbs_base, getpass.getuser())
366 else:
Ralph Nathan03047282015-03-23 11:09:32 -0700367 logging.info('Upload mode: normal; signers will process the images')
Jack Neus485a9d22020-12-21 03:15:15 +0000368 tbs_base = gs_base = dest_bucket
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400369
370 sect_general = {
371 'config_board': board,
372 'board': boardpath,
373 'version': version,
374 'versionrev': versionrev,
375 'milestone': milestone,
376 }
377 sect_insns = {}
378
379 if dry_run:
Ralph Nathan03047282015-03-23 11:09:32 -0700380 logging.info('DRY RUN MODE ACTIVE: NOTHING WILL BE UPLOADED')
381 logging.info('Signing for channels: %s', ' '.join(channels))
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400382
Don Garrett9459c2f2014-01-22 18:20:24 -0800383 instruction_urls = {}
384
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400385 def _ImageNameBase(image_type=None):
386 lmid = ('%s-' % image_type) if image_type else ''
387 return 'ChromeOS-%s%s-%s' % (lmid, versionrev, boardpath)
388
Amey Deshpandea936c622015-08-12 17:27:54 -0700389 # These variables are defined outside the loop so that the nested functions
390 # below can access them without 'cell-var-from-loop' linter warning.
Mike Frysinger80de5012019-08-01 14:10:53 -0400391 dst_path = ''
Amey Deshpandea936c622015-08-12 17:27:54 -0700392 files_to_sign = []
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400393 for channel in channels:
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700394 logging.debug('\n\n#### CHANNEL: %s ####\n', channel)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400395 sect_insns['channel'] = channel
396 sub_path = '%s-channel/%s/%s' % (channel, boardpath, version)
397 dst_path = '%s/%s' % (gs_base, sub_path)
Ralph Nathan03047282015-03-23 11:09:32 -0700398 logging.info('Copying images to %s', dst_path)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400399
Amey Deshpandea936c622015-08-12 17:27:54 -0700400 recovery_basename = _ImageNameBase(constants.IMAGE_TYPE_RECOVERY)
401 factory_basename = _ImageNameBase(constants.IMAGE_TYPE_FACTORY)
402 firmware_basename = _ImageNameBase(constants.IMAGE_TYPE_FIRMWARE)
Vincent Palatind599c662015-10-26 09:51:41 -0700403 acc_usbpd_basename = _ImageNameBase(constants.IMAGE_TYPE_ACCESSORY_USBPD)
404 acc_rwsig_basename = _ImageNameBase(constants.IMAGE_TYPE_ACCESSORY_RWSIG)
Vadim Bendeburyfe37f282020-11-04 19:05:49 -0800405 gsc_firmware_basename = _ImageNameBase(constants.IMAGE_TYPE_GSC_FIRMWARE)
Amey Deshpandea936c622015-08-12 17:27:54 -0700406 test_basename = _ImageNameBase(constants.IMAGE_TYPE_TEST)
407 base_basename = _ImageNameBase(constants.IMAGE_TYPE_BASE)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400408 hwqual_tarball = 'chromeos-hwqual-%s-%s.tar.bz2' % (board, versionrev)
409
Amey Deshpandea936c622015-08-12 17:27:54 -0700410 # The following build artifacts, if present, are always copied regardless of
411 # requested signing types.
412 files_to_copy_only = (
413 # (<src>, <dst>, <suffix>),
414 ('image.zip', _ImageNameBase(), 'zip'),
415 (constants.TEST_IMAGE_TAR, test_basename, 'tar.xz'),
416 ('debug.tgz', 'debug-%s' % boardpath, 'tgz'),
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800417 (hwqual_tarball, None, None),
418 ('stateful.tgz', None, None),
419 ('dlc', None, None),
Amin Hassani21e0ed12019-11-04 14:24:36 -0800420 (constants.QUICK_PROVISION_PAYLOAD_KERNEL, None, None),
421 (constants.QUICK_PROVISION_PAYLOAD_ROOTFS, None, None),
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400422 )
Amey Deshpandea936c622015-08-12 17:27:54 -0700423
424 # The following build artifacts, if present, are always copied.
425 # If |sign_types| is None, all of them are marked for signing, otherwise
426 # only the image types specified in |sign_types| are marked for signing.
427 files_to_copy_and_maybe_sign = (
428 # (<src>, <dst>, <suffix>, <signing type>),
429 (constants.RECOVERY_IMAGE_TAR, recovery_basename, 'tar.xz',
430 constants.IMAGE_TYPE_RECOVERY),
431
432 ('factory_image.zip', factory_basename, 'zip',
433 constants.IMAGE_TYPE_FACTORY),
434
435 ('firmware_from_source.tar.bz2', firmware_basename, 'tar.bz2',
436 constants.IMAGE_TYPE_FIRMWARE),
David Rileya04d19d2015-09-04 16:11:50 -0700437
Vincent Palatind599c662015-10-26 09:51:41 -0700438 ('firmware_from_source.tar.bz2', acc_usbpd_basename, 'tar.bz2',
439 constants.IMAGE_TYPE_ACCESSORY_USBPD),
440
441 ('firmware_from_source.tar.bz2', acc_rwsig_basename, 'tar.bz2',
442 constants.IMAGE_TYPE_ACCESSORY_RWSIG),
LaMont Jones7d6c98f2019-09-27 12:37:33 -0600443
Vadim Bendeburyfe37f282020-11-04 19:05:49 -0800444 ('firmware_from_source.tar.bz2', gsc_firmware_basename, 'tar.bz2',
445 constants.IMAGE_TYPE_GSC_FIRMWARE),
Amey Deshpandea936c622015-08-12 17:27:54 -0700446 )
447
448 # The following build artifacts are copied and marked for signing, if
449 # they are present *and* if the image type is specified via |sign_types|.
450 files_to_maybe_copy_and_sign = (
451 # (<src>, <dst>, <suffix>, <signing type>),
452 (constants.BASE_IMAGE_TAR, base_basename, 'tar.xz',
453 constants.IMAGE_TYPE_BASE),
454 )
455
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800456 def _CopyFileToGS(src, dst=None, suffix=None):
Amey Deshpandea936c622015-08-12 17:27:54 -0700457 """Returns |dst| file name if the copying was successful."""
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800458 if dst is None:
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400459 dst = src
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800460 elif suffix is not None:
Amey Deshpandea936c622015-08-12 17:27:54 -0700461 dst = '%s.%s' % (dst, suffix)
462 success = False
Mike Frysingere51a2652014-01-18 02:36:16 -0500463 try:
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800464 ctx.Copy(os.path.join(src_path, src), os.path.join(dst_path, dst),
465 recursive=True)
Amey Deshpandea936c622015-08-12 17:27:54 -0700466 success = True
Mike Frysingere51a2652014-01-18 02:36:16 -0500467 except gs.GSNoSuchKey:
Ralph Nathan446aee92015-03-23 14:44:56 -0700468 logging.warning('Skipping %s as it does not exist', src)
Mike Frysinger4495b032014-03-05 17:24:03 -0500469 except gs.GSContextException:
Amey Deshpandea936c622015-08-12 17:27:54 -0700470 unknown_error[0] = True
Ralph Nathan59900422015-03-24 10:41:17 -0700471 logging.error('Skipping %s due to unknown GS error', src, exc_info=True)
Amey Deshpandea936c622015-08-12 17:27:54 -0700472 return dst if success else None
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400473
Amey Deshpandea936c622015-08-12 17:27:54 -0700474 for src, dst, suffix in files_to_copy_only:
475 _CopyFileToGS(src, dst, suffix)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400476
Amey Deshpandea936c622015-08-12 17:27:54 -0700477 # Clear the list of files to sign before adding new artifacts.
478 files_to_sign = []
479
480 def _AddToFilesToSign(image_type, dst, suffix):
481 assert dst.endswith('.' + suffix), (
482 'dst: %s, suffix: %s' % (dst, suffix))
483 dst_base = dst[:-(len(suffix) + 1)]
484 files_to_sign.append([image_type, dst_base, suffix])
485
486 for src, dst, suffix, image_type in files_to_copy_and_maybe_sign:
487 dst = _CopyFileToGS(src, dst, suffix)
488 if dst and (not sign_types or image_type in sign_types):
489 _AddToFilesToSign(image_type, dst, suffix)
490
491 for src, dst, suffix, image_type in files_to_maybe_copy_and_sign:
492 if sign_types and image_type in sign_types:
493 dst = _CopyFileToGS(src, dst, suffix)
494 if dst:
495 _AddToFilesToSign(image_type, dst, suffix)
496
497 logging.debug('Files to sign: %s', files_to_sign)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400498 # Now go through the subset for signing.
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500499 for image_type, dst_name, suffix in files_to_sign:
500 try:
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700501 input_insns = InputInsns(board, image_type=image_type,
502 buildroot=buildroot)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500503 except MissingBoardInstructions as e:
504 logging.info('Nothing to sign: %s', e)
505 continue
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400506
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500507 dst_archive = '%s.%s' % (dst_name, suffix)
508 sect_general['archive'] = dst_archive
509 sect_general['type'] = image_type
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400510
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500511 # In the default/automatic mode, only flag files for signing if the
512 # archives were actually uploaded in a previous stage. This additional
513 # check can be removed in future once |sign_types| becomes a required
514 # argument.
515 # TODO: Make |sign_types| a required argument.
516 gs_artifact_path = os.path.join(dst_path, dst_archive)
517 exists = False
518 try:
519 exists = ctx.Exists(gs_artifact_path)
520 except gs.GSContextException:
521 unknown_error[0] = True
522 logging.error('Unknown error while checking %s', gs_artifact_path,
523 exc_info=True)
524 if not exists:
525 logging.info('%s does not exist. Nothing to sign.',
526 gs_artifact_path)
527 continue
528
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500529 first_image = True
530 for alt_insn_set in input_insns.GetAltInsnSets():
531 # Figure out which keysets have been requested for this type.
532 # We sort the forced set so tests/runtime behavior is stable.
533 keysets = sorted(force_keysets)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500534 if not keysets:
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500535 keysets = input_insns.GetKeysets(insns_merge=alt_insn_set)
536 if not keysets:
537 logging.warning('Skipping %s image signing due to no keysets',
538 image_type)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500539
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500540 for keyset in keysets:
541 sect_insns['keyset'] = keyset
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400542
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500543 # Generate the insn file for this artifact that the signer will use,
544 # and flag it for signing.
Mike Frysinger59babdb2019-09-06 06:25:50 -0400545 with cros_build_lib.UnbufferedNamedTemporaryFile(
546 prefix='pushimage.insns.') as insns_path:
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500547 input_insns.OutputInsns(insns_path.name, sect_insns, sect_general,
548 insns_merge=alt_insn_set)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400549
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500550 gs_insns_path = '%s/%s' % (dst_path, dst_name)
551 if not first_image:
552 gs_insns_path += '-%s' % keyset
553 first_image = False
554 gs_insns_path += '.instructions'
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400555
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500556 try:
557 ctx.Copy(insns_path.name, gs_insns_path)
558 except gs.GSContextException:
559 unknown_error[0] = True
560 logging.error('Unknown error while uploading insns %s',
561 gs_insns_path, exc_info=True)
562 continue
Mike Frysinger4495b032014-03-05 17:24:03 -0500563
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500564 try:
565 MarkImageToBeSigned(ctx, tbs_base, gs_insns_path, priority)
566 except gs.GSContextException:
567 unknown_error[0] = True
568 logging.error('Unknown error while marking for signing %s',
569 gs_insns_path, exc_info=True)
570 continue
571 logging.info('Signing %s image with keyset %s at %s', image_type,
572 keyset, gs_insns_path)
573 instruction_urls.setdefault(channel, []).append(gs_insns_path)
Don Garrett9459c2f2014-01-22 18:20:24 -0800574
Amey Deshpandea936c622015-08-12 17:27:54 -0700575 if unknown_error[0]:
Mike Frysinger4495b032014-03-05 17:24:03 -0500576 raise PushError('hit some unknown error(s)', instruction_urls)
577
Don Garrett9459c2f2014-01-22 18:20:24 -0800578 return instruction_urls
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400579
580
Mike Frysinger26144192017-08-30 18:26:46 -0400581def GetParser():
582 """Creates the argparse parser."""
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400583 parser = commandline.ArgumentParser(description=__doc__)
584
585 # The type of image_dir will strip off trailing slashes (makes later
586 # processing simpler and the display prettier).
587 parser.add_argument('image_dir', default=None, type='local_or_gs_path',
588 help='full path of source artifacts to upload')
589 parser.add_argument('--board', default=None, required=True,
590 help='board to generate symbols for')
591 parser.add_argument('--profile', default=None,
592 help='board profile in use (e.g. "asan")')
593 parser.add_argument('--version', default=None,
594 help='version info (normally extracted from image_dir)')
Mike Frysinger77912102017-08-30 18:35:46 -0400595 parser.add_argument('--channels', default=None, action='split_extend',
596 help='override list of channels to process')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400597 parser.add_argument('-n', '--dry-run', default=False, action='store_true',
598 help='show what would be done, but do not upload')
599 parser.add_argument('-M', '--mock', default=False, action='store_true',
600 help='upload things to a testing bucket (dev testing)')
David Rileyf8205122015-09-04 13:46:36 -0700601 parser.add_argument('--test-sign', default=[], action='append',
602 choices=TEST_KEYSETS,
603 help='mung signing behavior to sign w/ test keys')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400604 parser.add_argument('--priority', type=int, default=50,
605 help='set signing priority (lower == higher prio)')
606 parser.add_argument('--sign-types', default=None, nargs='+',
Amey Deshpandea936c622015-08-12 17:27:54 -0700607 choices=_SUPPORTED_IMAGE_TYPES,
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400608 help='only sign specified image types')
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700609 parser.add_argument('--buildroot', default=constants.SOURCE_ROOT, type='path',
610 help='Buildroot to use. Defaults to current.')
Mike Frysinger09fe0122014-02-09 02:44:05 -0500611 parser.add_argument('--yes', action='store_true', default=False,
612 help='answer yes to all prompts')
Jack Neus485a9d22020-12-21 03:15:15 +0000613 parser.add_argument('--dest-bucket', default=constants.RELEASE_BUCKET,
614 help='dest bucket. Default to %(default)s')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400615
Mike Frysinger26144192017-08-30 18:26:46 -0400616 return parser
617
618
619def main(argv):
620 parser = GetParser()
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400621 opts = parser.parse_args(argv)
622 opts.Freeze()
623
David Rileyf8205122015-09-04 13:46:36 -0700624 force_keysets = set(['%s-%s' % (TEST_KEYSET_PREFIX, x)
625 for x in opts.test_sign])
Mike Frysingerdad40d62014-02-09 02:18:02 -0500626
Mike Frysinger09fe0122014-02-09 02:44:05 -0500627 # If we aren't using mock or test or dry run mode, then let's prompt the user
628 # to make sure they actually want to do this. It's rare that people want to
629 # run this directly and hit the release bucket.
630 if not (opts.mock or force_keysets or opts.dry_run) and not opts.yes:
631 prolog = '\n'.join(textwrap.wrap(textwrap.dedent(
632 'Uploading images for signing to the *release* bucket is not something '
633 'you generally should be doing yourself.'), 80)).strip()
634 if not cros_build_lib.BooleanPrompt(
635 prompt='Are you sure you want to sign these images',
636 default=False, prolog=prolog):
637 cros_build_lib.Die('better safe than sorry')
638
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400639 PushImage(opts.image_dir, opts.board, versionrev=opts.version,
640 profile=opts.profile, priority=opts.priority,
Mike Frysingerdad40d62014-02-09 02:18:02 -0500641 sign_types=opts.sign_types, dry_run=opts.dry_run, mock=opts.mock,
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700642 force_keysets=force_keysets, force_channels=opts.channels,
Jack Neus485a9d22020-12-21 03:15:15 +0000643 buildroot=opts.buildroot, dest_bucket=opts.dest_bucket)