blob: 23af7f15bf1d4603f31295a958b8314fe2094473 [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
22from chromite.buildbot import constants
23from chromite.lib import commandline
24from chromite.lib import cros_build_lib
25from chromite.lib import git
26from 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
43class MissingBoardInstructions(Exception):
44 """Raised when a board lacks any signer instructions."""
45
46
47class InputInsns(object):
48 """Object to hold settings for a signable board.
49
50 Note: The format of the instruction file pushimage outputs (and the signer
51 reads) is not exactly the same as the instruction file pushimage reads.
52 """
53
54 def __init__(self, board):
55 self.board = board
56
57 config = ConfigParser.ConfigParser()
58 config.readfp(open(self.GetInsnFile('DEFAULT')))
59 try:
60 input_insn = self.GetInsnFile('recovery')
61 config.readfp(open(input_insn))
62 except IOError as e:
63 if e.errno == errno.ENOENT:
64 # This board doesn't have any signing instructions.
65 # This is normal for new or experimental boards.
66 raise MissingBoardInstructions(input_insn)
67 raise
68 self.cfg = config
69
70 def GetInsnFile(self, image_type):
71 """Find the signer instruction files for this board/image type.
72
73 Args:
74 image_type: The type of instructions to load. It can be a common file
75 (like "DEFAULT"), or one of the --sign-types.
76
77 Returns:
78 Full path to the instruction file using |image_type| and |self.board|.
79 """
80 if image_type == image_type.upper():
81 name = image_type
82 elif image_type == 'recovery':
83 name = self.board
84 else:
85 name = '%s.%s' % (self.board, image_type)
86
87 return os.path.join(signing.INPUT_INSN_DIR, '%s.instructions' % name)
88
89 @staticmethod
90 def SplitCfgField(val):
91 """Split a string into multiple elements.
92
93 This centralizes our convention for multiple elements in the input files
94 being delimited by either a space or comma.
95
96 Args:
97 val: The string to split.
98
99 Returns:
100 The list of elements from having done split the string.
101 """
102 return val.replace(',', ' ').split()
103
104 def GetChannels(self):
105 """Return the list of channels to sign for this board.
106
107 If the board-specific config doesn't specify a preference, we'll use the
108 common settings.
109 """
110 return self.SplitCfgField(self.cfg.get('insns', 'channel'))
111
112 def GetKeysets(self):
113 """Return the list of keysets to sign for this board."""
114 return self.SplitCfgField(self.cfg.get('insns', 'keyset'))
115
116 def OutputInsns(self, image_type, output_file, sect_insns, sect_general):
117 """Generate the output instruction file for sending to the signer.
118
119 Note: The format of the instruction file pushimage outputs (and the signer
120 reads) is not exactly the same as the instruction file pushimage reads.
121
122 Args:
123 image_type: The type of image we will be signing (see --sign-types).
124 output_file: The file to write the new instruction file to.
125 sect_insns: Items to set/override in the [insns] section.
126 sect_general: Items to set/override in the [general] section.
127 """
128 config = ConfigParser.ConfigParser()
129 config.readfp(open(self.GetInsnFile(image_type)))
130
131 # Clear channel entry in instructions file, ensuring we only get
132 # one channel for the signer to look at. Then provide all the
133 # other details for this signing request to avoid any ambiguity
134 # and to avoid relying on encoding data into filenames.
135 for sect, fields in zip(('insns', 'general'), (sect_insns, sect_general)):
136 if not config.has_section(sect):
137 config.add_section(sect)
138 for k, v in fields.iteritems():
139 config.set(sect, k, v)
140
141 output = cStringIO.StringIO()
142 config.write(output)
143 data = output.getvalue()
144 osutils.WriteFile(output_file, data)
145 cros_build_lib.Debug('generated insns file for %s:\n%s', image_type, data)
146
147
148def MarkImageToBeSigned(ctx, tbs_base, insns_path, priority):
149 """Mark an instructions file for signing.
150
151 This will upload a file to the GS bucket flagging an image for signing by
152 the signers.
153
154 Args:
155 ctx: A viable gs.GSContext.
156 tbs_base: The full path to where the tobesigned directory lives.
157 insns_path: The path (relative to |tbs_base|) of the file to sign.
158 priority: Set the signing priority (lower == higher prio).
159
160 Returns:
161 The full path to the remote tobesigned file.
162 """
163 if priority < 0 or priority > 99:
164 raise ValueError('priority must be [0, 99] inclusive')
165
166 if insns_path.startswith(tbs_base):
167 insns_path = insns_path[len(tbs_base):].lstrip('/')
168
169 tbs_path = '%s/tobesigned/%02i,%s' % (tbs_base, priority,
170 insns_path.replace('/', ','))
171
172 with tempfile.NamedTemporaryFile(
173 bufsize=0, prefix='pushimage.tbs.') as temp_tbs_file:
174 lines = [
175 'PROG=%s' % __file__,
176 'USER=%s' % getpass.getuser(),
177 'HOSTNAME=%s' % cros_build_lib.GetHostName(fully_qualified=True),
Mike Frysinger6791b1d2014-03-04 20:52:22 -0500178 'GIT_REV=%s' % git.RunGit(constants.CHROMITE_DIR,
179 ['rev-parse', 'HEAD']).output.rstrip(),
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400180 ]
Mike Frysinger6791b1d2014-03-04 20:52:22 -0500181 osutils.WriteFile(temp_tbs_file.name, '\n'.join(lines) + '\n')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400182 ctx.Copy(temp_tbs_file.name, tbs_path)
183
184 return tbs_path
185
186
187def PushImage(src_path, board, versionrev=None, profile=None, priority=50,
Mike Frysingerdad40d62014-02-09 02:18:02 -0500188 sign_types=None, dry_run=False, mock=False, force_keysets=()):
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400189 """Push the image from the archive bucket to the release bucket.
190
191 Args:
192 src_path: Where to copy the files from; can be a local path or gs:// URL.
193 Should be a full path to the artifacts in either case.
194 board: The board we're uploading artifacts for (e.g. $BOARD).
195 versionrev: The full Chromium OS version string (e.g. R34-5126.0.0).
196 profile: The board profile in use (e.g. "asan").
197 priority: Set the signing priority (lower == higher prio).
198 sign_types: If set, a set of types which we'll restrict ourselves to
199 signing. See the --sign-types option for more details.
200 dry_run: Show what would be done, but do not upload anything.
201 mock: Upload to a testing bucket rather than the real one.
Mike Frysingerdad40d62014-02-09 02:18:02 -0500202 force_keysets: Set of keysets to use rather than what the inputs say.
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400203
204 Returns:
Don Garrett9459c2f2014-01-22 18:20:24 -0800205 A dictionary that maps 'channel' -> ['gs://signer_instruction_uri1',
206 'gs://signer_instruction_uri2',
207 ...]
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400208 """
209 if versionrev is None:
210 # Extract milestone/version from the directory name.
211 versionrev = os.path.basename(src_path)
212
213 # We only support the latest format here. Older releases can use pushimage
214 # from the respective branch which deals with legacy cruft.
215 m = re.match(VERSION_REGEX, versionrev)
216 if not m:
217 raise ValueError('version %s does not match %s' %
218 (versionrev, VERSION_REGEX))
219 milestone = m.group(1)
220 version = m.group(2)
221
222 # Normalize board to always use dashes not underscores. This is mostly a
223 # historical artifact at this point, but we can't really break it since the
224 # value is used in URLs.
225 boardpath = board.replace('_', '-')
226 if profile is not None:
227 boardpath += '-%s' % profile.replace('_', '-')
228
229 ctx = gs.GSContext(dry_run=dry_run)
230
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400231 try:
232 input_insns = InputInsns(board)
233 except MissingBoardInstructions as e:
234 cros_build_lib.Warning('board "%s" is missing base instruction file: %s',
235 board, e)
236 cros_build_lib.Warning('not uploading anything for signing')
237 return
238 channels = input_insns.GetChannels()
Mike Frysingerdad40d62014-02-09 02:18:02 -0500239
240 # We want force_keysets as a set, and keysets as a list.
241 force_keysets = set(force_keysets)
242 keysets = list(force_keysets) if force_keysets else input_insns.GetKeysets()
243
244 if mock:
245 cros_build_lib.Info('Upload mode: mock; signers will not process anything')
246 tbs_base = gs_base = os.path.join(constants.TRASH_BUCKET, 'pushimage-tests',
247 getpass.getuser())
248 elif TEST_KEYSETS & force_keysets:
249 cros_build_lib.Info('Upload mode: test; signers will process test keys')
250 # We need the tbs_base to be in the place the signer will actually scan.
251 tbs_base = TEST_SIGN_BUCKET_BASE
252 gs_base = os.path.join(tbs_base, getpass.getuser())
253 else:
254 cros_build_lib.Info('Upload mode: normal; signers will process the images')
255 tbs_base = gs_base = constants.RELEASE_BUCKET
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400256
257 sect_general = {
258 'config_board': board,
259 'board': boardpath,
260 'version': version,
261 'versionrev': versionrev,
262 'milestone': milestone,
263 }
264 sect_insns = {}
265
266 if dry_run:
267 cros_build_lib.Info('DRY RUN MODE ACTIVE: NOTHING WILL BE UPLOADED')
268 cros_build_lib.Info('Signing for channels: %s', ' '.join(channels))
269 cros_build_lib.Info('Signing for keysets : %s', ' '.join(keysets))
270
Don Garrett9459c2f2014-01-22 18:20:24 -0800271 instruction_urls = {}
272
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400273 def _ImageNameBase(image_type=None):
274 lmid = ('%s-' % image_type) if image_type else ''
275 return 'ChromeOS-%s%s-%s' % (lmid, versionrev, boardpath)
276
277 for channel in channels:
278 cros_build_lib.Debug('\n\n#### CHANNEL: %s ####\n', channel)
279 sect_insns['channel'] = channel
280 sub_path = '%s-channel/%s/%s' % (channel, boardpath, version)
281 dst_path = '%s/%s' % (gs_base, sub_path)
282 cros_build_lib.Info('Copying images to %s', dst_path)
283
284 recovery_base = _ImageNameBase('recovery')
285 factory_base = _ImageNameBase('factory')
286 firmware_base = _ImageNameBase('firmware')
287 test_base = _ImageNameBase('test')
288 hwqual_tarball = 'chromeos-hwqual-%s-%s.tar.bz2' % (board, versionrev)
289
290 # Upload all the files first before flagging them for signing.
291 files_to_copy = (
292 # <src> <dst>
293 # <signing type> <sfx>
294 ('recovery_image.tar.xz', recovery_base, 'tar.xz',
295 'recovery'),
296
297 ('factory_image.zip', factory_base, 'zip',
298 'factory'),
299
300 ('firmware_from_source.tar.bz2', firmware_base, 'tar.bz2',
301 'firmware'),
302
303 ('image.zip', _ImageNameBase(), 'zip', ''),
304 ('chromiumos_test_image.tar.xz', test_base, 'tar.xz', ''),
305 ('debug.tgz', 'debug-%s' % boardpath, 'tgz', ''),
306 (hwqual_tarball, '', '', ''),
307 ('au-generator.zip', '', '', ''),
308 )
309 files_to_sign = []
310 for src, dst, sfx, image_type in files_to_copy:
311 if not dst:
312 dst = src
313 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:
318 cros_build_lib.Warning('Skipping %s as it does not exist', src)
319 continue
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400320
321 if image_type:
322 dst_base = dst[:-(len(sfx) + 1)]
323 assert dst == '%s.%s' % (dst_base, sfx)
324 files_to_sign += [[image_type, dst_base, '.%s' % sfx]]
325
326 # Now go through the subset for signing.
327 for keyset in keysets:
328 cros_build_lib.Debug('\n\n#### KEYSET: %s ####\n', keyset)
329 sect_insns['keyset'] = keyset
330 for image_type, dst_name, suffix in files_to_sign:
331 dst_archive = '%s%s' % (dst_name, suffix)
332 sect_general['archive'] = dst_archive
333 sect_general['type'] = image_type
334
335 # See if the caller has requested we only sign certain types.
336 if sign_types:
337 if not image_type in sign_types:
338 cros_build_lib.Info('Skipping %s signing as it was not requested',
339 image_type)
340 continue
341 else:
342 # In the default/automatic mode, only flag files for signing if the
343 # archives were actually uploaded in a previous stage.
344 gs_artifact_path = os.path.join(dst_path, dst_archive)
345 if not ctx.Exists(gs_artifact_path):
346 cros_build_lib.Info('%s does not exist. Nothing to sign.',
347 gs_artifact_path)
348 continue
349
350 input_insn_path = input_insns.GetInsnFile(image_type)
351 if not os.path.exists(input_insn_path):
352 cros_build_lib.Info('%s does not exist. Nothing to sign.',
353 input_insn_path)
354 continue
355
356 # Generate the insn file for this artifact that the signer will use,
357 # and flag it for signing.
358 with tempfile.NamedTemporaryFile(
359 bufsize=0, prefix='pushimage.insns.') as insns_path:
360 input_insns.OutputInsns(image_type, insns_path.name, sect_insns,
361 sect_general)
362
363 gs_insns_path = '%s/%s' % (dst_path, dst_name)
364 if keyset != keysets[0]:
365 gs_insns_path += '-%s' % keyset
366 gs_insns_path += '.instructions'
367
368 ctx.Copy(insns_path.name, gs_insns_path)
Mike Frysingerdad40d62014-02-09 02:18:02 -0500369 MarkImageToBeSigned(ctx, tbs_base, gs_insns_path, priority)
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400370 cros_build_lib.Info('Signing %s image %s', image_type, gs_insns_path)
Don Garrett9459c2f2014-01-22 18:20:24 -0800371 instruction_urls.setdefault(channel, []).append(gs_insns_path)
372
373 return instruction_urls
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400374
375
376def main(argv):
377 parser = commandline.ArgumentParser(description=__doc__)
378
379 # The type of image_dir will strip off trailing slashes (makes later
380 # processing simpler and the display prettier).
381 parser.add_argument('image_dir', default=None, type='local_or_gs_path',
382 help='full path of source artifacts to upload')
383 parser.add_argument('--board', default=None, required=True,
384 help='board to generate symbols for')
385 parser.add_argument('--profile', default=None,
386 help='board profile in use (e.g. "asan")')
387 parser.add_argument('--version', default=None,
388 help='version info (normally extracted from image_dir)')
389 parser.add_argument('-n', '--dry-run', default=False, action='store_true',
390 help='show what would be done, but do not upload')
391 parser.add_argument('-M', '--mock', default=False, action='store_true',
392 help='upload things to a testing bucket (dev testing)')
Mike Frysingerdad40d62014-02-09 02:18:02 -0500393 parser.add_argument('--test-sign-mp', default=False, action='store_true',
394 help='mung signing behavior to sign w/test mp keys')
395 parser.add_argument('--test-sign-premp', default=False, action='store_true',
396 help='mung signing behavior to sign w/test premp keys')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400397 parser.add_argument('--priority', type=int, default=50,
398 help='set signing priority (lower == higher prio)')
399 parser.add_argument('--sign-types', default=None, nargs='+',
400 choices=('recovery', 'factory', 'firmware'),
401 help='only sign specified image types')
Mike Frysinger09fe0122014-02-09 02:44:05 -0500402 parser.add_argument('--yes', action='store_true', default=False,
403 help='answer yes to all prompts')
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400404
405 opts = parser.parse_args(argv)
406 opts.Freeze()
407
Mike Frysingerdad40d62014-02-09 02:18:02 -0500408 force_keysets = set()
409 if opts.test_sign_mp:
410 force_keysets.add('test-keys-mp')
411 if opts.test_sign_premp:
412 force_keysets.add('test-keys-premp')
413
Mike Frysinger09fe0122014-02-09 02:44:05 -0500414 # If we aren't using mock or test or dry run mode, then let's prompt the user
415 # to make sure they actually want to do this. It's rare that people want to
416 # run this directly and hit the release bucket.
417 if not (opts.mock or force_keysets or opts.dry_run) and not opts.yes:
418 prolog = '\n'.join(textwrap.wrap(textwrap.dedent(
419 'Uploading images for signing to the *release* bucket is not something '
420 'you generally should be doing yourself.'), 80)).strip()
421 if not cros_build_lib.BooleanPrompt(
422 prompt='Are you sure you want to sign these images',
423 default=False, prolog=prolog):
424 cros_build_lib.Die('better safe than sorry')
425
Mike Frysingerd13faeb2013-09-05 16:00:46 -0400426 PushImage(opts.image_dir, opts.board, versionrev=opts.version,
427 profile=opts.profile, priority=opts.priority,
Mike Frysingerdad40d62014-02-09 02:18:02 -0500428 sign_types=opts.sign_types, dry_run=opts.dry_run, mock=opts.mock,
429 force_keysets=force_keysets)