blob: c5c61229afa4ef60aa748128fb6ae364c47bcb9b [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Mike Frysingerd13faeb2013-09-05 16:00:46 -04002# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""ChromeOS image pusher (from cbuildbot to signer).
7
8This pushes files from the archive bucket to the signer bucket and marks
9artifacts for signing (which a signing process will look for).
10"""
11
12from __future__ import print_function
13
Mike Frysingerd13faeb2013-09-05 16:00:46 -040014import getpass
15import os
16import re
Mike Frysinger09fe0122014-02-09 02:44:05 -050017import textwrap
Mike Frysingerd13faeb2013-09-05 16:00:46 -040018
Mike Frysingerb43142e2019-08-27 17:50:44 -040019from six.moves import configparser
Mike Frysingerfd544572019-09-06 16:35:50 -040020from six.moves import StringIO
Mike Frysingerb43142e2019-08-27 17:50:44 -040021
Aviv Keshetb7519e12016-10-04 00:50:00 -070022from chromite.lib import constants
Mike Frysingerd13faeb2013-09-05 16:00:46 -040023from chromite.lib import commandline
24from chromite.lib import cros_build_lib
Ralph Nathan5a582ff2015-03-20 18:18:30 -070025from chromite.lib import cros_logging as logging
Mike Frysingerd13faeb2013-09-05 16:00:46 -040026from chromite.lib import gs
27from chromite.lib import osutils
28from chromite.lib import signing
29
30
31# This will split a fully qualified ChromeOS version string up.
32# R34-5126.0.0 will break into "34" and "5126.0.0".
33VERSION_REGEX = r'^R([0-9]+)-([^-]+)'
34
Mike Frysingerdad40d62014-02-09 02:18:02 -050035# The test signers will scan this dir looking for test work.
36# Keep it in sync with the signer config files [gs_test_buckets].
37TEST_SIGN_BUCKET_BASE = 'gs://chromeos-throw-away-bucket/signer-tests'
38
David Rileyf8205122015-09-04 13:46:36 -070039# Keysets that are only valid in the above test bucket.
40TEST_KEYSET_PREFIX = 'test-keys'
41TEST_KEYSETS = set((
42 'mp',
43 'premp',
44 'nvidia-premp',
45))
Mike Frysingerdad40d62014-02-09 02:18:02 -050046
Amey Deshpandea936c622015-08-12 17:27:54 -070047# Supported image types for signing.
48_SUPPORTED_IMAGE_TYPES = (
49 constants.IMAGE_TYPE_RECOVERY,
50 constants.IMAGE_TYPE_FACTORY,
51 constants.IMAGE_TYPE_FIRMWARE,
David Rileya04d19d2015-09-04 16:11:50 -070052 constants.IMAGE_TYPE_NV_LP0_FIRMWARE,
Vincent Palatind599c662015-10-26 09:51:41 -070053 constants.IMAGE_TYPE_ACCESSORY_USBPD,
54 constants.IMAGE_TYPE_ACCESSORY_RWSIG,
Amey Deshpandea936c622015-08-12 17:27:54 -070055 constants.IMAGE_TYPE_BASE,
LaMont Jones7d6c98f2019-09-27 12:37:33 -060056 constants.IMAGE_TYPE_CR50_FIRMWARE,
Amey Deshpandea936c622015-08-12 17:27:54 -070057)
58
Mike Frysingerd13faeb2013-09-05 16:00:46 -040059
Mike Frysinger4495b032014-03-05 17:24:03 -050060class PushError(Exception):
61 """When an (unknown) error happened while trying to push artifacts."""
62
63
Mike Frysingerd13faeb2013-09-05 16:00:46 -040064class MissingBoardInstructions(Exception):
65 """Raised when a board lacks any signer instructions."""
66
Mike Frysingerd84d91e2015-11-05 18:02:24 -050067 def __init__(self, board, image_type, input_insns):
68 Exception.__init__(self, 'Board %s lacks insns for %s image: %s not found' %
69 (board, image_type, input_insns))
70
Mike Frysingerd13faeb2013-09-05 16:00:46 -040071
72class InputInsns(object):
73 """Object to hold settings for a signable board.
74
75 Note: The format of the instruction file pushimage outputs (and the signer
76 reads) is not exactly the same as the instruction file pushimage reads.
77 """
78
Don Garrett3cf5f9a2018-08-14 13:14:47 -070079 def __init__(self, board, image_type=None, buildroot=None):
Mike Frysingerd84d91e2015-11-05 18:02:24 -050080 """Initialization.
81
82 Args:
83 board: The board to look up details.
84 image_type: The type of image we will be signing (see --sign-types).
Don Garrett3cf5f9a2018-08-14 13:14:47 -070085 buildroot: Buildroot in which to look for signing instructions.
Mike Frysingerd84d91e2015-11-05 18:02:24 -050086 """
Mike Frysingerd13faeb2013-09-05 16:00:46 -040087 self.board = board
Don Garrett3cf5f9a2018-08-14 13:14:47 -070088 self.buildroot = buildroot or constants.SOURCE_ROOT
Mike Frysingerd13faeb2013-09-05 16:00:46 -040089
Mike Frysingerb43142e2019-08-27 17:50:44 -040090 config = configparser.ConfigParser()
Mike Frysingerd7c93092019-10-14 00:12:50 -040091 with open(self.GetInsnFile('DEFAULT')) as fp:
92 config.readfp(fp)
Mike Frysingerd84d91e2015-11-05 18:02:24 -050093
Amey Deshpandea936c622015-08-12 17:27:54 -070094 # What pushimage internally refers to as 'recovery', are the basic signing
95 # instructions in practice, and other types are stacked on top.
Mike Frysingerd84d91e2015-11-05 18:02:24 -050096 if image_type is None:
97 image_type = constants.IMAGE_TYPE_RECOVERY
98 self.image_type = image_type
Amey Deshpandea936c622015-08-12 17:27:54 -070099 input_insns = self.GetInsnFile(constants.IMAGE_TYPE_RECOVERY)
100 if not os.path.exists(input_insns):
101 # This board doesn't have any signing instructions.
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500102 raise MissingBoardInstructions(self.board, image_type, input_insns)
Mike Frysingerd7c93092019-10-14 00:12:50 -0400103 with open(input_insns) as fp:
104 config.readfp(fp)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500105
106 if image_type is not None:
107 input_insns = self.GetInsnFile(image_type)
108 if not os.path.exists(input_insns):
109 # This type doesn't have any signing instructions.
110 raise MissingBoardInstructions(self.board, image_type, input_insns)
111
112 self.image_type = image_type
Mike Frysingerd7c93092019-10-14 00:12:50 -0400113 with open(input_insns) as fp:
114 config.readfp(fp)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500115
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400116 self.cfg = config
117
118 def GetInsnFile(self, image_type):
119 """Find the signer instruction files for this board/image type.
120
121 Args:
122 image_type: The type of instructions to load. It can be a common file
123 (like "DEFAULT"), or one of the --sign-types.
124
125 Returns:
126 Full path to the instruction file using |image_type| and |self.board|.
127 """
128 if image_type == image_type.upper():
129 name = image_type
Amey Deshpandea936c622015-08-12 17:27:54 -0700130 elif image_type in (constants.IMAGE_TYPE_RECOVERY,
131 constants.IMAGE_TYPE_BASE):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400132 name = self.board
133 else:
134 name = '%s.%s' % (self.board, image_type)
135
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700136 return os.path.join(
137 self.buildroot, signing.INPUT_INSN_DIR_REL, '%s.instructions' % name)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400138
139 @staticmethod
140 def SplitCfgField(val):
141 """Split a string into multiple elements.
142
143 This centralizes our convention for multiple elements in the input files
144 being delimited by either a space or comma.
145
146 Args:
147 val: The string to split.
148
149 Returns:
150 The list of elements from having done split the string.
151 """
152 return val.replace(',', ' ').split()
153
154 def GetChannels(self):
155 """Return the list of channels to sign for this board.
156
157 If the board-specific config doesn't specify a preference, we'll use the
158 common settings.
159 """
160 return self.SplitCfgField(self.cfg.get('insns', 'channel'))
161
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500162 def GetKeysets(self, insns_merge=None):
163 """Return the list of keysets to sign for this board.
164
165 Args:
166 insns_merge: The additional section to look at over [insns].
167 """
168 # First load the default value from [insns.keyset] if available.
169 sections = ['insns']
170 # Then overlay the [insns.xxx.keyset] if requested.
171 if insns_merge is not None:
172 sections += [insns_merge]
173
174 keyset = ''
175 for section in sections:
176 try:
177 keyset = self.cfg.get(section, 'keyset')
Mike Frysingerb43142e2019-08-27 17:50:44 -0400178 except (configparser.NoSectionError, configparser.NoOptionError):
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500179 pass
180
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500181 # We do not perturb the order (e.g. using sorted() or making a set())
182 # because we want the behavior stable, and we want the input insns to
183 # explicitly control the order (since it has an impact on naming).
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500184 return self.SplitCfgField(keyset)
185
186 def GetAltInsnSets(self):
187 """Return the list of alternative insn sections."""
188 # We do not perturb the order (e.g. using sorted() or making a set())
189 # because we want the behavior stable, and we want the input insns to
190 # explicitly control the order (since it has an impact on naming).
191 ret = [x for x in self.cfg.sections() if x.startswith('insns.')]
192 return ret if ret else [None]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400193
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500194 @staticmethod
195 def CopyConfigParser(config):
196 """Return a copy of a ConfigParser object.
197
Thiemo Nagel9fb99722017-05-26 16:26:40 +0200198 The python folks broke the ability to use something like deepcopy:
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500199 https://bugs.python.org/issue16058
200 """
201 # Write the current config to a string io object.
Mike Frysingerfd544572019-09-06 16:35:50 -0400202 data = StringIO()
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500203 config.write(data)
204 data.seek(0)
205
206 # Create a new ConfigParser from the serialized data.
Mike Frysingerb43142e2019-08-27 17:50:44 -0400207 ret = configparser.ConfigParser()
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500208 ret.readfp(data)
209
210 return ret
211
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500212 def OutputInsns(self, output_file, sect_insns, sect_general,
213 insns_merge=None):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400214 """Generate the output instruction file for sending to the signer.
215
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500216 The override order is (later has precedence):
217 [insns]
218 [insns_merge] (should be named "insns.xxx")
219 sect_insns
220
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400221 Note: The format of the instruction file pushimage outputs (and the signer
222 reads) is not exactly the same as the instruction file pushimage reads.
223
224 Args:
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400225 output_file: The file to write the new instruction file to.
226 sect_insns: Items to set/override in the [insns] section.
227 sect_general: Items to set/override in the [general] section.
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500228 insns_merge: The alternative insns.xxx section to merge.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400229 """
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500230 # Create a copy so we can clobber certain fields.
231 config = self.CopyConfigParser(self.cfg)
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500232 sect_insns = sect_insns.copy()
233
234 # Merge in the alternative insns section if need be.
235 if insns_merge is not None:
236 for k, v in config.items(insns_merge):
237 sect_insns.setdefault(k, v)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400238
239 # Clear channel entry in instructions file, ensuring we only get
240 # one channel for the signer to look at. Then provide all the
241 # other details for this signing request to avoid any ambiguity
242 # and to avoid relying on encoding data into filenames.
243 for sect, fields in zip(('insns', 'general'), (sect_insns, sect_general)):
244 if not config.has_section(sect):
245 config.add_section(sect)
Mike Frysinger0bdbc102019-06-13 15:27:29 -0400246 for k, v in fields.items():
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400247 config.set(sect, k, v)
248
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500249 # Now prune the alternative sections.
250 for alt in self.GetAltInsnSets():
251 config.remove_section(alt)
252
Mike Frysingerfd544572019-09-06 16:35:50 -0400253 output = StringIO()
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400254 config.write(output)
255 data = output.getvalue()
256 osutils.WriteFile(output_file, data)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500257 logging.debug('generated insns file for %s:\n%s', self.image_type, data)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400258
259
260def MarkImageToBeSigned(ctx, tbs_base, insns_path, priority):
261 """Mark an instructions file for signing.
262
263 This will upload a file to the GS bucket flagging an image for signing by
264 the signers.
265
266 Args:
267 ctx: A viable gs.GSContext.
268 tbs_base: The full path to where the tobesigned directory lives.
269 insns_path: The path (relative to |tbs_base|) of the file to sign.
270 priority: Set the signing priority (lower == higher prio).
271
272 Returns:
273 The full path to the remote tobesigned file.
274 """
275 if priority < 0 or priority > 99:
276 raise ValueError('priority must be [0, 99] inclusive')
277
278 if insns_path.startswith(tbs_base):
279 insns_path = insns_path[len(tbs_base):].lstrip('/')
280
281 tbs_path = '%s/tobesigned/%02i,%s' % (tbs_base, priority,
282 insns_path.replace('/', ','))
283
Mike Frysinger6430d132014-10-27 23:43:30 -0400284 # The caller will catch gs.GSContextException for us.
285 ctx.Copy('-', tbs_path, input=cros_build_lib.MachineDetails())
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400286
287 return tbs_path
288
289
290def PushImage(src_path, board, versionrev=None, profile=None, priority=50,
Mike Frysinger77912102017-08-30 18:35:46 -0400291 sign_types=None, dry_run=False, mock=False, force_keysets=(),
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700292 force_channels=None, buildroot=constants.SOURCE_ROOT):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400293 """Push the image from the archive bucket to the release bucket.
294
295 Args:
296 src_path: Where to copy the files from; can be a local path or gs:// URL.
297 Should be a full path to the artifacts in either case.
298 board: The board we're uploading artifacts for (e.g. $BOARD).
299 versionrev: The full Chromium OS version string (e.g. R34-5126.0.0).
300 profile: The board profile in use (e.g. "asan").
301 priority: Set the signing priority (lower == higher prio).
302 sign_types: If set, a set of types which we'll restrict ourselves to
303 signing. See the --sign-types option for more details.
304 dry_run: Show what would be done, but do not upload anything.
305 mock: Upload to a testing bucket rather than the real one.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500306 force_keysets: Set of keysets to use rather than what the inputs say.
Mike Frysinger77912102017-08-30 18:35:46 -0400307 force_channels: Set of channels to use rather than what the inputs say.
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700308 buildroot: Buildroot in which to look for signing instructions.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400309
310 Returns:
Don Garrett9459c2f2014-01-22 18:20:24 -0800311 A dictionary that maps 'channel' -> ['gs://signer_instruction_uri1',
312 'gs://signer_instruction_uri2',
313 ...]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400314 """
Mike Frysinger4495b032014-03-05 17:24:03 -0500315 # Whether we hit an unknown error. If so, we'll throw an error, but only
316 # at the end (so that we still upload as many files as possible).
Amey Deshpandea936c622015-08-12 17:27:54 -0700317 # It's implemented using a list to deal with variable scopes in nested
318 # functions below.
319 unknown_error = [False]
Mike Frysinger4495b032014-03-05 17:24:03 -0500320
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400321 if versionrev is None:
322 # Extract milestone/version from the directory name.
323 versionrev = os.path.basename(src_path)
324
325 # We only support the latest format here. Older releases can use pushimage
326 # from the respective branch which deals with legacy cruft.
327 m = re.match(VERSION_REGEX, versionrev)
328 if not m:
329 raise ValueError('version %s does not match %s' %
330 (versionrev, VERSION_REGEX))
331 milestone = m.group(1)
332 version = m.group(2)
333
334 # Normalize board to always use dashes not underscores. This is mostly a
335 # historical artifact at this point, but we can't really break it since the
336 # value is used in URLs.
337 boardpath = board.replace('_', '-')
338 if profile is not None:
339 boardpath += '-%s' % profile.replace('_', '-')
340
341 ctx = gs.GSContext(dry_run=dry_run)
342
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400343 try:
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700344 input_insns = InputInsns(board, buildroot=buildroot)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400345 except MissingBoardInstructions as e:
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500346 logging.warning('Missing base instruction file: %s', e)
Ralph Nathan446aee92015-03-23 14:44:56 -0700347 logging.warning('not uploading anything for signing')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400348 return
Mike Frysinger77912102017-08-30 18:35:46 -0400349
350 if force_channels is None:
351 channels = input_insns.GetChannels()
352 else:
353 # Filter out duplicates.
354 channels = sorted(set(force_channels))
Mike Frysingerdad40d62014-02-09 02:18:02 -0500355
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500356 # We want force_keysets as a set.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500357 force_keysets = set(force_keysets)
Mike Frysingerdad40d62014-02-09 02:18:02 -0500358
359 if mock:
Ralph Nathan03047282015-03-23 11:09:32 -0700360 logging.info('Upload mode: mock; signers will not process anything')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500361 tbs_base = gs_base = os.path.join(constants.TRASH_BUCKET, 'pushimage-tests',
362 getpass.getuser())
David Rileyf8205122015-09-04 13:46:36 -0700363 elif set(['%s-%s' % (TEST_KEYSET_PREFIX, x)
364 for x in TEST_KEYSETS]) & force_keysets:
Ralph Nathan03047282015-03-23 11:09:32 -0700365 logging.info('Upload mode: test; signers will process test keys')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500366 # We need the tbs_base to be in the place the signer will actually scan.
367 tbs_base = TEST_SIGN_BUCKET_BASE
368 gs_base = os.path.join(tbs_base, getpass.getuser())
369 else:
Ralph Nathan03047282015-03-23 11:09:32 -0700370 logging.info('Upload mode: normal; signers will process the images')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500371 tbs_base = gs_base = constants.RELEASE_BUCKET
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400372
373 sect_general = {
374 'config_board': board,
375 'board': boardpath,
376 'version': version,
377 'versionrev': versionrev,
378 'milestone': milestone,
379 }
380 sect_insns = {}
381
382 if dry_run:
Ralph Nathan03047282015-03-23 11:09:32 -0700383 logging.info('DRY RUN MODE ACTIVE: NOTHING WILL BE UPLOADED')
384 logging.info('Signing for channels: %s', ' '.join(channels))
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400385
Don Garrett9459c2f2014-01-22 18:20:24 -0800386 instruction_urls = {}
387
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400388 def _ImageNameBase(image_type=None):
389 lmid = ('%s-' % image_type) if image_type else ''
390 return 'ChromeOS-%s%s-%s' % (lmid, versionrev, boardpath)
391
Amey Deshpandea936c622015-08-12 17:27:54 -0700392 # These variables are defined outside the loop so that the nested functions
393 # below can access them without 'cell-var-from-loop' linter warning.
Mike Frysinger80de5012019-08-01 14:10:53 -0400394 dst_path = ''
Amey Deshpandea936c622015-08-12 17:27:54 -0700395 files_to_sign = []
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400396 for channel in channels:
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700397 logging.debug('\n\n#### CHANNEL: %s ####\n', channel)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400398 sect_insns['channel'] = channel
399 sub_path = '%s-channel/%s/%s' % (channel, boardpath, version)
400 dst_path = '%s/%s' % (gs_base, sub_path)
Ralph Nathan03047282015-03-23 11:09:32 -0700401 logging.info('Copying images to %s', dst_path)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400402
Amey Deshpandea936c622015-08-12 17:27:54 -0700403 recovery_basename = _ImageNameBase(constants.IMAGE_TYPE_RECOVERY)
404 factory_basename = _ImageNameBase(constants.IMAGE_TYPE_FACTORY)
405 firmware_basename = _ImageNameBase(constants.IMAGE_TYPE_FIRMWARE)
David Rileya04d19d2015-09-04 16:11:50 -0700406 nv_lp0_firmware_basename = _ImageNameBase(
407 constants.IMAGE_TYPE_NV_LP0_FIRMWARE)
Vincent Palatind599c662015-10-26 09:51:41 -0700408 acc_usbpd_basename = _ImageNameBase(constants.IMAGE_TYPE_ACCESSORY_USBPD)
409 acc_rwsig_basename = _ImageNameBase(constants.IMAGE_TYPE_ACCESSORY_RWSIG)
LaMont Jones7d6c98f2019-09-27 12:37:33 -0600410 cr50_firmware_basename = _ImageNameBase(constants.IMAGE_TYPE_CR50_FIRMWARE)
Amey Deshpandea936c622015-08-12 17:27:54 -0700411 test_basename = _ImageNameBase(constants.IMAGE_TYPE_TEST)
412 base_basename = _ImageNameBase(constants.IMAGE_TYPE_BASE)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400413 hwqual_tarball = 'chromeos-hwqual-%s-%s.tar.bz2' % (board, versionrev)
414
Amey Deshpandea936c622015-08-12 17:27:54 -0700415 # The following build artifacts, if present, are always copied regardless of
416 # requested signing types.
417 files_to_copy_only = (
418 # (<src>, <dst>, <suffix>),
419 ('image.zip', _ImageNameBase(), 'zip'),
420 (constants.TEST_IMAGE_TAR, test_basename, 'tar.xz'),
421 ('debug.tgz', 'debug-%s' % boardpath, 'tgz'),
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800422 (hwqual_tarball, None, None),
423 ('stateful.tgz', None, None),
424 ('dlc', 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
441 ('firmware_from_source.tar.bz2', nv_lp0_firmware_basename, 'tar.bz2',
442 constants.IMAGE_TYPE_NV_LP0_FIRMWARE),
Vincent Palatind599c662015-10-26 09:51:41 -0700443
444 ('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
450 ('firmware_from_source.tar.bz2', cr50_firmware_basename, 'tar.bz2',
451 constants.IMAGE_TYPE_CR50_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)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400504 # Now go through the subset for signing.
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500505 for image_type, dst_name, suffix in files_to_sign:
506 try:
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700507 input_insns = InputInsns(board, image_type=image_type,
508 buildroot=buildroot)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500509 except MissingBoardInstructions as e:
510 logging.info('Nothing to sign: %s', e)
511 continue
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400512
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500513 dst_archive = '%s.%s' % (dst_name, suffix)
514 sect_general['archive'] = dst_archive
515 sect_general['type'] = image_type
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400516
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500517 # In the default/automatic mode, only flag files for signing if the
518 # archives were actually uploaded in a previous stage. This additional
519 # check can be removed in future once |sign_types| becomes a required
520 # argument.
521 # TODO: Make |sign_types| a required argument.
522 gs_artifact_path = os.path.join(dst_path, dst_archive)
523 exists = False
524 try:
525 exists = ctx.Exists(gs_artifact_path)
526 except gs.GSContextException:
527 unknown_error[0] = True
528 logging.error('Unknown error while checking %s', gs_artifact_path,
529 exc_info=True)
530 if not exists:
531 logging.info('%s does not exist. Nothing to sign.',
532 gs_artifact_path)
533 continue
534
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500535 first_image = True
536 for alt_insn_set in input_insns.GetAltInsnSets():
537 # Figure out which keysets have been requested for this type.
538 # We sort the forced set so tests/runtime behavior is stable.
539 keysets = sorted(force_keysets)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500540 if not keysets:
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500541 keysets = input_insns.GetKeysets(insns_merge=alt_insn_set)
542 if not keysets:
543 logging.warning('Skipping %s image signing due to no keysets',
544 image_type)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500545
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500546 for keyset in keysets:
547 sect_insns['keyset'] = keyset
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400548
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500549 # Generate the insn file for this artifact that the signer will use,
550 # and flag it for signing.
Mike Frysinger59babdb2019-09-06 06:25:50 -0400551 with cros_build_lib.UnbufferedNamedTemporaryFile(
552 prefix='pushimage.insns.') as insns_path:
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500553 input_insns.OutputInsns(insns_path.name, sect_insns, sect_general,
554 insns_merge=alt_insn_set)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400555
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500556 gs_insns_path = '%s/%s' % (dst_path, dst_name)
557 if not first_image:
558 gs_insns_path += '-%s' % keyset
559 first_image = False
560 gs_insns_path += '.instructions'
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400561
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500562 try:
563 ctx.Copy(insns_path.name, gs_insns_path)
564 except gs.GSContextException:
565 unknown_error[0] = True
566 logging.error('Unknown error while uploading insns %s',
567 gs_insns_path, exc_info=True)
568 continue
Mike Frysinger4495b032014-03-05 17:24:03 -0500569
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500570 try:
571 MarkImageToBeSigned(ctx, tbs_base, gs_insns_path, priority)
572 except gs.GSContextException:
573 unknown_error[0] = True
574 logging.error('Unknown error while marking for signing %s',
575 gs_insns_path, exc_info=True)
576 continue
577 logging.info('Signing %s image with keyset %s at %s', image_type,
578 keyset, gs_insns_path)
579 instruction_urls.setdefault(channel, []).append(gs_insns_path)
Don Garrett9459c2f2014-01-22 18:20:24 -0800580
Amey Deshpandea936c622015-08-12 17:27:54 -0700581 if unknown_error[0]:
Mike Frysinger4495b032014-03-05 17:24:03 -0500582 raise PushError('hit some unknown error(s)', instruction_urls)
583
Don Garrett9459c2f2014-01-22 18:20:24 -0800584 return instruction_urls
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400585
586
Mike Frysinger26144192017-08-30 18:26:46 -0400587def GetParser():
588 """Creates the argparse parser."""
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400589 parser = commandline.ArgumentParser(description=__doc__)
590
591 # The type of image_dir will strip off trailing slashes (makes later
592 # processing simpler and the display prettier).
593 parser.add_argument('image_dir', default=None, type='local_or_gs_path',
594 help='full path of source artifacts to upload')
595 parser.add_argument('--board', default=None, required=True,
596 help='board to generate symbols for')
597 parser.add_argument('--profile', default=None,
598 help='board profile in use (e.g. "asan")')
599 parser.add_argument('--version', default=None,
600 help='version info (normally extracted from image_dir)')
Mike Frysinger77912102017-08-30 18:35:46 -0400601 parser.add_argument('--channels', default=None, action='split_extend',
602 help='override list of channels to process')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400603 parser.add_argument('-n', '--dry-run', default=False, action='store_true',
604 help='show what would be done, but do not upload')
605 parser.add_argument('-M', '--mock', default=False, action='store_true',
606 help='upload things to a testing bucket (dev testing)')
David Rileyf8205122015-09-04 13:46:36 -0700607 parser.add_argument('--test-sign', default=[], action='append',
608 choices=TEST_KEYSETS,
609 help='mung signing behavior to sign w/ test keys')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400610 parser.add_argument('--priority', type=int, default=50,
611 help='set signing priority (lower == higher prio)')
612 parser.add_argument('--sign-types', default=None, nargs='+',
Amey Deshpandea936c622015-08-12 17:27:54 -0700613 choices=_SUPPORTED_IMAGE_TYPES,
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400614 help='only sign specified image types')
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700615 parser.add_argument('--buildroot', default=constants.SOURCE_ROOT, type='path',
616 help='Buildroot to use. Defaults to current.')
Mike Frysinger09fe0122014-02-09 02:44:05 -0500617 parser.add_argument('--yes', action='store_true', default=False,
618 help='answer yes to all prompts')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400619
Mike Frysinger26144192017-08-30 18:26:46 -0400620 return parser
621
622
623def main(argv):
624 parser = GetParser()
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400625 opts = parser.parse_args(argv)
626 opts.Freeze()
627
David Rileyf8205122015-09-04 13:46:36 -0700628 force_keysets = set(['%s-%s' % (TEST_KEYSET_PREFIX, x)
629 for x in opts.test_sign])
Mike Frysingerdad40d62014-02-09 02:18:02 -0500630
Mike Frysinger09fe0122014-02-09 02:44:05 -0500631 # If we aren't using mock or test or dry run mode, then let's prompt the user
632 # to make sure they actually want to do this. It's rare that people want to
633 # run this directly and hit the release bucket.
634 if not (opts.mock or force_keysets or opts.dry_run) and not opts.yes:
635 prolog = '\n'.join(textwrap.wrap(textwrap.dedent(
636 'Uploading images for signing to the *release* bucket is not something '
637 'you generally should be doing yourself.'), 80)).strip()
638 if not cros_build_lib.BooleanPrompt(
639 prompt='Are you sure you want to sign these images',
640 default=False, prolog=prolog):
641 cros_build_lib.Die('better safe than sorry')
642
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400643 PushImage(opts.image_dir, opts.board, versionrev=opts.version,
644 profile=opts.profile, priority=opts.priority,
Mike Frysingerdad40d62014-02-09 02:18:02 -0500645 sign_types=opts.sign_types, dry_run=opts.dry_run, mock=opts.mock,
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700646 force_keysets=force_keysets, force_channels=opts.channels,
647 buildroot=opts.buildroot)