blob: 2dbe8ff1cb838d2ae81459cd3fbb9467db63f1dc [file] [log] [blame]
David James8c846492011-01-25 17:07:29 -08001#!/usr/bin/python
2# Copyright (c) 2010 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
6import datetime
7import multiprocessing
8import optparse
9import os
10import re
11import sys
12import tempfile
13import time
14
Chris Sosa471532a2011-02-01 15:10:06 -080015if __name__ == '__main__':
16 import constants
17 sys.path.append(constants.SOURCE_ROOT)
18
David James8c846492011-01-25 17:07:29 -080019from chromite.lib import cros_build_lib
20from chromite.lib.binpkg import (GrabLocalPackageIndex, GrabRemotePackageIndex,
21 PackageIndex)
22"""
23This script is used to upload host prebuilts as well as board BINHOSTS.
24
25If the URL starts with 'gs://', we upload using gsutil to Google Storage.
26Otherwise, rsync is used.
27
28After a build is successfully uploaded a file is updated with the proper
29BINHOST version as well as the target board. This file is defined in GIT_FILE
30
31
32To read more about prebuilts/binhost binary packages please refer to:
33http://sites/chromeos/for-team-members/engineering/releng/prebuilt-binaries-for-streamlining-the-build-process
34
35
36Example of uploading prebuilt amd64 host files to Google Storage:
37./prebuilt.py -p /b/cbuild/build -s -u gs://chromeos-prebuilt
38
39Example of uploading x86-dogfood binhosts to Google Storage:
40./prebuilt.py -b x86-dogfood -p /b/cbuild/build/ -u gs://chromeos-prebuilt -g
41
42Example of uploading prebuilt amd64 host files using rsync:
43./prebuilt.py -p /b/cbuild/build -s -u codf30.jail:/tmp
44"""
45
46# as per http://crosbug.com/5855 always filter the below packages
47_FILTER_PACKAGES = set()
48_RETRIES = 3
49_GSUTIL_BIN = '/b/build/third_party/gsutil/gsutil'
50_HOST_PACKAGES_PATH = 'chroot/var/lib/portage/pkgs'
51_HOST_TARGET = 'amd64'
52_BOARD_PATH = 'chroot/build/%(board)s'
53_BOTO_CONFIG = '/home/chrome-bot/external-boto'
54# board/board-target/version/packages/'
55_REL_BOARD_PATH = 'board/%(board)s/%(version)s/packages'
56# host/host-target/version/packages/'
57_REL_HOST_PATH = 'host/%(target)s/%(version)s/packages'
58# Private overlays to look at for builds to filter
59# relative to build path
60_PRIVATE_OVERLAY_DIR = 'src/private-overlays'
61_BINHOST_BASE_URL = 'http://commondatastorage.googleapis.com/chromeos-prebuilt'
62_PREBUILT_BASE_DIR = 'src/third_party/chromiumos-overlay/chromeos/config/'
63# Created in the event of new host targets becoming available
64_PREBUILT_MAKE_CONF = {'amd64': os.path.join(_PREBUILT_BASE_DIR,
65 'make.conf.amd64-host')}
66_BINHOST_CONF_DIR = 'src/third_party/chromiumos-overlay/chromeos/binhost'
67
68
69class FiltersEmpty(Exception):
70 """Raised when filters are used but none are found."""
71 pass
72
73
74class UploadFailed(Exception):
75 """Raised when one of the files uploaded failed."""
76 pass
77
78class UnknownBoardFormat(Exception):
79 """Raised when a function finds an unknown board format."""
80 pass
81
82class GitPushFailed(Exception):
83 """Raised when a git push failed after retry."""
84 pass
85
86
87def UpdateLocalFile(filename, value, key='PORTAGE_BINHOST'):
88 """Update the key in file with the value passed.
89 File format:
90 key="value"
91 Note quotes are added automatically
92
93 Args:
94 filename: Name of file to modify.
95 value: Value to write with the key.
96 key: The variable key to update. (Default: PORTAGE_BINHOST)
97 """
98 if os.path.exists(filename):
99 file_fh = open(filename)
100 else:
101 file_fh = open(filename, 'w+')
102 file_lines = []
103 found = False
104 keyval_str = '%(key)s=%(value)s'
105 for line in file_fh:
106 # Strip newlines from end of line. We already add newlines below.
107 line = line.rstrip("\n")
108
109 if len(line.split('=')) != 2:
110 # Skip any line that doesn't fit key=val.
111 file_lines.append(line)
112 continue
113
114 file_var, file_val = line.split('=')
115 if file_var == key:
116 found = True
117 print 'Updating %s=%s to %s="%s"' % (file_var, file_val, key, value)
118 value = '"%s"' % value
119 file_lines.append(keyval_str % {'key': key, 'value': value})
120 else:
121 file_lines.append(keyval_str % {'key': file_var, 'value': file_val})
122
123 if not found:
124 file_lines.append(keyval_str % {'key': key, 'value': value})
125
126 file_fh.close()
127 # write out new file
128 new_file_fh = open(filename, 'w')
129 new_file_fh.write('\n'.join(file_lines) + '\n')
130 new_file_fh.close()
131
132
133def RevGitPushWithRetry(retries=5):
134 """Repo sync and then push git changes in flight.
135
136 Args:
137 retries: The number of times to retry before giving up, default: 5
138
139 Raises:
140 GitPushFailed if push was unsuccessful after retries
141 """
Chris Sosa471532a2011-02-01 15:10:06 -0800142 for retry in range(1, retries + 1):
David James8c846492011-01-25 17:07:29 -0800143 try:
144 cros_build_lib.RunCommand('repo sync .', shell=True)
145 cros_build_lib.RunCommand('git push', shell=True)
146 break
147 except cros_build_lib.RunCommandError:
148 if retry < retries:
149 print 'Error pushing changes trying again (%s/%s)' % (retry, retries)
Chris Sosa471532a2011-02-01 15:10:06 -0800150 time.sleep(5 * retry)
David James8c846492011-01-25 17:07:29 -0800151 else:
152 raise GitPushFailed('Failed to push change after %s retries' % retries)
153
154
155def RevGitFile(filename, value, retries=5, key='PORTAGE_BINHOST'):
156 """Update and push the git file.
157
158 Args:
159 filename: file to modify that is in a git repo already
160 value: string representing the version of the prebuilt that has been
161 uploaded.
162 retries: The number of times to retry before giving up, default: 5
163 key: The variable key to update in the git file.
164 (Default: PORTAGE_BINHOST)
165 """
166 prebuilt_branch = 'prebuilt_branch'
167 old_cwd = os.getcwd()
168 os.chdir(os.path.dirname(filename))
169
170 cros_build_lib.RunCommand('repo sync .', shell=True)
171 cros_build_lib.RunCommand('repo start %s .' % prebuilt_branch, shell=True)
172 git_ssh_config_cmd = (
173 'git config url.ssh://git@gitrw.chromium.org:9222.pushinsteadof '
174 'http://git.chromium.org/git')
175 cros_build_lib.RunCommand(git_ssh_config_cmd, shell=True)
176 description = 'Update %s="%s" in %s' % (key, value, filename)
177 print description
178 try:
179 UpdateLocalFile(filename, value, key)
180 cros_build_lib.RunCommand('git config push.default tracking', shell=True)
181 cros_build_lib.RunCommand('git commit -am "%s"' % description, shell=True)
182 RevGitPushWithRetry(retries)
183 finally:
184 cros_build_lib.RunCommand('repo abandon %s .' % prebuilt_branch, shell=True)
185 os.chdir(old_cwd)
186
187
188def GetVersion():
189 """Get the version to put in LATEST and update the git version with."""
190 return datetime.datetime.now().strftime('%d.%m.%y.%H%M%S')
191
192
193def LoadPrivateFilters(build_path):
194 """Load private filters based on ebuilds found under _PRIVATE_OVERLAY_DIR.
195
196 This function adds filters to the global set _FILTER_PACKAGES.
197 Args:
198 build_path: Path that _PRIVATE_OVERLAY_DIR is in.
199 """
200 # TODO(scottz): eventually use manifest.xml to find the proper
201 # private overlay path.
202 filter_path = os.path.join(build_path, _PRIVATE_OVERLAY_DIR)
203 files = cros_build_lib.ListFiles(filter_path)
204 filters = []
205 for file in files:
206 if file.endswith('.ebuild'):
207 basename = os.path.basename(file)
208 match = re.match('(.*?)-\d.*.ebuild', basename)
209 if match:
210 filters.append(match.group(1))
211
212 if not filters:
213 raise FiltersEmpty('No filters were returned')
214
215 _FILTER_PACKAGES.update(filters)
216
217
218def ShouldFilterPackage(file_path):
219 """Skip a particular file if it matches a pattern.
220
221 Skip any files that machine the list of packages to filter in
222 _FILTER_PACKAGES.
223
224 Args:
225 file_path: string of a file path to inspect against _FILTER_PACKAGES
226
227 Returns:
228 True if we should filter the package,
229 False otherwise.
230 """
231 for name in _FILTER_PACKAGES:
232 if name in file_path:
233 print 'FILTERING %s' % file_path
234 return True
235
236 return False
237
238
239def _RetryRun(cmd, print_cmd=True, shell=False, cwd=None):
240 """Run the specified command, retrying if necessary.
241
242 Args:
243 cmd: The command to run.
244 print_cmd: Whether to print out the cmd.
245 shell: Whether to treat the command as a shell.
246 cwd: Working directory to run command in.
247
248 Returns:
249 True if the command succeeded. Otherwise, returns False.
250 """
251
252 # TODO(scottz): port to use _Run or similar when it is available in
253 # cros_build_lib.
254 for attempt in range(_RETRIES):
255 try:
256 output = cros_build_lib.RunCommand(cmd, print_cmd=print_cmd, shell=shell,
257 cwd=cwd)
258 return True
259 except cros_build_lib.RunCommandError:
260 print 'Failed to run %s' % cmd
261 else:
262 print 'Retry failed run %s, giving up' % cmd
263 return False
264
265
266def _GsUpload(args):
267 """Upload to GS bucket.
268
269 Args:
270 args: a tuple of two arguments that contains local_file and remote_file.
271
272 Returns:
273 Return the arg tuple of two if the upload failed
274 """
275 (local_file, remote_file) = args
276
277 cmd = '%s cp -a public-read %s %s' % (_GSUTIL_BIN, local_file, remote_file)
278 if not _RetryRun(cmd, print_cmd=False, shell=True):
279 return (local_file, remote_file)
280
281
282def RemoteUpload(files, pool=10):
283 """Upload to google storage.
284
285 Create a pool of process and call _GsUpload with the proper arguments.
286
287 Args:
288 files: dictionary with keys to local files and values to remote path.
289 pool: integer of maximum proesses to have at the same time.
290
291 Returns:
292 Return a set of tuple arguments of the failed uploads
293 """
294 # TODO(scottz) port this to use _RunManyParallel when it is available in
295 # cros_build_lib
296 pool = multiprocessing.Pool(processes=pool)
297 workers = []
298 for local_file, remote_path in files.iteritems():
299 workers.append((local_file, remote_path))
300
301 result = pool.map_async(_GsUpload, workers, chunksize=1)
302 while True:
303 try:
Chris Sosa471532a2011-02-01 15:10:06 -0800304 return set(result.get(60 * 60))
David James8c846492011-01-25 17:07:29 -0800305 except multiprocessing.TimeoutError:
306 pass
307
308
309def GenerateUploadDict(base_local_path, base_remote_path, pkgs):
310 """Build a dictionary of local remote file key pairs to upload.
311
312 Args:
313 base_local_path: The base path to the files on the local hard drive.
314 remote_path: The base path to the remote paths.
315 pkgs: The packages to upload.
316
317 Returns:
318 Returns a dictionary of local_path/remote_path pairs
319 """
320 upload_files = {}
321 for pkg in pkgs:
322 suffix = pkg['CPV'] + '.tbz2'
323 local_path = os.path.join(base_local_path, suffix)
324 assert os.path.exists(local_path)
325 remote_path = '%s/%s' % (base_remote_path.rstrip('/'), suffix)
326 upload_files[local_path] = remote_path
327
328 return upload_files
329
330def GetBoardPathFromCrosOverlayList(build_path, target):
331 """Use the cros_overlay_list to determine the path to the board overlay
332 Args:
333 build_path: The path to the root of the build directory
334 target: The target that we are looking for, could consist of board and
335 board_variant, we handle that properly
336 Returns:
337 The last line from cros_overlay_list as a string
338 """
Chris Sosa471532a2011-02-01 15:10:06 -0800339 script_dir = os.path.join(build_path, 'src/platform/dev/host')
David James8c846492011-01-25 17:07:29 -0800340 cmd = ['./cros_overlay_list']
341 if re.match('.*?_.*', target):
342 (board, variant) = target.split('_')
343 cmd += ['--board', board, '--variant', variant]
344 elif re.match('.*?-\w+', target):
345 cmd += ['--board', target]
346 else:
347 raise UnknownBoardFormat('Unknown format: %s' % target)
348
349 cmd_output = cros_build_lib.RunCommand(cmd, redirect_stdout=True,
350 cwd=script_dir)
351 # We only care about the last entry
352 return cmd_output.output.splitlines().pop()
353
354
355def DeterminePrebuiltConfFile(build_path, target):
356 """Determine the prebuilt.conf file that needs to be updated for prebuilts.
357
358 Args:
359 build_path: The path to the root of the build directory
360 target: String representation of the board. This includes host and board
361 targets
362
363 Returns
364 A string path to a prebuilt.conf file to be updated.
365 """
366 if _HOST_TARGET == target:
367 # We are host.
368 # Without more examples of hosts this is a kludge for now.
369 # TODO(Scottz): as new host targets come online expand this to
370 # work more like boards.
Chris Sosa471532a2011-02-01 15:10:06 -0800371 make_path = _PREBUILT_MAKE_CONF[target]
David James8c846492011-01-25 17:07:29 -0800372 else:
373 # We are a board
374 board = GetBoardPathFromCrosOverlayList(build_path, target)
375 make_path = os.path.join(board, 'prebuilt.conf')
376
377 return make_path
378
379
380def UpdateBinhostConfFile(path, key, value):
381 """Update binhost config file file with key=value.
382
383 Args:
384 path: Filename to update.
385 key: Key to update.
386 value: New value for key.
387 """
388 cwd = os.path.dirname(os.path.abspath(path))
389 filename = os.path.basename(path)
390 if not os.path.isdir(cwd):
391 os.makedirs(cwd)
392 if not os.path.isfile(path):
393 config_file = file(path, 'w')
394 config_file.write('FULL_BINHOST="$PORTAGE_BINHOST"\n')
395 config_file.close()
396 UpdateLocalFile(path, value, key)
397 cros_build_lib.RunCommand('git add %s' % filename, cwd=cwd, shell=True)
398 description = 'Update %s=%s in %s' % (key, value, filename)
399 cros_build_lib.RunCommand('git commit -m "%s"' % description, cwd=cwd,
400 shell=True)
401
402
403def UploadPrebuilt(build_path, upload_location, version, binhost_base_url,
404 board=None, git_sync=False, git_sync_retries=5,
405 key='PORTAGE_BINHOST', pkg_indexes=[],
406 sync_binhost_conf=False):
407 """Upload Host prebuilt files to Google Storage space.
408
409 Args:
410 build_path: The path to the root of the chroot.
411 upload_location: The upload location.
412 board: The board to upload to Google Storage. If this is None, upload
413 host packages.
414 git_sync: If set, update make.conf of target to reference the latest
415 prebuilt packages generated here.
416 git_sync_retries: How many times to retry pushing when updating git files.
417 This helps avoid failures when multiple bots are modifying the same Repo.
418 default: 5
419 key: The variable key to update in the git file. (Default: PORTAGE_BINHOST)
420 pkg_indexes: Old uploaded prebuilts to compare against. Instead of
421 uploading duplicate files, we just link to the old files.
422 sync_binhost_conf: If set, update binhost config file in chromiumos-overlay
423 for the current board or host.
424 """
425
426 if not board:
427 # We are uploading host packages
428 # TODO(scottz): eventually add support for different host_targets
429 package_path = os.path.join(build_path, _HOST_PACKAGES_PATH)
430 url_suffix = _REL_HOST_PATH % {'version': version, 'target': _HOST_TARGET}
431 package_string = _HOST_TARGET
432 git_file = os.path.join(build_path, _PREBUILT_MAKE_CONF[_HOST_TARGET])
433 binhost_conf = os.path.join(build_path, _BINHOST_CONF_DIR, 'host',
434 '%s.conf' % _HOST_TARGET)
435 else:
436 board_path = os.path.join(build_path, _BOARD_PATH % {'board': board})
437 package_path = os.path.join(board_path, 'packages')
438 package_string = board
439 url_suffix = _REL_BOARD_PATH % {'board': board, 'version': version}
440 git_file = DeterminePrebuiltConfFile(build_path, board)
441 binhost_conf = os.path.join(build_path, _BINHOST_CONF_DIR, 'target',
442 '%s.conf' % board)
443 remote_location = '%s/%s' % (upload_location.rstrip('/'), url_suffix)
444
445 # Process Packages file, removing duplicates and filtered packages.
446 pkg_index = GrabLocalPackageIndex(package_path)
447 pkg_index.SetUploadLocation(binhost_base_url, url_suffix)
448 pkg_index.RemoveFilteredPackages(lambda pkg: ShouldFilterPackage(pkg))
449 uploads = pkg_index.ResolveDuplicateUploads(pkg_indexes)
450
451 # Write Packages file.
452 tmp_packages_file = pkg_index.WriteToNamedTemporaryFile()
453
454 if upload_location.startswith('gs://'):
455 # Build list of files to upload.
456 upload_files = GenerateUploadDict(package_path, remote_location, uploads)
457 remote_file = '%s/Packages' % remote_location.rstrip('/')
458 upload_files[tmp_packages_file.name] = remote_file
459
460 print 'Uploading %s' % package_string
461 failed_uploads = RemoteUpload(upload_files)
462 if len(failed_uploads) > 1 or (None not in failed_uploads):
463 error_msg = ['%s -> %s\n' % args for args in failed_uploads]
464 raise UploadFailed('Error uploading:\n%s' % error_msg)
465 else:
466 pkgs = ' '.join(p['CPV'] + '.tbz2' for p in uploads)
467 ssh_server, remote_path = remote_location.split(':', 1)
468 d = { 'pkg_index': tmp_packages_file.name,
469 'pkgs': pkgs,
470 'remote_packages': '%s/Packages' % remote_location.rstrip('/'),
471 'remote_path': remote_path,
472 'remote_location': remote_location,
473 'ssh_server': ssh_server }
474 cmds = ['ssh %(ssh_server)s mkdir -p %(remote_path)s' % d,
475 'rsync -av --chmod=a+r %(pkg_index)s %(remote_packages)s' % d]
476 if pkgs:
477 cmds.append('rsync -Rav %(pkgs)s %(remote_location)s/' % d)
478 for cmd in cmds:
479 if not _RetryRun(cmd, shell=True, cwd=package_path):
480 raise UploadFailed('Could not run %s' % cmd)
481
482 url_value = '%s/%s/' % (binhost_base_url, url_suffix)
483
484 if git_sync:
485 RevGitFile(git_file, url_value, retries=git_sync_retries, key=key)
486
487 if sync_binhost_conf:
488 UpdateBinhostConfFile(binhost_conf, key, url_value)
489
490def usage(parser, msg):
491 """Display usage message and parser help then exit with 1."""
492 print >> sys.stderr, msg
493 parser.print_help()
494 sys.exit(1)
495
496
497def main():
498 parser = optparse.OptionParser()
499 parser.add_option('-H', '--binhost-base-url', dest='binhost_base_url',
500 default=_BINHOST_BASE_URL,
501 help='Base URL to use for binhost in make.conf updates')
502 parser.add_option('', '--previous-binhost-url', action='append',
503 default=[], dest='previous_binhost_url',
504 help='Previous binhost URL')
505 parser.add_option('-b', '--board', dest='board', default=None,
506 help='Board type that was built on this machine')
507 parser.add_option('-p', '--build-path', dest='build_path',
508 help='Path to the chroot')
509 parser.add_option('-s', '--sync-host', dest='sync_host',
510 default=False, action='store_true',
511 help='Sync host prebuilts')
512 parser.add_option('-g', '--git-sync', dest='git_sync',
513 default=False, action='store_true',
514 help='Enable git version sync (This commits to a repo)')
515 parser.add_option('-u', '--upload', dest='upload',
516 default=None,
517 help='Upload location')
518 parser.add_option('-V', '--prepend-version', dest='prepend_version',
519 default=None,
520 help='Add an identifier to the front of the version')
521 parser.add_option('-f', '--filters', dest='filters', action='store_true',
522 default=False,
523 help='Turn on filtering of private ebuild packages')
524 parser.add_option('-k', '--key', dest='key',
525 default='PORTAGE_BINHOST',
526 help='Key to update in make.conf / binhost.conf')
527 parser.add_option('', '--sync-binhost-conf', dest='sync_binhost_conf',
528 default=False, action='store_true',
529 help='Update binhost.conf')
530
531 options, args = parser.parse_args()
532 # Setup boto environment for gsutil to use
533 os.environ['BOTO_CONFIG'] = _BOTO_CONFIG
534 if not options.build_path:
535 usage(parser, 'Error: you need provide a chroot path')
536
537 if not options.upload:
538 usage(parser, 'Error: you need to provide an upload location using -u')
539
540 if options.filters:
541 LoadPrivateFilters(options.build_path)
542
543 version = GetVersion()
544 if options.prepend_version:
545 version = '%s-%s' % (options.prepend_version, version)
546
547 pkg_indexes = []
548 for url in options.previous_binhost_url:
549 pkg_index = GrabRemotePackageIndex(url)
550 if pkg_index:
551 pkg_indexes.append(pkg_index)
552
553 if options.sync_host:
554 UploadPrebuilt(options.build_path, options.upload, version,
555 options.binhost_base_url, git_sync=options.git_sync,
556 key=options.key, pkg_indexes=pkg_indexes,
557 sync_binhost_conf=options.sync_binhost_conf)
558
559 if options.board:
560 UploadPrebuilt(options.build_path, options.upload, version,
561 options.binhost_base_url, board=options.board,
562 git_sync=options.git_sync, key=options.key,
563 pkg_indexes=pkg_indexes,
564 sync_binhost_conf=options.sync_binhost_conf)
565
566
567if __name__ == '__main__':
568 main()