blob: 752d7ddf2e43116822e64206cf61ad60bd1aa9a2 [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 Frysinger99a7f8a2020-04-19 06:23:18 -040017import sys
Mike Frysinger09fe0122014-02-09 02:44:05 -050018import textwrap
Mike Frysingerd13faeb2013-09-05 16:00:46 -040019
Mike Frysingerb43142e2019-08-27 17:50:44 -040020from six.moves import configparser
Mike Frysingerfd544572019-09-06 16:35:50 -040021from six.moves import StringIO
Mike Frysingerb43142e2019-08-27 17:50:44 -040022
Aviv Keshetb7519e12016-10-04 00:50:00 -070023from chromite.lib import constants
Mike Frysingerd13faeb2013-09-05 16:00:46 -040024from chromite.lib import commandline
25from chromite.lib import cros_build_lib
Ralph Nathan5a582ff2015-03-20 18:18:30 -070026from chromite.lib import cros_logging as logging
Mike Frysingerd13faeb2013-09-05 16:00:46 -040027from chromite.lib import gs
28from chromite.lib import osutils
29from chromite.lib import signing
30
31
Mike Frysinger99a7f8a2020-04-19 06:23:18 -040032assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
33
34
Mike Frysingerd13faeb2013-09-05 16:00:46 -040035# This will split a fully qualified ChromeOS version string up.
36# R34-5126.0.0 will break into "34" and "5126.0.0".
37VERSION_REGEX = r'^R([0-9]+)-([^-]+)'
38
Mike Frysingerdad40d62014-02-09 02:18:02 -050039# The test signers will scan this dir looking for test work.
40# Keep it in sync with the signer config files [gs_test_buckets].
41TEST_SIGN_BUCKET_BASE = 'gs://chromeos-throw-away-bucket/signer-tests'
42
David Rileyf8205122015-09-04 13:46:36 -070043# Keysets that are only valid in the above test bucket.
44TEST_KEYSET_PREFIX = 'test-keys'
45TEST_KEYSETS = set((
46 'mp',
47 'premp',
48 'nvidia-premp',
49))
Mike Frysingerdad40d62014-02-09 02:18:02 -050050
Amey Deshpandea936c622015-08-12 17:27:54 -070051# Supported image types for signing.
52_SUPPORTED_IMAGE_TYPES = (
53 constants.IMAGE_TYPE_RECOVERY,
54 constants.IMAGE_TYPE_FACTORY,
55 constants.IMAGE_TYPE_FIRMWARE,
David Rileya04d19d2015-09-04 16:11:50 -070056 constants.IMAGE_TYPE_NV_LP0_FIRMWARE,
Vincent Palatind599c662015-10-26 09:51:41 -070057 constants.IMAGE_TYPE_ACCESSORY_USBPD,
58 constants.IMAGE_TYPE_ACCESSORY_RWSIG,
Amey Deshpandea936c622015-08-12 17:27:54 -070059 constants.IMAGE_TYPE_BASE,
LaMont Jones7d6c98f2019-09-27 12:37:33 -060060 constants.IMAGE_TYPE_CR50_FIRMWARE,
Amey Deshpandea936c622015-08-12 17:27:54 -070061)
62
Mike Frysingerd13faeb2013-09-05 16:00:46 -040063
Mike Frysinger4495b032014-03-05 17:24:03 -050064class PushError(Exception):
65 """When an (unknown) error happened while trying to push artifacts."""
66
67
Mike Frysingerd13faeb2013-09-05 16:00:46 -040068class MissingBoardInstructions(Exception):
69 """Raised when a board lacks any signer instructions."""
70
Mike Frysingerd84d91e2015-11-05 18:02:24 -050071 def __init__(self, board, image_type, input_insns):
72 Exception.__init__(self, 'Board %s lacks insns for %s image: %s not found' %
73 (board, image_type, input_insns))
74
Mike Frysingerd13faeb2013-09-05 16:00:46 -040075
76class InputInsns(object):
77 """Object to hold settings for a signable board.
78
79 Note: The format of the instruction file pushimage outputs (and the signer
80 reads) is not exactly the same as the instruction file pushimage reads.
81 """
82
Don Garrett3cf5f9a2018-08-14 13:14:47 -070083 def __init__(self, board, image_type=None, buildroot=None):
Mike Frysingerd84d91e2015-11-05 18:02:24 -050084 """Initialization.
85
86 Args:
87 board: The board to look up details.
88 image_type: The type of image we will be signing (see --sign-types).
Don Garrett3cf5f9a2018-08-14 13:14:47 -070089 buildroot: Buildroot in which to look for signing instructions.
Mike Frysingerd84d91e2015-11-05 18:02:24 -050090 """
Mike Frysingerd13faeb2013-09-05 16:00:46 -040091 self.board = board
Don Garrett3cf5f9a2018-08-14 13:14:47 -070092 self.buildroot = buildroot or constants.SOURCE_ROOT
Mike Frysingerd13faeb2013-09-05 16:00:46 -040093
Mike Frysingerb43142e2019-08-27 17:50:44 -040094 config = configparser.ConfigParser()
Mike Frysingerd7c93092019-10-14 00:12:50 -040095 with open(self.GetInsnFile('DEFAULT')) as fp:
96 config.readfp(fp)
Mike Frysingerd84d91e2015-11-05 18:02:24 -050097
Amey Deshpandea936c622015-08-12 17:27:54 -070098 # What pushimage internally refers to as 'recovery', are the basic signing
99 # instructions in practice, and other types are stacked on top.
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500100 if image_type is None:
101 image_type = constants.IMAGE_TYPE_RECOVERY
102 self.image_type = image_type
Amey Deshpandea936c622015-08-12 17:27:54 -0700103 input_insns = self.GetInsnFile(constants.IMAGE_TYPE_RECOVERY)
104 if not os.path.exists(input_insns):
105 # This board doesn't have any signing instructions.
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500106 raise MissingBoardInstructions(self.board, image_type, input_insns)
Mike Frysingerd7c93092019-10-14 00:12:50 -0400107 with open(input_insns) as fp:
108 config.readfp(fp)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500109
110 if image_type is not None:
111 input_insns = self.GetInsnFile(image_type)
112 if not os.path.exists(input_insns):
113 # This type doesn't have any signing instructions.
114 raise MissingBoardInstructions(self.board, image_type, input_insns)
115
116 self.image_type = image_type
Mike Frysingerd7c93092019-10-14 00:12:50 -0400117 with open(input_insns) as fp:
118 config.readfp(fp)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500119
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400120 self.cfg = config
121
122 def GetInsnFile(self, image_type):
123 """Find the signer instruction files for this board/image type.
124
125 Args:
126 image_type: The type of instructions to load. It can be a common file
127 (like "DEFAULT"), or one of the --sign-types.
128
129 Returns:
130 Full path to the instruction file using |image_type| and |self.board|.
131 """
132 if image_type == image_type.upper():
133 name = image_type
Amey Deshpandea936c622015-08-12 17:27:54 -0700134 elif image_type in (constants.IMAGE_TYPE_RECOVERY,
135 constants.IMAGE_TYPE_BASE):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400136 name = self.board
137 else:
138 name = '%s.%s' % (self.board, image_type)
139
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700140 return os.path.join(
141 self.buildroot, signing.INPUT_INSN_DIR_REL, '%s.instructions' % name)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400142
143 @staticmethod
144 def SplitCfgField(val):
145 """Split a string into multiple elements.
146
147 This centralizes our convention for multiple elements in the input files
148 being delimited by either a space or comma.
149
150 Args:
151 val: The string to split.
152
153 Returns:
154 The list of elements from having done split the string.
155 """
156 return val.replace(',', ' ').split()
157
158 def GetChannels(self):
159 """Return the list of channels to sign for this board.
160
161 If the board-specific config doesn't specify a preference, we'll use the
162 common settings.
163 """
164 return self.SplitCfgField(self.cfg.get('insns', 'channel'))
165
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500166 def GetKeysets(self, insns_merge=None):
167 """Return the list of keysets to sign for this board.
168
169 Args:
170 insns_merge: The additional section to look at over [insns].
171 """
172 # First load the default value from [insns.keyset] if available.
173 sections = ['insns']
174 # Then overlay the [insns.xxx.keyset] if requested.
175 if insns_merge is not None:
176 sections += [insns_merge]
177
178 keyset = ''
179 for section in sections:
180 try:
181 keyset = self.cfg.get(section, 'keyset')
Mike Frysingerb43142e2019-08-27 17:50:44 -0400182 except (configparser.NoSectionError, configparser.NoOptionError):
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500183 pass
184
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500185 # We do not perturb the order (e.g. using sorted() or making a set())
186 # because we want the behavior stable, and we want the input insns to
187 # explicitly control the order (since it has an impact on naming).
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500188 return self.SplitCfgField(keyset)
189
190 def GetAltInsnSets(self):
191 """Return the list of alternative insn sections."""
192 # We do not perturb the order (e.g. using sorted() or making a set())
193 # because we want the behavior stable, and we want the input insns to
194 # explicitly control the order (since it has an impact on naming).
195 ret = [x for x in self.cfg.sections() if x.startswith('insns.')]
196 return ret if ret else [None]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400197
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500198 @staticmethod
199 def CopyConfigParser(config):
200 """Return a copy of a ConfigParser object.
201
Thiemo Nagel9fb99722017-05-26 16:26:40 +0200202 The python folks broke the ability to use something like deepcopy:
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500203 https://bugs.python.org/issue16058
204 """
205 # Write the current config to a string io object.
Mike Frysingerfd544572019-09-06 16:35:50 -0400206 data = StringIO()
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500207 config.write(data)
208 data.seek(0)
209
210 # Create a new ConfigParser from the serialized data.
Mike Frysingerb43142e2019-08-27 17:50:44 -0400211 ret = configparser.ConfigParser()
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500212 ret.readfp(data)
213
214 return ret
215
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500216 def OutputInsns(self, output_file, sect_insns, sect_general,
217 insns_merge=None):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400218 """Generate the output instruction file for sending to the signer.
219
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500220 The override order is (later has precedence):
221 [insns]
222 [insns_merge] (should be named "insns.xxx")
223 sect_insns
224
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400225 Note: The format of the instruction file pushimage outputs (and the signer
226 reads) is not exactly the same as the instruction file pushimage reads.
227
228 Args:
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400229 output_file: The file to write the new instruction file to.
230 sect_insns: Items to set/override in the [insns] section.
231 sect_general: Items to set/override in the [general] section.
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500232 insns_merge: The alternative insns.xxx section to merge.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400233 """
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500234 # Create a copy so we can clobber certain fields.
235 config = self.CopyConfigParser(self.cfg)
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500236 sect_insns = sect_insns.copy()
237
238 # Merge in the alternative insns section if need be.
239 if insns_merge is not None:
240 for k, v in config.items(insns_merge):
241 sect_insns.setdefault(k, v)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400242
243 # Clear channel entry in instructions file, ensuring we only get
244 # one channel for the signer to look at. Then provide all the
245 # other details for this signing request to avoid any ambiguity
246 # and to avoid relying on encoding data into filenames.
247 for sect, fields in zip(('insns', 'general'), (sect_insns, sect_general)):
248 if not config.has_section(sect):
249 config.add_section(sect)
Mike Frysinger0bdbc102019-06-13 15:27:29 -0400250 for k, v in fields.items():
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400251 config.set(sect, k, v)
252
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500253 # Now prune the alternative sections.
254 for alt in self.GetAltInsnSets():
255 config.remove_section(alt)
256
Mike Frysingerfd544572019-09-06 16:35:50 -0400257 output = StringIO()
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400258 config.write(output)
259 data = output.getvalue()
260 osutils.WriteFile(output_file, data)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500261 logging.debug('generated insns file for %s:\n%s', self.image_type, data)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400262
263
264def MarkImageToBeSigned(ctx, tbs_base, insns_path, priority):
265 """Mark an instructions file for signing.
266
267 This will upload a file to the GS bucket flagging an image for signing by
268 the signers.
269
270 Args:
271 ctx: A viable gs.GSContext.
272 tbs_base: The full path to where the tobesigned directory lives.
273 insns_path: The path (relative to |tbs_base|) of the file to sign.
274 priority: Set the signing priority (lower == higher prio).
275
276 Returns:
277 The full path to the remote tobesigned file.
278 """
279 if priority < 0 or priority > 99:
280 raise ValueError('priority must be [0, 99] inclusive')
281
282 if insns_path.startswith(tbs_base):
283 insns_path = insns_path[len(tbs_base):].lstrip('/')
284
285 tbs_path = '%s/tobesigned/%02i,%s' % (tbs_base, priority,
286 insns_path.replace('/', ','))
287
Mike Frysinger6430d132014-10-27 23:43:30 -0400288 # The caller will catch gs.GSContextException for us.
289 ctx.Copy('-', tbs_path, input=cros_build_lib.MachineDetails())
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400290
291 return tbs_path
292
293
294def PushImage(src_path, board, versionrev=None, profile=None, priority=50,
Mike Frysinger77912102017-08-30 18:35:46 -0400295 sign_types=None, dry_run=False, mock=False, force_keysets=(),
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700296 force_channels=None, buildroot=constants.SOURCE_ROOT):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400297 """Push the image from the archive bucket to the release bucket.
298
299 Args:
300 src_path: Where to copy the files from; can be a local path or gs:// URL.
301 Should be a full path to the artifacts in either case.
302 board: The board we're uploading artifacts for (e.g. $BOARD).
303 versionrev: The full Chromium OS version string (e.g. R34-5126.0.0).
304 profile: The board profile in use (e.g. "asan").
305 priority: Set the signing priority (lower == higher prio).
306 sign_types: If set, a set of types which we'll restrict ourselves to
307 signing. See the --sign-types option for more details.
308 dry_run: Show what would be done, but do not upload anything.
309 mock: Upload to a testing bucket rather than the real one.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500310 force_keysets: Set of keysets to use rather than what the inputs say.
Mike Frysinger77912102017-08-30 18:35:46 -0400311 force_channels: Set of channels to use rather than what the inputs say.
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700312 buildroot: Buildroot in which to look for signing instructions.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400313
314 Returns:
Don Garrett9459c2f2014-01-22 18:20:24 -0800315 A dictionary that maps 'channel' -> ['gs://signer_instruction_uri1',
316 'gs://signer_instruction_uri2',
317 ...]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400318 """
Mike Frysinger4495b032014-03-05 17:24:03 -0500319 # Whether we hit an unknown error. If so, we'll throw an error, but only
320 # at the end (so that we still upload as many files as possible).
Amey Deshpandea936c622015-08-12 17:27:54 -0700321 # It's implemented using a list to deal with variable scopes in nested
322 # functions below.
323 unknown_error = [False]
Mike Frysinger4495b032014-03-05 17:24:03 -0500324
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400325 if versionrev is None:
326 # Extract milestone/version from the directory name.
327 versionrev = os.path.basename(src_path)
328
329 # We only support the latest format here. Older releases can use pushimage
330 # from the respective branch which deals with legacy cruft.
331 m = re.match(VERSION_REGEX, versionrev)
332 if not m:
333 raise ValueError('version %s does not match %s' %
334 (versionrev, VERSION_REGEX))
335 milestone = m.group(1)
336 version = m.group(2)
337
338 # Normalize board to always use dashes not underscores. This is mostly a
339 # historical artifact at this point, but we can't really break it since the
340 # value is used in URLs.
341 boardpath = board.replace('_', '-')
342 if profile is not None:
343 boardpath += '-%s' % profile.replace('_', '-')
344
345 ctx = gs.GSContext(dry_run=dry_run)
346
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400347 try:
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700348 input_insns = InputInsns(board, buildroot=buildroot)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400349 except MissingBoardInstructions as e:
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500350 logging.warning('Missing base instruction file: %s', e)
Ralph Nathan446aee92015-03-23 14:44:56 -0700351 logging.warning('not uploading anything for signing')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400352 return
Mike Frysinger77912102017-08-30 18:35:46 -0400353
354 if force_channels is None:
355 channels = input_insns.GetChannels()
356 else:
357 # Filter out duplicates.
358 channels = sorted(set(force_channels))
Mike Frysingerdad40d62014-02-09 02:18:02 -0500359
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500360 # We want force_keysets as a set.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500361 force_keysets = set(force_keysets)
Mike Frysingerdad40d62014-02-09 02:18:02 -0500362
363 if mock:
Ralph Nathan03047282015-03-23 11:09:32 -0700364 logging.info('Upload mode: mock; signers will not process anything')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500365 tbs_base = gs_base = os.path.join(constants.TRASH_BUCKET, 'pushimage-tests',
366 getpass.getuser())
David Rileyf8205122015-09-04 13:46:36 -0700367 elif set(['%s-%s' % (TEST_KEYSET_PREFIX, x)
368 for x in TEST_KEYSETS]) & force_keysets:
Ralph Nathan03047282015-03-23 11:09:32 -0700369 logging.info('Upload mode: test; signers will process test keys')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500370 # We need the tbs_base to be in the place the signer will actually scan.
371 tbs_base = TEST_SIGN_BUCKET_BASE
372 gs_base = os.path.join(tbs_base, getpass.getuser())
373 else:
Ralph Nathan03047282015-03-23 11:09:32 -0700374 logging.info('Upload mode: normal; signers will process the images')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500375 tbs_base = gs_base = constants.RELEASE_BUCKET
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400376
377 sect_general = {
378 'config_board': board,
379 'board': boardpath,
380 'version': version,
381 'versionrev': versionrev,
382 'milestone': milestone,
383 }
384 sect_insns = {}
385
386 if dry_run:
Ralph Nathan03047282015-03-23 11:09:32 -0700387 logging.info('DRY RUN MODE ACTIVE: NOTHING WILL BE UPLOADED')
388 logging.info('Signing for channels: %s', ' '.join(channels))
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400389
Don Garrett9459c2f2014-01-22 18:20:24 -0800390 instruction_urls = {}
391
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400392 def _ImageNameBase(image_type=None):
393 lmid = ('%s-' % image_type) if image_type else ''
394 return 'ChromeOS-%s%s-%s' % (lmid, versionrev, boardpath)
395
Amey Deshpandea936c622015-08-12 17:27:54 -0700396 # These variables are defined outside the loop so that the nested functions
397 # below can access them without 'cell-var-from-loop' linter warning.
Mike Frysinger80de5012019-08-01 14:10:53 -0400398 dst_path = ''
Amey Deshpandea936c622015-08-12 17:27:54 -0700399 files_to_sign = []
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400400 for channel in channels:
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700401 logging.debug('\n\n#### CHANNEL: %s ####\n', channel)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400402 sect_insns['channel'] = channel
403 sub_path = '%s-channel/%s/%s' % (channel, boardpath, version)
404 dst_path = '%s/%s' % (gs_base, sub_path)
Ralph Nathan03047282015-03-23 11:09:32 -0700405 logging.info('Copying images to %s', dst_path)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400406
Amey Deshpandea936c622015-08-12 17:27:54 -0700407 recovery_basename = _ImageNameBase(constants.IMAGE_TYPE_RECOVERY)
408 factory_basename = _ImageNameBase(constants.IMAGE_TYPE_FACTORY)
409 firmware_basename = _ImageNameBase(constants.IMAGE_TYPE_FIRMWARE)
David Rileya04d19d2015-09-04 16:11:50 -0700410 nv_lp0_firmware_basename = _ImageNameBase(
411 constants.IMAGE_TYPE_NV_LP0_FIRMWARE)
Vincent Palatind599c662015-10-26 09:51:41 -0700412 acc_usbpd_basename = _ImageNameBase(constants.IMAGE_TYPE_ACCESSORY_USBPD)
413 acc_rwsig_basename = _ImageNameBase(constants.IMAGE_TYPE_ACCESSORY_RWSIG)
LaMont Jones7d6c98f2019-09-27 12:37:33 -0600414 cr50_firmware_basename = _ImageNameBase(constants.IMAGE_TYPE_CR50_FIRMWARE)
Amey Deshpandea936c622015-08-12 17:27:54 -0700415 test_basename = _ImageNameBase(constants.IMAGE_TYPE_TEST)
416 base_basename = _ImageNameBase(constants.IMAGE_TYPE_BASE)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400417 hwqual_tarball = 'chromeos-hwqual-%s-%s.tar.bz2' % (board, versionrev)
418
Amey Deshpandea936c622015-08-12 17:27:54 -0700419 # The following build artifacts, if present, are always copied regardless of
420 # requested signing types.
421 files_to_copy_only = (
422 # (<src>, <dst>, <suffix>),
423 ('image.zip', _ImageNameBase(), 'zip'),
424 (constants.TEST_IMAGE_TAR, test_basename, 'tar.xz'),
425 ('debug.tgz', 'debug-%s' % boardpath, 'tgz'),
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800426 (hwqual_tarball, None, None),
427 ('stateful.tgz', None, None),
428 ('dlc', None, None),
Amin Hassani21e0ed12019-11-04 14:24:36 -0800429 (constants.QUICK_PROVISION_PAYLOAD_KERNEL, None, None),
430 (constants.QUICK_PROVISION_PAYLOAD_ROOTFS, None, None),
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400431 )
Amey Deshpandea936c622015-08-12 17:27:54 -0700432
433 # The following build artifacts, if present, are always copied.
434 # If |sign_types| is None, all of them are marked for signing, otherwise
435 # only the image types specified in |sign_types| are marked for signing.
436 files_to_copy_and_maybe_sign = (
437 # (<src>, <dst>, <suffix>, <signing type>),
438 (constants.RECOVERY_IMAGE_TAR, recovery_basename, 'tar.xz',
439 constants.IMAGE_TYPE_RECOVERY),
440
441 ('factory_image.zip', factory_basename, 'zip',
442 constants.IMAGE_TYPE_FACTORY),
443
444 ('firmware_from_source.tar.bz2', firmware_basename, 'tar.bz2',
445 constants.IMAGE_TYPE_FIRMWARE),
David Rileya04d19d2015-09-04 16:11:50 -0700446
447 ('firmware_from_source.tar.bz2', nv_lp0_firmware_basename, 'tar.bz2',
448 constants.IMAGE_TYPE_NV_LP0_FIRMWARE),
Vincent Palatind599c662015-10-26 09:51:41 -0700449
450 ('firmware_from_source.tar.bz2', acc_usbpd_basename, 'tar.bz2',
451 constants.IMAGE_TYPE_ACCESSORY_USBPD),
452
453 ('firmware_from_source.tar.bz2', acc_rwsig_basename, 'tar.bz2',
454 constants.IMAGE_TYPE_ACCESSORY_RWSIG),
LaMont Jones7d6c98f2019-09-27 12:37:33 -0600455
456 ('firmware_from_source.tar.bz2', cr50_firmware_basename, 'tar.bz2',
457 constants.IMAGE_TYPE_CR50_FIRMWARE),
Amey Deshpandea936c622015-08-12 17:27:54 -0700458 )
459
460 # The following build artifacts are copied and marked for signing, if
461 # they are present *and* if the image type is specified via |sign_types|.
462 files_to_maybe_copy_and_sign = (
463 # (<src>, <dst>, <suffix>, <signing type>),
464 (constants.BASE_IMAGE_TAR, base_basename, 'tar.xz',
465 constants.IMAGE_TYPE_BASE),
466 )
467
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800468 def _CopyFileToGS(src, dst=None, suffix=None):
Amey Deshpandea936c622015-08-12 17:27:54 -0700469 """Returns |dst| file name if the copying was successful."""
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800470 if dst is None:
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400471 dst = src
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800472 elif suffix is not None:
Amey Deshpandea936c622015-08-12 17:27:54 -0700473 dst = '%s.%s' % (dst, suffix)
474 success = False
Mike Frysingere51a2652014-01-18 02:36:16 -0500475 try:
Xiaochu Liu254e0dd2019-03-08 16:10:57 -0800476 ctx.Copy(os.path.join(src_path, src), os.path.join(dst_path, dst),
477 recursive=True)
Amey Deshpandea936c622015-08-12 17:27:54 -0700478 success = True
Mike Frysingere51a2652014-01-18 02:36:16 -0500479 except gs.GSNoSuchKey:
Ralph Nathan446aee92015-03-23 14:44:56 -0700480 logging.warning('Skipping %s as it does not exist', src)
Mike Frysinger4495b032014-03-05 17:24:03 -0500481 except gs.GSContextException:
Amey Deshpandea936c622015-08-12 17:27:54 -0700482 unknown_error[0] = True
Ralph Nathan59900422015-03-24 10:41:17 -0700483 logging.error('Skipping %s due to unknown GS error', src, exc_info=True)
Amey Deshpandea936c622015-08-12 17:27:54 -0700484 return dst if success else None
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400485
Amey Deshpandea936c622015-08-12 17:27:54 -0700486 for src, dst, suffix in files_to_copy_only:
487 _CopyFileToGS(src, dst, suffix)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400488
Amey Deshpandea936c622015-08-12 17:27:54 -0700489 # Clear the list of files to sign before adding new artifacts.
490 files_to_sign = []
491
492 def _AddToFilesToSign(image_type, dst, suffix):
493 assert dst.endswith('.' + suffix), (
494 'dst: %s, suffix: %s' % (dst, suffix))
495 dst_base = dst[:-(len(suffix) + 1)]
496 files_to_sign.append([image_type, dst_base, suffix])
497
498 for src, dst, suffix, image_type in files_to_copy_and_maybe_sign:
499 dst = _CopyFileToGS(src, dst, suffix)
500 if dst and (not sign_types or image_type in sign_types):
501 _AddToFilesToSign(image_type, dst, suffix)
502
503 for src, dst, suffix, image_type in files_to_maybe_copy_and_sign:
504 if sign_types and image_type in sign_types:
505 dst = _CopyFileToGS(src, dst, suffix)
506 if dst:
507 _AddToFilesToSign(image_type, dst, suffix)
508
509 logging.debug('Files to sign: %s', files_to_sign)
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')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400625
Mike Frysinger26144192017-08-30 18:26:46 -0400626 return parser
627
628
629def main(argv):
630 parser = GetParser()
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400631 opts = parser.parse_args(argv)
632 opts.Freeze()
633
David Rileyf8205122015-09-04 13:46:36 -0700634 force_keysets = set(['%s-%s' % (TEST_KEYSET_PREFIX, x)
635 for x in opts.test_sign])
Mike Frysingerdad40d62014-02-09 02:18:02 -0500636
Mike Frysinger09fe0122014-02-09 02:44:05 -0500637 # If we aren't using mock or test or dry run mode, then let's prompt the user
638 # to make sure they actually want to do this. It's rare that people want to
639 # run this directly and hit the release bucket.
640 if not (opts.mock or force_keysets or opts.dry_run) and not opts.yes:
641 prolog = '\n'.join(textwrap.wrap(textwrap.dedent(
642 'Uploading images for signing to the *release* bucket is not something '
643 'you generally should be doing yourself.'), 80)).strip()
644 if not cros_build_lib.BooleanPrompt(
645 prompt='Are you sure you want to sign these images',
646 default=False, prolog=prolog):
647 cros_build_lib.Die('better safe than sorry')
648
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400649 PushImage(opts.image_dir, opts.board, versionrev=opts.version,
650 profile=opts.profile, priority=opts.priority,
Mike Frysingerdad40d62014-02-09 02:18:02 -0500651 sign_types=opts.sign_types, dry_run=opts.dry_run, mock=opts.mock,
Don Garrett3cf5f9a2018-08-14 13:14:47 -0700652 force_keysets=force_keysets, force_channels=opts.channels,
653 buildroot=opts.buildroot)