blob: e926b84518398ff3e7d00e0697c24b546ad30daa [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
14import ConfigParser
15import cStringIO
Mike Frysingerd13faeb2013-09-05 16:00:46 -040016import getpass
17import os
18import re
19import tempfile
Mike Frysinger09fe0122014-02-09 02:44:05 -050020import textwrap
Mike Frysingerd13faeb2013-09-05 16:00:46 -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,
56)
57
Mike Frysingerd13faeb2013-09-05 16:00:46 -040058
Mike Frysinger4495b032014-03-05 17:24:03 -050059class PushError(Exception):
60 """When an (unknown) error happened while trying to push artifacts."""
61
62
Mike Frysingerd13faeb2013-09-05 16:00:46 -040063class MissingBoardInstructions(Exception):
64 """Raised when a board lacks any signer instructions."""
65
Mike Frysingerd84d91e2015-11-05 18:02:24 -050066 def __init__(self, board, image_type, input_insns):
67 Exception.__init__(self, 'Board %s lacks insns for %s image: %s not found' %
68 (board, image_type, input_insns))
69
Mike Frysingerd13faeb2013-09-05 16:00:46 -040070
71class InputInsns(object):
72 """Object to hold settings for a signable board.
73
74 Note: The format of the instruction file pushimage outputs (and the signer
75 reads) is not exactly the same as the instruction file pushimage reads.
76 """
77
Mike Frysingerd84d91e2015-11-05 18:02:24 -050078 def __init__(self, board, image_type=None):
79 """Initialization.
80
81 Args:
82 board: The board to look up details.
83 image_type: The type of image we will be signing (see --sign-types).
84 """
Mike Frysingerd13faeb2013-09-05 16:00:46 -040085 self.board = board
86
87 config = ConfigParser.ConfigParser()
88 config.readfp(open(self.GetInsnFile('DEFAULT')))
Mike Frysingerd84d91e2015-11-05 18:02:24 -050089
Amey Deshpandea936c622015-08-12 17:27:54 -070090 # What pushimage internally refers to as 'recovery', are the basic signing
91 # instructions in practice, and other types are stacked on top.
Mike Frysingerd84d91e2015-11-05 18:02:24 -050092 if image_type is None:
93 image_type = constants.IMAGE_TYPE_RECOVERY
94 self.image_type = image_type
Amey Deshpandea936c622015-08-12 17:27:54 -070095 input_insns = self.GetInsnFile(constants.IMAGE_TYPE_RECOVERY)
96 if not os.path.exists(input_insns):
97 # This board doesn't have any signing instructions.
Mike Frysingerd84d91e2015-11-05 18:02:24 -050098 raise MissingBoardInstructions(self.board, image_type, input_insns)
Amey Deshpandea936c622015-08-12 17:27:54 -070099 config.readfp(open(input_insns))
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
108 config.readfp(open(input_insns))
109
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400110 self.cfg = config
111
112 def GetInsnFile(self, image_type):
113 """Find the signer instruction files for this board/image type.
114
115 Args:
116 image_type: The type of instructions to load. It can be a common file
117 (like "DEFAULT"), or one of the --sign-types.
118
119 Returns:
120 Full path to the instruction file using |image_type| and |self.board|.
121 """
122 if image_type == image_type.upper():
123 name = image_type
Amey Deshpandea936c622015-08-12 17:27:54 -0700124 elif image_type in (constants.IMAGE_TYPE_RECOVERY,
125 constants.IMAGE_TYPE_BASE):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400126 name = self.board
127 else:
128 name = '%s.%s' % (self.board, image_type)
129
130 return os.path.join(signing.INPUT_INSN_DIR, '%s.instructions' % name)
131
132 @staticmethod
133 def SplitCfgField(val):
134 """Split a string into multiple elements.
135
136 This centralizes our convention for multiple elements in the input files
137 being delimited by either a space or comma.
138
139 Args:
140 val: The string to split.
141
142 Returns:
143 The list of elements from having done split the string.
144 """
145 return val.replace(',', ' ').split()
146
147 def GetChannels(self):
148 """Return the list of channels to sign for this board.
149
150 If the board-specific config doesn't specify a preference, we'll use the
151 common settings.
152 """
153 return self.SplitCfgField(self.cfg.get('insns', 'channel'))
154
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500155 def GetKeysets(self, insns_merge=None):
156 """Return the list of keysets to sign for this board.
157
158 Args:
159 insns_merge: The additional section to look at over [insns].
160 """
161 # First load the default value from [insns.keyset] if available.
162 sections = ['insns']
163 # Then overlay the [insns.xxx.keyset] if requested.
164 if insns_merge is not None:
165 sections += [insns_merge]
166
167 keyset = ''
168 for section in sections:
169 try:
170 keyset = self.cfg.get(section, 'keyset')
171 except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
172 pass
173
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500174 # We do not perturb the order (e.g. using sorted() or making a set())
175 # because we want the behavior stable, and we want the input insns to
176 # explicitly control the order (since it has an impact on naming).
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500177 return self.SplitCfgField(keyset)
178
179 def GetAltInsnSets(self):
180 """Return the list of alternative insn sections."""
181 # 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).
184 ret = [x for x in self.cfg.sections() if x.startswith('insns.')]
185 return ret if ret else [None]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400186
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500187 @staticmethod
188 def CopyConfigParser(config):
189 """Return a copy of a ConfigParser object.
190
Thiemo Nagel9fb99722017-05-26 16:26:40 +0200191 The python folks broke the ability to use something like deepcopy:
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500192 https://bugs.python.org/issue16058
193 """
194 # Write the current config to a string io object.
195 data = cStringIO.StringIO()
196 config.write(data)
197 data.seek(0)
198
199 # Create a new ConfigParser from the serialized data.
200 ret = ConfigParser.ConfigParser()
201 ret.readfp(data)
202
203 return ret
204
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500205 def OutputInsns(self, output_file, sect_insns, sect_general,
206 insns_merge=None):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400207 """Generate the output instruction file for sending to the signer.
208
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500209 The override order is (later has precedence):
210 [insns]
211 [insns_merge] (should be named "insns.xxx")
212 sect_insns
213
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400214 Note: The format of the instruction file pushimage outputs (and the signer
215 reads) is not exactly the same as the instruction file pushimage reads.
216
217 Args:
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400218 output_file: The file to write the new instruction file to.
219 sect_insns: Items to set/override in the [insns] section.
220 sect_general: Items to set/override in the [general] section.
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500221 insns_merge: The alternative insns.xxx section to merge.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400222 """
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500223 # Create a copy so we can clobber certain fields.
224 config = self.CopyConfigParser(self.cfg)
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500225 sect_insns = sect_insns.copy()
226
227 # Merge in the alternative insns section if need be.
228 if insns_merge is not None:
229 for k, v in config.items(insns_merge):
230 sect_insns.setdefault(k, v)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400231
232 # Clear channel entry in instructions file, ensuring we only get
233 # one channel for the signer to look at. Then provide all the
234 # other details for this signing request to avoid any ambiguity
235 # and to avoid relying on encoding data into filenames.
236 for sect, fields in zip(('insns', 'general'), (sect_insns, sect_general)):
237 if not config.has_section(sect):
238 config.add_section(sect)
239 for k, v in fields.iteritems():
240 config.set(sect, k, v)
241
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500242 # Now prune the alternative sections.
243 for alt in self.GetAltInsnSets():
244 config.remove_section(alt)
245
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400246 output = cStringIO.StringIO()
247 config.write(output)
248 data = output.getvalue()
249 osutils.WriteFile(output_file, data)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500250 logging.debug('generated insns file for %s:\n%s', self.image_type, data)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400251
252
253def MarkImageToBeSigned(ctx, tbs_base, insns_path, priority):
254 """Mark an instructions file for signing.
255
256 This will upload a file to the GS bucket flagging an image for signing by
257 the signers.
258
259 Args:
260 ctx: A viable gs.GSContext.
261 tbs_base: The full path to where the tobesigned directory lives.
262 insns_path: The path (relative to |tbs_base|) of the file to sign.
263 priority: Set the signing priority (lower == higher prio).
264
265 Returns:
266 The full path to the remote tobesigned file.
267 """
268 if priority < 0 or priority > 99:
269 raise ValueError('priority must be [0, 99] inclusive')
270
271 if insns_path.startswith(tbs_base):
272 insns_path = insns_path[len(tbs_base):].lstrip('/')
273
274 tbs_path = '%s/tobesigned/%02i,%s' % (tbs_base, priority,
275 insns_path.replace('/', ','))
276
Mike Frysinger6430d132014-10-27 23:43:30 -0400277 # The caller will catch gs.GSContextException for us.
278 ctx.Copy('-', tbs_path, input=cros_build_lib.MachineDetails())
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400279
280 return tbs_path
281
282
283def PushImage(src_path, board, versionrev=None, profile=None, priority=50,
Mike Frysinger77912102017-08-30 18:35:46 -0400284 sign_types=None, dry_run=False, mock=False, force_keysets=(),
285 force_channels=None):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400286 """Push the image from the archive bucket to the release bucket.
287
288 Args:
289 src_path: Where to copy the files from; can be a local path or gs:// URL.
290 Should be a full path to the artifacts in either case.
291 board: The board we're uploading artifacts for (e.g. $BOARD).
292 versionrev: The full Chromium OS version string (e.g. R34-5126.0.0).
293 profile: The board profile in use (e.g. "asan").
294 priority: Set the signing priority (lower == higher prio).
295 sign_types: If set, a set of types which we'll restrict ourselves to
296 signing. See the --sign-types option for more details.
297 dry_run: Show what would be done, but do not upload anything.
298 mock: Upload to a testing bucket rather than the real one.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500299 force_keysets: Set of keysets to use rather than what the inputs say.
Mike Frysinger77912102017-08-30 18:35:46 -0400300 force_channels: Set of channels to use rather than what the inputs say.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400301
302 Returns:
Don Garrett9459c2f2014-01-22 18:20:24 -0800303 A dictionary that maps 'channel' -> ['gs://signer_instruction_uri1',
304 'gs://signer_instruction_uri2',
305 ...]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400306 """
Mike Frysinger4495b032014-03-05 17:24:03 -0500307 # Whether we hit an unknown error. If so, we'll throw an error, but only
308 # at the end (so that we still upload as many files as possible).
Amey Deshpandea936c622015-08-12 17:27:54 -0700309 # It's implemented using a list to deal with variable scopes in nested
310 # functions below.
311 unknown_error = [False]
Mike Frysinger4495b032014-03-05 17:24:03 -0500312
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400313 if versionrev is None:
314 # Extract milestone/version from the directory name.
315 versionrev = os.path.basename(src_path)
316
317 # We only support the latest format here. Older releases can use pushimage
318 # from the respective branch which deals with legacy cruft.
319 m = re.match(VERSION_REGEX, versionrev)
320 if not m:
321 raise ValueError('version %s does not match %s' %
322 (versionrev, VERSION_REGEX))
323 milestone = m.group(1)
324 version = m.group(2)
325
326 # Normalize board to always use dashes not underscores. This is mostly a
327 # historical artifact at this point, but we can't really break it since the
328 # value is used in URLs.
329 boardpath = board.replace('_', '-')
330 if profile is not None:
331 boardpath += '-%s' % profile.replace('_', '-')
332
333 ctx = gs.GSContext(dry_run=dry_run)
334
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400335 try:
336 input_insns = InputInsns(board)
337 except MissingBoardInstructions as e:
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500338 logging.warning('Missing base instruction file: %s', e)
Ralph Nathan446aee92015-03-23 14:44:56 -0700339 logging.warning('not uploading anything for signing')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400340 return
Mike Frysinger77912102017-08-30 18:35:46 -0400341
342 if force_channels is None:
343 channels = input_insns.GetChannels()
344 else:
345 # Filter out duplicates.
346 channels = sorted(set(force_channels))
Mike Frysingerdad40d62014-02-09 02:18:02 -0500347
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500348 # We want force_keysets as a set.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500349 force_keysets = set(force_keysets)
Mike Frysingerdad40d62014-02-09 02:18:02 -0500350
351 if mock:
Ralph Nathan03047282015-03-23 11:09:32 -0700352 logging.info('Upload mode: mock; signers will not process anything')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500353 tbs_base = gs_base = os.path.join(constants.TRASH_BUCKET, 'pushimage-tests',
354 getpass.getuser())
David Rileyf8205122015-09-04 13:46:36 -0700355 elif set(['%s-%s' % (TEST_KEYSET_PREFIX, x)
356 for x in TEST_KEYSETS]) & force_keysets:
Ralph Nathan03047282015-03-23 11:09:32 -0700357 logging.info('Upload mode: test; signers will process test keys')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500358 # We need the tbs_base to be in the place the signer will actually scan.
359 tbs_base = TEST_SIGN_BUCKET_BASE
360 gs_base = os.path.join(tbs_base, getpass.getuser())
361 else:
Ralph Nathan03047282015-03-23 11:09:32 -0700362 logging.info('Upload mode: normal; signers will process the images')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500363 tbs_base = gs_base = constants.RELEASE_BUCKET
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400364
365 sect_general = {
366 'config_board': board,
367 'board': boardpath,
368 'version': version,
369 'versionrev': versionrev,
370 'milestone': milestone,
371 }
372 sect_insns = {}
373
374 if dry_run:
Ralph Nathan03047282015-03-23 11:09:32 -0700375 logging.info('DRY RUN MODE ACTIVE: NOTHING WILL BE UPLOADED')
376 logging.info('Signing for channels: %s', ' '.join(channels))
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400377
Don Garrett9459c2f2014-01-22 18:20:24 -0800378 instruction_urls = {}
379
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400380 def _ImageNameBase(image_type=None):
381 lmid = ('%s-' % image_type) if image_type else ''
382 return 'ChromeOS-%s%s-%s' % (lmid, versionrev, boardpath)
383
Amey Deshpandea936c622015-08-12 17:27:54 -0700384 # These variables are defined outside the loop so that the nested functions
385 # below can access them without 'cell-var-from-loop' linter warning.
386 dst_path = ""
387 files_to_sign = []
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400388 for channel in channels:
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700389 logging.debug('\n\n#### CHANNEL: %s ####\n', channel)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400390 sect_insns['channel'] = channel
391 sub_path = '%s-channel/%s/%s' % (channel, boardpath, version)
392 dst_path = '%s/%s' % (gs_base, sub_path)
Ralph Nathan03047282015-03-23 11:09:32 -0700393 logging.info('Copying images to %s', dst_path)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400394
Amey Deshpandea936c622015-08-12 17:27:54 -0700395 recovery_basename = _ImageNameBase(constants.IMAGE_TYPE_RECOVERY)
396 factory_basename = _ImageNameBase(constants.IMAGE_TYPE_FACTORY)
397 firmware_basename = _ImageNameBase(constants.IMAGE_TYPE_FIRMWARE)
David Rileya04d19d2015-09-04 16:11:50 -0700398 nv_lp0_firmware_basename = _ImageNameBase(
399 constants.IMAGE_TYPE_NV_LP0_FIRMWARE)
Vincent Palatind599c662015-10-26 09:51:41 -0700400 acc_usbpd_basename = _ImageNameBase(constants.IMAGE_TYPE_ACCESSORY_USBPD)
401 acc_rwsig_basename = _ImageNameBase(constants.IMAGE_TYPE_ACCESSORY_RWSIG)
Amey Deshpandea936c622015-08-12 17:27:54 -0700402 test_basename = _ImageNameBase(constants.IMAGE_TYPE_TEST)
403 base_basename = _ImageNameBase(constants.IMAGE_TYPE_BASE)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400404 hwqual_tarball = 'chromeos-hwqual-%s-%s.tar.bz2' % (board, versionrev)
405
Amey Deshpandea936c622015-08-12 17:27:54 -0700406 # The following build artifacts, if present, are always copied regardless of
407 # requested signing types.
408 files_to_copy_only = (
409 # (<src>, <dst>, <suffix>),
410 ('image.zip', _ImageNameBase(), 'zip'),
411 (constants.TEST_IMAGE_TAR, test_basename, 'tar.xz'),
412 ('debug.tgz', 'debug-%s' % boardpath, 'tgz'),
413 (hwqual_tarball, '', ''),
414 ('au-generator.zip', '', ''),
415 ('stateful.tgz', '', ''),
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400416 )
Amey Deshpandea936c622015-08-12 17:27:54 -0700417
418 # The following build artifacts, if present, are always copied.
419 # If |sign_types| is None, all of them are marked for signing, otherwise
420 # only the image types specified in |sign_types| are marked for signing.
421 files_to_copy_and_maybe_sign = (
422 # (<src>, <dst>, <suffix>, <signing type>),
423 (constants.RECOVERY_IMAGE_TAR, recovery_basename, 'tar.xz',
424 constants.IMAGE_TYPE_RECOVERY),
425
426 ('factory_image.zip', factory_basename, 'zip',
427 constants.IMAGE_TYPE_FACTORY),
428
429 ('firmware_from_source.tar.bz2', firmware_basename, 'tar.bz2',
430 constants.IMAGE_TYPE_FIRMWARE),
David Rileya04d19d2015-09-04 16:11:50 -0700431
432 ('firmware_from_source.tar.bz2', nv_lp0_firmware_basename, 'tar.bz2',
433 constants.IMAGE_TYPE_NV_LP0_FIRMWARE),
Vincent Palatind599c662015-10-26 09:51:41 -0700434
435 ('firmware_from_source.tar.bz2', acc_usbpd_basename, 'tar.bz2',
436 constants.IMAGE_TYPE_ACCESSORY_USBPD),
437
438 ('firmware_from_source.tar.bz2', acc_rwsig_basename, 'tar.bz2',
439 constants.IMAGE_TYPE_ACCESSORY_RWSIG),
Amey Deshpandea936c622015-08-12 17:27:54 -0700440 )
441
442 # The following build artifacts are copied and marked for signing, if
443 # they are present *and* if the image type is specified via |sign_types|.
444 files_to_maybe_copy_and_sign = (
445 # (<src>, <dst>, <suffix>, <signing type>),
446 (constants.BASE_IMAGE_TAR, base_basename, 'tar.xz',
447 constants.IMAGE_TYPE_BASE),
448 )
449
450 def _CopyFileToGS(src, dst, suffix):
451 """Returns |dst| file name if the copying was successful."""
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400452 if not dst:
453 dst = src
Amey Deshpandea936c622015-08-12 17:27:54 -0700454 elif suffix:
455 dst = '%s.%s' % (dst, suffix)
456 success = False
Mike Frysingere51a2652014-01-18 02:36:16 -0500457 try:
458 ctx.Copy(os.path.join(src_path, src), os.path.join(dst_path, dst))
Amey Deshpandea936c622015-08-12 17:27:54 -0700459 success = True
Mike Frysingere51a2652014-01-18 02:36:16 -0500460 except gs.GSNoSuchKey:
Ralph Nathan446aee92015-03-23 14:44:56 -0700461 logging.warning('Skipping %s as it does not exist', src)
Mike Frysinger4495b032014-03-05 17:24:03 -0500462 except gs.GSContextException:
Amey Deshpandea936c622015-08-12 17:27:54 -0700463 unknown_error[0] = True
Ralph Nathan59900422015-03-24 10:41:17 -0700464 logging.error('Skipping %s due to unknown GS error', src, exc_info=True)
Amey Deshpandea936c622015-08-12 17:27:54 -0700465 return dst if success else None
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400466
Amey Deshpandea936c622015-08-12 17:27:54 -0700467 for src, dst, suffix in files_to_copy_only:
468 _CopyFileToGS(src, dst, suffix)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400469
Amey Deshpandea936c622015-08-12 17:27:54 -0700470 # Clear the list of files to sign before adding new artifacts.
471 files_to_sign = []
472
473 def _AddToFilesToSign(image_type, dst, suffix):
474 assert dst.endswith('.' + suffix), (
475 'dst: %s, suffix: %s' % (dst, suffix))
476 dst_base = dst[:-(len(suffix) + 1)]
477 files_to_sign.append([image_type, dst_base, suffix])
478
479 for src, dst, suffix, image_type in files_to_copy_and_maybe_sign:
480 dst = _CopyFileToGS(src, dst, suffix)
481 if dst and (not sign_types or image_type in sign_types):
482 _AddToFilesToSign(image_type, dst, suffix)
483
484 for src, dst, suffix, image_type in files_to_maybe_copy_and_sign:
485 if sign_types and image_type in sign_types:
486 dst = _CopyFileToGS(src, dst, suffix)
487 if dst:
488 _AddToFilesToSign(image_type, dst, suffix)
489
490 logging.debug('Files to sign: %s', files_to_sign)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400491 # Now go through the subset for signing.
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500492 for image_type, dst_name, suffix in files_to_sign:
493 try:
494 input_insns = InputInsns(board, image_type=image_type)
495 except MissingBoardInstructions as e:
496 logging.info('Nothing to sign: %s', e)
497 continue
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400498
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500499 dst_archive = '%s.%s' % (dst_name, suffix)
500 sect_general['archive'] = dst_archive
501 sect_general['type'] = image_type
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400502
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500503 # In the default/automatic mode, only flag files for signing if the
504 # archives were actually uploaded in a previous stage. This additional
505 # check can be removed in future once |sign_types| becomes a required
506 # argument.
507 # TODO: Make |sign_types| a required argument.
508 gs_artifact_path = os.path.join(dst_path, dst_archive)
509 exists = False
510 try:
511 exists = ctx.Exists(gs_artifact_path)
512 except gs.GSContextException:
513 unknown_error[0] = True
514 logging.error('Unknown error while checking %s', gs_artifact_path,
515 exc_info=True)
516 if not exists:
517 logging.info('%s does not exist. Nothing to sign.',
518 gs_artifact_path)
519 continue
520
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500521 first_image = True
522 for alt_insn_set in input_insns.GetAltInsnSets():
523 # Figure out which keysets have been requested for this type.
524 # We sort the forced set so tests/runtime behavior is stable.
525 keysets = sorted(force_keysets)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500526 if not keysets:
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500527 keysets = input_insns.GetKeysets(insns_merge=alt_insn_set)
528 if not keysets:
529 logging.warning('Skipping %s image signing due to no keysets',
530 image_type)
Mike Frysingerd84d91e2015-11-05 18:02:24 -0500531
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500532 for keyset in keysets:
533 sect_insns['keyset'] = keyset
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400534
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500535 # Generate the insn file for this artifact that the signer will use,
536 # and flag it for signing.
537 with tempfile.NamedTemporaryFile(
538 bufsize=0, prefix='pushimage.insns.') as insns_path:
539 input_insns.OutputInsns(insns_path.name, sect_insns, sect_general,
540 insns_merge=alt_insn_set)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400541
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500542 gs_insns_path = '%s/%s' % (dst_path, dst_name)
543 if not first_image:
544 gs_insns_path += '-%s' % keyset
545 first_image = False
546 gs_insns_path += '.instructions'
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400547
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500548 try:
549 ctx.Copy(insns_path.name, gs_insns_path)
550 except gs.GSContextException:
551 unknown_error[0] = True
552 logging.error('Unknown error while uploading insns %s',
553 gs_insns_path, exc_info=True)
554 continue
Mike Frysinger4495b032014-03-05 17:24:03 -0500555
Mike Frysinger37ccc2b2015-11-11 17:16:51 -0500556 try:
557 MarkImageToBeSigned(ctx, tbs_base, gs_insns_path, priority)
558 except gs.GSContextException:
559 unknown_error[0] = True
560 logging.error('Unknown error while marking for signing %s',
561 gs_insns_path, exc_info=True)
562 continue
563 logging.info('Signing %s image with keyset %s at %s', image_type,
564 keyset, gs_insns_path)
565 instruction_urls.setdefault(channel, []).append(gs_insns_path)
Don Garrett9459c2f2014-01-22 18:20:24 -0800566
Amey Deshpandea936c622015-08-12 17:27:54 -0700567 if unknown_error[0]:
Mike Frysinger4495b032014-03-05 17:24:03 -0500568 raise PushError('hit some unknown error(s)', instruction_urls)
569
Don Garrett9459c2f2014-01-22 18:20:24 -0800570 return instruction_urls
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400571
572
Mike Frysinger26144192017-08-30 18:26:46 -0400573def GetParser():
574 """Creates the argparse parser."""
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400575 parser = commandline.ArgumentParser(description=__doc__)
576
577 # The type of image_dir will strip off trailing slashes (makes later
578 # processing simpler and the display prettier).
579 parser.add_argument('image_dir', default=None, type='local_or_gs_path',
580 help='full path of source artifacts to upload')
581 parser.add_argument('--board', default=None, required=True,
582 help='board to generate symbols for')
583 parser.add_argument('--profile', default=None,
584 help='board profile in use (e.g. "asan")')
585 parser.add_argument('--version', default=None,
586 help='version info (normally extracted from image_dir)')
Mike Frysinger77912102017-08-30 18:35:46 -0400587 parser.add_argument('--channels', default=None, action='split_extend',
588 help='override list of channels to process')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400589 parser.add_argument('-n', '--dry-run', default=False, action='store_true',
590 help='show what would be done, but do not upload')
591 parser.add_argument('-M', '--mock', default=False, action='store_true',
592 help='upload things to a testing bucket (dev testing)')
David Rileyf8205122015-09-04 13:46:36 -0700593 parser.add_argument('--test-sign', default=[], action='append',
594 choices=TEST_KEYSETS,
595 help='mung signing behavior to sign w/ test keys')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400596 parser.add_argument('--priority', type=int, default=50,
597 help='set signing priority (lower == higher prio)')
598 parser.add_argument('--sign-types', default=None, nargs='+',
Amey Deshpandea936c622015-08-12 17:27:54 -0700599 choices=_SUPPORTED_IMAGE_TYPES,
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400600 help='only sign specified image types')
Mike Frysinger09fe0122014-02-09 02:44:05 -0500601 parser.add_argument('--yes', action='store_true', default=False,
602 help='answer yes to all prompts')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400603
Mike Frysinger26144192017-08-30 18:26:46 -0400604 return parser
605
606
607def main(argv):
608 parser = GetParser()
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400609 opts = parser.parse_args(argv)
610 opts.Freeze()
611
David Rileyf8205122015-09-04 13:46:36 -0700612 force_keysets = set(['%s-%s' % (TEST_KEYSET_PREFIX, x)
613 for x in opts.test_sign])
Mike Frysingerdad40d62014-02-09 02:18:02 -0500614
Mike Frysinger09fe0122014-02-09 02:44:05 -0500615 # If we aren't using mock or test or dry run mode, then let's prompt the user
616 # to make sure they actually want to do this. It's rare that people want to
617 # run this directly and hit the release bucket.
618 if not (opts.mock or force_keysets or opts.dry_run) and not opts.yes:
619 prolog = '\n'.join(textwrap.wrap(textwrap.dedent(
620 'Uploading images for signing to the *release* bucket is not something '
621 'you generally should be doing yourself.'), 80)).strip()
622 if not cros_build_lib.BooleanPrompt(
623 prompt='Are you sure you want to sign these images',
624 default=False, prolog=prolog):
625 cros_build_lib.Die('better safe than sorry')
626
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400627 PushImage(opts.image_dir, opts.board, versionrev=opts.version,
628 profile=opts.profile, priority=opts.priority,
Mike Frysingerdad40d62014-02-09 02:18:02 -0500629 sign_types=opts.sign_types, dry_run=opts.dry_run, mock=opts.mock,
Mike Frysinger77912102017-08-30 18:35:46 -0400630 force_keysets=force_keysets, force_channels=opts.channels)