blob: 7b659938386fe63f70589a69e34f652191bbbf1c [file] [log] [blame]
Mike Frysingerd13faeb2013-09-05 16:00:46 -04001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""ChromeOS image pusher (from cbuildbot to signer).
6
7This pushes files from the archive bucket to the signer bucket and marks
8artifacts for signing (which a signing process will look for).
9"""
10
11from __future__ import print_function
12
13import ConfigParser
14import cStringIO
Don Garrettfd97b402015-09-03 00:59:21 +000015import errno
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
Don Garrett88b8d782014-05-13 17:30:55 -070022from chromite.cbuildbot 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
39# Ketsets that are only valid in the above test bucket.
40TEST_KEYSETS = set(('test-keys-mp', 'test-keys-premp'))
41
Mike Frysingerd13faeb2013-09-05 16:00:46 -040042
Mike Frysinger4495b032014-03-05 17:24:03 -050043class PushError(Exception):
44 """When an (unknown) error happened while trying to push artifacts."""
45
46
Mike Frysingerd13faeb2013-09-05 16:00:46 -040047class MissingBoardInstructions(Exception):
48 """Raised when a board lacks any signer instructions."""
49
50
51class InputInsns(object):
52 """Object to hold settings for a signable board.
53
54 Note: The format of the instruction file pushimage outputs (and the signer
55 reads) is not exactly the same as the instruction file pushimage reads.
56 """
57
58 def __init__(self, board):
59 self.board = board
60
61 config = ConfigParser.ConfigParser()
62 config.readfp(open(self.GetInsnFile('DEFAULT')))
Don Garrettfd97b402015-09-03 00:59:21 +000063 try:
64 input_insn = self.GetInsnFile('recovery')
65 config.readfp(open(input_insn))
66 except IOError as e:
67 if e.errno == errno.ENOENT:
68 # This board doesn't have any signing instructions.
69 # This is normal for new or experimental boards.
70 raise MissingBoardInstructions(input_insn)
71 raise
Mike Frysingerd13faeb2013-09-05 16:00:46 -040072 self.cfg = config
73
74 def GetInsnFile(self, image_type):
75 """Find the signer instruction files for this board/image type.
76
77 Args:
78 image_type: The type of instructions to load. It can be a common file
79 (like "DEFAULT"), or one of the --sign-types.
80
81 Returns:
82 Full path to the instruction file using |image_type| and |self.board|.
83 """
84 if image_type == image_type.upper():
85 name = image_type
Don Garrettfd97b402015-09-03 00:59:21 +000086 elif image_type == 'recovery':
Mike Frysingerd13faeb2013-09-05 16:00:46 -040087 name = self.board
88 else:
89 name = '%s.%s' % (self.board, image_type)
90
91 return os.path.join(signing.INPUT_INSN_DIR, '%s.instructions' % name)
92
93 @staticmethod
94 def SplitCfgField(val):
95 """Split a string into multiple elements.
96
97 This centralizes our convention for multiple elements in the input files
98 being delimited by either a space or comma.
99
100 Args:
101 val: The string to split.
102
103 Returns:
104 The list of elements from having done split the string.
105 """
106 return val.replace(',', ' ').split()
107
108 def GetChannels(self):
109 """Return the list of channels to sign for this board.
110
111 If the board-specific config doesn't specify a preference, we'll use the
112 common settings.
113 """
114 return self.SplitCfgField(self.cfg.get('insns', 'channel'))
115
116 def GetKeysets(self):
117 """Return the list of keysets to sign for this board."""
118 return self.SplitCfgField(self.cfg.get('insns', 'keyset'))
119
120 def OutputInsns(self, image_type, output_file, sect_insns, sect_general):
121 """Generate the output instruction file for sending to the signer.
122
123 Note: The format of the instruction file pushimage outputs (and the signer
124 reads) is not exactly the same as the instruction file pushimage reads.
125
126 Args:
127 image_type: The type of image we will be signing (see --sign-types).
128 output_file: The file to write the new instruction file to.
129 sect_insns: Items to set/override in the [insns] section.
130 sect_general: Items to set/override in the [general] section.
131 """
132 config = ConfigParser.ConfigParser()
133 config.readfp(open(self.GetInsnFile(image_type)))
134
135 # Clear channel entry in instructions file, ensuring we only get
136 # one channel for the signer to look at. Then provide all the
137 # other details for this signing request to avoid any ambiguity
138 # and to avoid relying on encoding data into filenames.
139 for sect, fields in zip(('insns', 'general'), (sect_insns, sect_general)):
140 if not config.has_section(sect):
141 config.add_section(sect)
142 for k, v in fields.iteritems():
143 config.set(sect, k, v)
144
145 output = cStringIO.StringIO()
146 config.write(output)
147 data = output.getvalue()
148 osutils.WriteFile(output_file, data)
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700149 logging.debug('generated insns file for %s:\n%s', image_type, data)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400150
151
152def MarkImageToBeSigned(ctx, tbs_base, insns_path, priority):
153 """Mark an instructions file for signing.
154
155 This will upload a file to the GS bucket flagging an image for signing by
156 the signers.
157
158 Args:
159 ctx: A viable gs.GSContext.
160 tbs_base: The full path to where the tobesigned directory lives.
161 insns_path: The path (relative to |tbs_base|) of the file to sign.
162 priority: Set the signing priority (lower == higher prio).
163
164 Returns:
165 The full path to the remote tobesigned file.
166 """
167 if priority < 0 or priority > 99:
168 raise ValueError('priority must be [0, 99] inclusive')
169
170 if insns_path.startswith(tbs_base):
171 insns_path = insns_path[len(tbs_base):].lstrip('/')
172
173 tbs_path = '%s/tobesigned/%02i,%s' % (tbs_base, priority,
174 insns_path.replace('/', ','))
175
Mike Frysinger6430d132014-10-27 23:43:30 -0400176 # The caller will catch gs.GSContextException for us.
177 ctx.Copy('-', tbs_path, input=cros_build_lib.MachineDetails())
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400178
179 return tbs_path
180
181
182def PushImage(src_path, board, versionrev=None, profile=None, priority=50,
Mike Frysingerdad40d62014-02-09 02:18:02 -0500183 sign_types=None, dry_run=False, mock=False, force_keysets=()):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400184 """Push the image from the archive bucket to the release bucket.
185
186 Args:
187 src_path: Where to copy the files from; can be a local path or gs:// URL.
188 Should be a full path to the artifacts in either case.
189 board: The board we're uploading artifacts for (e.g. $BOARD).
190 versionrev: The full Chromium OS version string (e.g. R34-5126.0.0).
191 profile: The board profile in use (e.g. "asan").
192 priority: Set the signing priority (lower == higher prio).
193 sign_types: If set, a set of types which we'll restrict ourselves to
194 signing. See the --sign-types option for more details.
195 dry_run: Show what would be done, but do not upload anything.
196 mock: Upload to a testing bucket rather than the real one.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500197 force_keysets: Set of keysets to use rather than what the inputs say.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400198
199 Returns:
Don Garrett9459c2f2014-01-22 18:20:24 -0800200 A dictionary that maps 'channel' -> ['gs://signer_instruction_uri1',
201 'gs://signer_instruction_uri2',
202 ...]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400203 """
Mike Frysinger4495b032014-03-05 17:24:03 -0500204 # Whether we hit an unknown error. If so, we'll throw an error, but only
205 # at the end (so that we still upload as many files as possible).
Don Garrettfd97b402015-09-03 00:59:21 +0000206 unknown_error = False
Mike Frysinger4495b032014-03-05 17:24:03 -0500207
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400208 if versionrev is None:
209 # Extract milestone/version from the directory name.
210 versionrev = os.path.basename(src_path)
211
212 # We only support the latest format here. Older releases can use pushimage
213 # from the respective branch which deals with legacy cruft.
214 m = re.match(VERSION_REGEX, versionrev)
215 if not m:
216 raise ValueError('version %s does not match %s' %
217 (versionrev, VERSION_REGEX))
218 milestone = m.group(1)
219 version = m.group(2)
220
221 # Normalize board to always use dashes not underscores. This is mostly a
222 # historical artifact at this point, but we can't really break it since the
223 # value is used in URLs.
224 boardpath = board.replace('_', '-')
225 if profile is not None:
226 boardpath += '-%s' % profile.replace('_', '-')
227
228 ctx = gs.GSContext(dry_run=dry_run)
229
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400230 try:
231 input_insns = InputInsns(board)
232 except MissingBoardInstructions as e:
Ralph Nathan446aee92015-03-23 14:44:56 -0700233 logging.warning('board "%s" is missing base instruction file: %s', board, e)
234 logging.warning('not uploading anything for signing')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400235 return
236 channels = input_insns.GetChannels()
Mike Frysingerdad40d62014-02-09 02:18:02 -0500237
238 # We want force_keysets as a set, and keysets as a list.
239 force_keysets = set(force_keysets)
240 keysets = list(force_keysets) if force_keysets else input_insns.GetKeysets()
241
242 if mock:
Ralph Nathan03047282015-03-23 11:09:32 -0700243 logging.info('Upload mode: mock; signers will not process anything')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500244 tbs_base = gs_base = os.path.join(constants.TRASH_BUCKET, 'pushimage-tests',
245 getpass.getuser())
246 elif TEST_KEYSETS & force_keysets:
Ralph Nathan03047282015-03-23 11:09:32 -0700247 logging.info('Upload mode: test; signers will process test keys')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500248 # We need the tbs_base to be in the place the signer will actually scan.
249 tbs_base = TEST_SIGN_BUCKET_BASE
250 gs_base = os.path.join(tbs_base, getpass.getuser())
251 else:
Ralph Nathan03047282015-03-23 11:09:32 -0700252 logging.info('Upload mode: normal; signers will process the images')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500253 tbs_base = gs_base = constants.RELEASE_BUCKET
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400254
255 sect_general = {
256 'config_board': board,
257 'board': boardpath,
258 'version': version,
259 'versionrev': versionrev,
260 'milestone': milestone,
261 }
262 sect_insns = {}
263
264 if dry_run:
Ralph Nathan03047282015-03-23 11:09:32 -0700265 logging.info('DRY RUN MODE ACTIVE: NOTHING WILL BE UPLOADED')
266 logging.info('Signing for channels: %s', ' '.join(channels))
267 logging.info('Signing for keysets : %s', ' '.join(keysets))
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400268
Don Garrett9459c2f2014-01-22 18:20:24 -0800269 instruction_urls = {}
270
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400271 def _ImageNameBase(image_type=None):
272 lmid = ('%s-' % image_type) if image_type else ''
273 return 'ChromeOS-%s%s-%s' % (lmid, versionrev, boardpath)
274
275 for channel in channels:
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700276 logging.debug('\n\n#### CHANNEL: %s ####\n', channel)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400277 sect_insns['channel'] = channel
278 sub_path = '%s-channel/%s/%s' % (channel, boardpath, version)
279 dst_path = '%s/%s' % (gs_base, sub_path)
Ralph Nathan03047282015-03-23 11:09:32 -0700280 logging.info('Copying images to %s', dst_path)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400281
Don Garrettfd97b402015-09-03 00:59:21 +0000282 recovery_base = _ImageNameBase('recovery')
283 factory_base = _ImageNameBase('factory')
284 firmware_base = _ImageNameBase('firmware')
285 test_base = _ImageNameBase('test')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400286 hwqual_tarball = 'chromeos-hwqual-%s-%s.tar.bz2' % (board, versionrev)
287
Don Garrettfd97b402015-09-03 00:59:21 +0000288 # Upload all the files first before flagging them for signing.
289 files_to_copy = (
290 # pylint: disable=bad-whitespace
291 # <src> <dst>
292 # <signing type> <sfx>
293 ('recovery_image.tar.xz', recovery_base, 'tar.xz',
294 'recovery'),
295
296 ('factory_image.zip', factory_base, 'zip',
297 'factory'),
298
299 ('firmware_from_source.tar.bz2', firmware_base, 'tar.bz2',
300 'firmware'),
301
302 ('image.zip', _ImageNameBase(), 'zip', ''),
303 ('chromiumos_test_image.tar.xz', test_base, 'tar.xz', ''),
304 ('debug.tgz', 'debug-%s' % boardpath, 'tgz', ''),
305 (hwqual_tarball, '', '', ''),
306 ('au-generator.zip', '', '', ''),
307 ('stateful.tgz', '', '', ''),
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400308 )
Don Garrettfd97b402015-09-03 00:59:21 +0000309 files_to_sign = []
310 for src, dst, sfx, image_type in files_to_copy:
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400311 if not dst:
312 dst = src
Don Garrettfd97b402015-09-03 00:59:21 +0000313 elif sfx:
314 dst += '.%s' % sfx
Mike Frysingere51a2652014-01-18 02:36:16 -0500315 try:
316 ctx.Copy(os.path.join(src_path, src), os.path.join(dst_path, dst))
317 except gs.GSNoSuchKey:
Ralph Nathan446aee92015-03-23 14:44:56 -0700318 logging.warning('Skipping %s as it does not exist', src)
Don Garrettfd97b402015-09-03 00:59:21 +0000319 continue
Mike Frysinger4495b032014-03-05 17:24:03 -0500320 except gs.GSContextException:
Don Garrettfd97b402015-09-03 00:59:21 +0000321 unknown_error = True
Ralph Nathan59900422015-03-24 10:41:17 -0700322 logging.error('Skipping %s due to unknown GS error', src, exc_info=True)
Don Garrettfd97b402015-09-03 00:59:21 +0000323 continue
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400324
Don Garrettfd97b402015-09-03 00:59:21 +0000325 if image_type:
326 dst_base = dst[:-(len(sfx) + 1)]
327 assert dst == '%s.%s' % (dst_base, sfx)
328 files_to_sign += [[image_type, dst_base, '.%s' % sfx]]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400329
330 # Now go through the subset for signing.
331 for keyset in keysets:
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700332 logging.debug('\n\n#### KEYSET: %s ####\n', keyset)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400333 sect_insns['keyset'] = keyset
334 for image_type, dst_name, suffix in files_to_sign:
Don Garrettfd97b402015-09-03 00:59:21 +0000335 dst_archive = '%s%s' % (dst_name, suffix)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400336 sect_general['archive'] = dst_archive
337 sect_general['type'] = image_type
338
Don Garrettfd97b402015-09-03 00:59:21 +0000339 # See if the caller has requested we only sign certain types.
340 if sign_types:
341 if not image_type in sign_types:
342 logging.info('Skipping %s signing as it was not requested',
343 image_type)
344 continue
345 else:
346 # In the default/automatic mode, only flag files for signing if the
347 # archives were actually uploaded in a previous stage.
348 gs_artifact_path = os.path.join(dst_path, dst_archive)
349 try:
350 exists = ctx.Exists(gs_artifact_path)
351 except gs.GSContextException:
352 unknown_error = True
353 exists = False
354 logging.error('Unknown error while checking %s', gs_artifact_path,
355 exc_info=True)
356 if not exists:
357 logging.info('%s does not exist. Nothing to sign.',
358 gs_artifact_path)
359 continue
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400360
361 input_insn_path = input_insns.GetInsnFile(image_type)
362 if not os.path.exists(input_insn_path):
Ralph Nathan03047282015-03-23 11:09:32 -0700363 logging.info('%s does not exist. Nothing to sign.', input_insn_path)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400364 continue
365
366 # Generate the insn file for this artifact that the signer will use,
367 # and flag it for signing.
368 with tempfile.NamedTemporaryFile(
369 bufsize=0, prefix='pushimage.insns.') as insns_path:
370 input_insns.OutputInsns(image_type, insns_path.name, sect_insns,
371 sect_general)
372
373 gs_insns_path = '%s/%s' % (dst_path, dst_name)
374 if keyset != keysets[0]:
375 gs_insns_path += '-%s' % keyset
376 gs_insns_path += '.instructions'
377
Mike Frysinger4495b032014-03-05 17:24:03 -0500378 try:
379 ctx.Copy(insns_path.name, gs_insns_path)
380 except gs.GSContextException:
Don Garrettfd97b402015-09-03 00:59:21 +0000381 unknown_error = True
Ralph Nathan59900422015-03-24 10:41:17 -0700382 logging.error('Unknown error while uploading insns %s',
383 gs_insns_path, exc_info=True)
Mike Frysinger4495b032014-03-05 17:24:03 -0500384 continue
385
386 try:
387 MarkImageToBeSigned(ctx, tbs_base, gs_insns_path, priority)
388 except gs.GSContextException:
Don Garrettfd97b402015-09-03 00:59:21 +0000389 unknown_error = True
Ralph Nathan59900422015-03-24 10:41:17 -0700390 logging.error('Unknown error while marking for signing %s',
391 gs_insns_path, exc_info=True)
Mike Frysinger4495b032014-03-05 17:24:03 -0500392 continue
Ralph Nathan03047282015-03-23 11:09:32 -0700393 logging.info('Signing %s image %s', image_type, gs_insns_path)
Don Garrett9459c2f2014-01-22 18:20:24 -0800394 instruction_urls.setdefault(channel, []).append(gs_insns_path)
395
Don Garrettfd97b402015-09-03 00:59:21 +0000396 if unknown_error:
Mike Frysinger4495b032014-03-05 17:24:03 -0500397 raise PushError('hit some unknown error(s)', instruction_urls)
398
Don Garrett9459c2f2014-01-22 18:20:24 -0800399 return instruction_urls
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400400
401
402def main(argv):
403 parser = commandline.ArgumentParser(description=__doc__)
404
405 # The type of image_dir will strip off trailing slashes (makes later
406 # processing simpler and the display prettier).
407 parser.add_argument('image_dir', default=None, type='local_or_gs_path',
408 help='full path of source artifacts to upload')
409 parser.add_argument('--board', default=None, required=True,
410 help='board to generate symbols for')
411 parser.add_argument('--profile', default=None,
412 help='board profile in use (e.g. "asan")')
413 parser.add_argument('--version', default=None,
414 help='version info (normally extracted from image_dir)')
415 parser.add_argument('-n', '--dry-run', default=False, action='store_true',
416 help='show what would be done, but do not upload')
417 parser.add_argument('-M', '--mock', default=False, action='store_true',
418 help='upload things to a testing bucket (dev testing)')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500419 parser.add_argument('--test-sign-mp', default=False, action='store_true',
420 help='mung signing behavior to sign w/test mp keys')
421 parser.add_argument('--test-sign-premp', default=False, action='store_true',
422 help='mung signing behavior to sign w/test premp keys')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400423 parser.add_argument('--priority', type=int, default=50,
424 help='set signing priority (lower == higher prio)')
425 parser.add_argument('--sign-types', default=None, nargs='+',
Don Garrettfd97b402015-09-03 00:59:21 +0000426 choices=('recovery', 'factory', 'firmware'),
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400427 help='only sign specified image types')
Mike Frysinger09fe0122014-02-09 02:44:05 -0500428 parser.add_argument('--yes', action='store_true', default=False,
429 help='answer yes to all prompts')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400430
431 opts = parser.parse_args(argv)
432 opts.Freeze()
433
Mike Frysingerdad40d62014-02-09 02:18:02 -0500434 force_keysets = set()
435 if opts.test_sign_mp:
436 force_keysets.add('test-keys-mp')
437 if opts.test_sign_premp:
438 force_keysets.add('test-keys-premp')
439
Mike Frysinger09fe0122014-02-09 02:44:05 -0500440 # If we aren't using mock or test or dry run mode, then let's prompt the user
441 # to make sure they actually want to do this. It's rare that people want to
442 # run this directly and hit the release bucket.
443 if not (opts.mock or force_keysets or opts.dry_run) and not opts.yes:
444 prolog = '\n'.join(textwrap.wrap(textwrap.dedent(
445 'Uploading images for signing to the *release* bucket is not something '
446 'you generally should be doing yourself.'), 80)).strip()
447 if not cros_build_lib.BooleanPrompt(
448 prompt='Are you sure you want to sign these images',
449 default=False, prolog=prolog):
450 cros_build_lib.Die('better safe than sorry')
451
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400452 PushImage(opts.image_dir, opts.board, versionrev=opts.version,
453 profile=opts.profile, priority=opts.priority,
Mike Frysingerdad40d62014-02-09 02:18:02 -0500454 sign_types=opts.sign_types, dry_run=opts.dry_run, mock=opts.mock,
455 force_keysets=force_keysets)