blob: 36977f9636f567e4c692cd3549f1ef0b421d5ace [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
15import errno
16import 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
Mike Frysingerd13faeb2013-09-05 16:00:46 -040025from chromite.lib import gs
26from chromite.lib import osutils
27from chromite.lib import signing
28
29
30# This will split a fully qualified ChromeOS version string up.
31# R34-5126.0.0 will break into "34" and "5126.0.0".
32VERSION_REGEX = r'^R([0-9]+)-([^-]+)'
33
Mike Frysingerdad40d62014-02-09 02:18:02 -050034# The test signers will scan this dir looking for test work.
35# Keep it in sync with the signer config files [gs_test_buckets].
36TEST_SIGN_BUCKET_BASE = 'gs://chromeos-throw-away-bucket/signer-tests'
37
38# Ketsets that are only valid in the above test bucket.
39TEST_KEYSETS = set(('test-keys-mp', 'test-keys-premp'))
40
Mike Frysingerd13faeb2013-09-05 16:00:46 -040041
Mike Frysinger4495b032014-03-05 17:24:03 -050042class PushError(Exception):
43 """When an (unknown) error happened while trying to push artifacts."""
44
45
Mike Frysingerd13faeb2013-09-05 16:00:46 -040046class MissingBoardInstructions(Exception):
47 """Raised when a board lacks any signer instructions."""
48
49
50class InputInsns(object):
51 """Object to hold settings for a signable board.
52
53 Note: The format of the instruction file pushimage outputs (and the signer
54 reads) is not exactly the same as the instruction file pushimage reads.
55 """
56
57 def __init__(self, board):
58 self.board = board
59
60 config = ConfigParser.ConfigParser()
61 config.readfp(open(self.GetInsnFile('DEFAULT')))
62 try:
63 input_insn = self.GetInsnFile('recovery')
64 config.readfp(open(input_insn))
65 except IOError as e:
66 if e.errno == errno.ENOENT:
67 # This board doesn't have any signing instructions.
68 # This is normal for new or experimental boards.
69 raise MissingBoardInstructions(input_insn)
70 raise
71 self.cfg = config
72
73 def GetInsnFile(self, image_type):
74 """Find the signer instruction files for this board/image type.
75
76 Args:
77 image_type: The type of instructions to load. It can be a common file
78 (like "DEFAULT"), or one of the --sign-types.
79
80 Returns:
81 Full path to the instruction file using |image_type| and |self.board|.
82 """
83 if image_type == image_type.upper():
84 name = image_type
85 elif image_type == 'recovery':
86 name = self.board
87 else:
88 name = '%s.%s' % (self.board, image_type)
89
90 return os.path.join(signing.INPUT_INSN_DIR, '%s.instructions' % name)
91
92 @staticmethod
93 def SplitCfgField(val):
94 """Split a string into multiple elements.
95
96 This centralizes our convention for multiple elements in the input files
97 being delimited by either a space or comma.
98
99 Args:
100 val: The string to split.
101
102 Returns:
103 The list of elements from having done split the string.
104 """
105 return val.replace(',', ' ').split()
106
107 def GetChannels(self):
108 """Return the list of channels to sign for this board.
109
110 If the board-specific config doesn't specify a preference, we'll use the
111 common settings.
112 """
113 return self.SplitCfgField(self.cfg.get('insns', 'channel'))
114
115 def GetKeysets(self):
116 """Return the list of keysets to sign for this board."""
117 return self.SplitCfgField(self.cfg.get('insns', 'keyset'))
118
119 def OutputInsns(self, image_type, output_file, sect_insns, sect_general):
120 """Generate the output instruction file for sending to the signer.
121
122 Note: The format of the instruction file pushimage outputs (and the signer
123 reads) is not exactly the same as the instruction file pushimage reads.
124
125 Args:
126 image_type: The type of image we will be signing (see --sign-types).
127 output_file: The file to write the new instruction file to.
128 sect_insns: Items to set/override in the [insns] section.
129 sect_general: Items to set/override in the [general] section.
130 """
131 config = ConfigParser.ConfigParser()
132 config.readfp(open(self.GetInsnFile(image_type)))
133
134 # Clear channel entry in instructions file, ensuring we only get
135 # one channel for the signer to look at. Then provide all the
136 # other details for this signing request to avoid any ambiguity
137 # and to avoid relying on encoding data into filenames.
138 for sect, fields in zip(('insns', 'general'), (sect_insns, sect_general)):
139 if not config.has_section(sect):
140 config.add_section(sect)
141 for k, v in fields.iteritems():
142 config.set(sect, k, v)
143
144 output = cStringIO.StringIO()
145 config.write(output)
146 data = output.getvalue()
147 osutils.WriteFile(output_file, data)
148 cros_build_lib.Debug('generated insns file for %s:\n%s', image_type, data)
149
150
151def MarkImageToBeSigned(ctx, tbs_base, insns_path, priority):
152 """Mark an instructions file for signing.
153
154 This will upload a file to the GS bucket flagging an image for signing by
155 the signers.
156
157 Args:
158 ctx: A viable gs.GSContext.
159 tbs_base: The full path to where the tobesigned directory lives.
160 insns_path: The path (relative to |tbs_base|) of the file to sign.
161 priority: Set the signing priority (lower == higher prio).
162
163 Returns:
164 The full path to the remote tobesigned file.
165 """
166 if priority < 0 or priority > 99:
167 raise ValueError('priority must be [0, 99] inclusive')
168
169 if insns_path.startswith(tbs_base):
170 insns_path = insns_path[len(tbs_base):].lstrip('/')
171
172 tbs_path = '%s/tobesigned/%02i,%s' % (tbs_base, priority,
173 insns_path.replace('/', ','))
174
Mike Frysinger6430d132014-10-27 23:43:30 -0400175 # The caller will catch gs.GSContextException for us.
176 ctx.Copy('-', tbs_path, input=cros_build_lib.MachineDetails())
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400177
178 return tbs_path
179
180
181def PushImage(src_path, board, versionrev=None, profile=None, priority=50,
Mike Frysingerdad40d62014-02-09 02:18:02 -0500182 sign_types=None, dry_run=False, mock=False, force_keysets=()):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400183 """Push the image from the archive bucket to the release bucket.
184
185 Args:
186 src_path: Where to copy the files from; can be a local path or gs:// URL.
187 Should be a full path to the artifacts in either case.
188 board: The board we're uploading artifacts for (e.g. $BOARD).
189 versionrev: The full Chromium OS version string (e.g. R34-5126.0.0).
190 profile: The board profile in use (e.g. "asan").
191 priority: Set the signing priority (lower == higher prio).
192 sign_types: If set, a set of types which we'll restrict ourselves to
193 signing. See the --sign-types option for more details.
194 dry_run: Show what would be done, but do not upload anything.
195 mock: Upload to a testing bucket rather than the real one.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500196 force_keysets: Set of keysets to use rather than what the inputs say.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400197
198 Returns:
Don Garrett9459c2f2014-01-22 18:20:24 -0800199 A dictionary that maps 'channel' -> ['gs://signer_instruction_uri1',
200 'gs://signer_instruction_uri2',
201 ...]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400202 """
Mike Frysinger4495b032014-03-05 17:24:03 -0500203 # Whether we hit an unknown error. If so, we'll throw an error, but only
204 # at the end (so that we still upload as many files as possible).
205 unknown_error = False
206
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400207 if versionrev is None:
208 # Extract milestone/version from the directory name.
209 versionrev = os.path.basename(src_path)
210
211 # We only support the latest format here. Older releases can use pushimage
212 # from the respective branch which deals with legacy cruft.
213 m = re.match(VERSION_REGEX, versionrev)
214 if not m:
215 raise ValueError('version %s does not match %s' %
216 (versionrev, VERSION_REGEX))
217 milestone = m.group(1)
218 version = m.group(2)
219
220 # Normalize board to always use dashes not underscores. This is mostly a
221 # historical artifact at this point, but we can't really break it since the
222 # value is used in URLs.
223 boardpath = board.replace('_', '-')
224 if profile is not None:
225 boardpath += '-%s' % profile.replace('_', '-')
226
227 ctx = gs.GSContext(dry_run=dry_run)
228
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400229 try:
230 input_insns = InputInsns(board)
231 except MissingBoardInstructions as e:
232 cros_build_lib.Warning('board "%s" is missing base instruction file: %s',
233 board, e)
234 cros_build_lib.Warning('not uploading anything for signing')
235 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:
243 cros_build_lib.Info('Upload mode: mock; signers will not process anything')
244 tbs_base = gs_base = os.path.join(constants.TRASH_BUCKET, 'pushimage-tests',
245 getpass.getuser())
246 elif TEST_KEYSETS & force_keysets:
247 cros_build_lib.Info('Upload mode: test; signers will process test keys')
248 # 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:
252 cros_build_lib.Info('Upload mode: normal; signers will process the images')
253 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:
265 cros_build_lib.Info('DRY RUN MODE ACTIVE: NOTHING WILL BE UPLOADED')
266 cros_build_lib.Info('Signing for channels: %s', ' '.join(channels))
267 cros_build_lib.Info('Signing for keysets : %s', ' '.join(keysets))
268
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:
276 cros_build_lib.Debug('\n\n#### CHANNEL: %s ####\n', channel)
277 sect_insns['channel'] = channel
278 sub_path = '%s-channel/%s/%s' % (channel, boardpath, version)
279 dst_path = '%s/%s' % (gs_base, sub_path)
280 cros_build_lib.Info('Copying images to %s', dst_path)
281
282 recovery_base = _ImageNameBase('recovery')
283 factory_base = _ImageNameBase('factory')
284 firmware_base = _ImageNameBase('firmware')
285 test_base = _ImageNameBase('test')
286 hwqual_tarball = 'chromeos-hwqual-%s-%s.tar.bz2' % (board, versionrev)
287
288 # Upload all the files first before flagging them for signing.
289 files_to_copy = (
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500290 # pylint: disable=bad-whitespace
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400291 # <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 )
308 files_to_sign = []
309 for src, dst, sfx, image_type in files_to_copy:
310 if not dst:
311 dst = src
312 elif sfx:
313 dst += '.%s' % sfx
Mike Frysingere51a2652014-01-18 02:36:16 -0500314 try:
315 ctx.Copy(os.path.join(src_path, src), os.path.join(dst_path, dst))
316 except gs.GSNoSuchKey:
317 cros_build_lib.Warning('Skipping %s as it does not exist', src)
318 continue
Mike Frysinger4495b032014-03-05 17:24:03 -0500319 except gs.GSContextException:
320 unknown_error = True
321 cros_build_lib.Error('Skipping %s due to unknown GS error', src,
322 exc_info=True)
323 continue
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400324
325 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]]
329
330 # Now go through the subset for signing.
331 for keyset in keysets:
332 cros_build_lib.Debug('\n\n#### KEYSET: %s ####\n', keyset)
333 sect_insns['keyset'] = keyset
334 for image_type, dst_name, suffix in files_to_sign:
335 dst_archive = '%s%s' % (dst_name, suffix)
336 sect_general['archive'] = dst_archive
337 sect_general['type'] = image_type
338
339 # See if the caller has requested we only sign certain types.
340 if sign_types:
341 if not image_type in sign_types:
342 cros_build_lib.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)
Mike Frysinger4495b032014-03-05 17:24:03 -0500349 try:
350 exists = ctx.Exists(gs_artifact_path)
351 except gs.GSContextException:
352 unknown_error = True
353 exists = False
354 cros_build_lib.Error('Unknown error while checking %s',
355 gs_artifact_path, exc_info=True)
356 if not exists:
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400357 cros_build_lib.Info('%s does not exist. Nothing to sign.',
358 gs_artifact_path)
359 continue
360
361 input_insn_path = input_insns.GetInsnFile(image_type)
362 if not os.path.exists(input_insn_path):
363 cros_build_lib.Info('%s does not exist. Nothing to sign.',
364 input_insn_path)
365 continue
366
367 # Generate the insn file for this artifact that the signer will use,
368 # and flag it for signing.
369 with tempfile.NamedTemporaryFile(
370 bufsize=0, prefix='pushimage.insns.') as insns_path:
371 input_insns.OutputInsns(image_type, insns_path.name, sect_insns,
372 sect_general)
373
374 gs_insns_path = '%s/%s' % (dst_path, dst_name)
375 if keyset != keysets[0]:
376 gs_insns_path += '-%s' % keyset
377 gs_insns_path += '.instructions'
378
Mike Frysinger4495b032014-03-05 17:24:03 -0500379 try:
380 ctx.Copy(insns_path.name, gs_insns_path)
381 except gs.GSContextException:
382 unknown_error = True
383 cros_build_lib.Error('Unknown error while uploading insns %s',
384 gs_insns_path, exc_info=True)
385 continue
386
387 try:
388 MarkImageToBeSigned(ctx, tbs_base, gs_insns_path, priority)
389 except gs.GSContextException:
390 unknown_error = True
391 cros_build_lib.Error('Unknown error while marking for signing %s',
392 gs_insns_path, exc_info=True)
393 continue
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400394 cros_build_lib.Info('Signing %s image %s', image_type, gs_insns_path)
Don Garrett9459c2f2014-01-22 18:20:24 -0800395 instruction_urls.setdefault(channel, []).append(gs_insns_path)
396
Mike Frysinger4495b032014-03-05 17:24:03 -0500397 if unknown_error:
398 raise PushError('hit some unknown error(s)', instruction_urls)
399
Don Garrett9459c2f2014-01-22 18:20:24 -0800400 return instruction_urls
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400401
402
403def main(argv):
404 parser = commandline.ArgumentParser(description=__doc__)
405
406 # The type of image_dir will strip off trailing slashes (makes later
407 # processing simpler and the display prettier).
408 parser.add_argument('image_dir', default=None, type='local_or_gs_path',
409 help='full path of source artifacts to upload')
410 parser.add_argument('--board', default=None, required=True,
411 help='board to generate symbols for')
412 parser.add_argument('--profile', default=None,
413 help='board profile in use (e.g. "asan")')
414 parser.add_argument('--version', default=None,
415 help='version info (normally extracted from image_dir)')
416 parser.add_argument('-n', '--dry-run', default=False, action='store_true',
417 help='show what would be done, but do not upload')
418 parser.add_argument('-M', '--mock', default=False, action='store_true',
419 help='upload things to a testing bucket (dev testing)')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500420 parser.add_argument('--test-sign-mp', default=False, action='store_true',
421 help='mung signing behavior to sign w/test mp keys')
422 parser.add_argument('--test-sign-premp', default=False, action='store_true',
423 help='mung signing behavior to sign w/test premp keys')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400424 parser.add_argument('--priority', type=int, default=50,
425 help='set signing priority (lower == higher prio)')
426 parser.add_argument('--sign-types', default=None, nargs='+',
427 choices=('recovery', 'factory', 'firmware'),
428 help='only sign specified image types')
Mike Frysinger09fe0122014-02-09 02:44:05 -0500429 parser.add_argument('--yes', action='store_true', default=False,
430 help='answer yes to all prompts')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400431
432 opts = parser.parse_args(argv)
433 opts.Freeze()
434
Mike Frysingerdad40d62014-02-09 02:18:02 -0500435 force_keysets = set()
436 if opts.test_sign_mp:
437 force_keysets.add('test-keys-mp')
438 if opts.test_sign_premp:
439 force_keysets.add('test-keys-premp')
440
Mike Frysinger09fe0122014-02-09 02:44:05 -0500441 # If we aren't using mock or test or dry run mode, then let's prompt the user
442 # to make sure they actually want to do this. It's rare that people want to
443 # run this directly and hit the release bucket.
444 if not (opts.mock or force_keysets or opts.dry_run) and not opts.yes:
445 prolog = '\n'.join(textwrap.wrap(textwrap.dedent(
446 'Uploading images for signing to the *release* bucket is not something '
447 'you generally should be doing yourself.'), 80)).strip()
448 if not cros_build_lib.BooleanPrompt(
449 prompt='Are you sure you want to sign these images',
450 default=False, prolog=prolog):
451 cros_build_lib.Die('better safe than sorry')
452
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400453 PushImage(opts.image_dir, opts.board, versionrev=opts.version,
454 profile=opts.profile, priority=opts.priority,
Mike Frysingerdad40d62014-02-09 02:18:02 -0500455 sign_types=opts.sign_types, dry_run=opts.dry_run, mock=opts.mock,
456 force_keysets=force_keysets)