blob: 009be1c316040e7a5e4cdfb4f33b81b7726e0d41 [file] [log] [blame]
David James8c846492011-01-25 17:07:29 -08001#!/usr/bin/python
Chris Sosac13bba52011-05-24 15:14:09 -07002# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
David James8c846492011-01-25 17:07:29 -08003# 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
Chris Sosac13bba52011-05-24 15:14:09 -070020from chromite.lib.binpkg import (GrabLocalPackageIndex, GrabRemotePackageIndex)
David James8c846492011-01-25 17:07:29 -080021"""
22This script is used to upload host prebuilts as well as board BINHOSTS.
23
24If the URL starts with 'gs://', we upload using gsutil to Google Storage.
25Otherwise, rsync is used.
26
27After a build is successfully uploaded a file is updated with the proper
28BINHOST version as well as the target board. This file is defined in GIT_FILE
29
30
31To read more about prebuilts/binhost binary packages please refer to:
32http://sites/chromeos/for-team-members/engineering/releng/prebuilt-binaries-for-streamlining-the-build-process
33
34
35Example of uploading prebuilt amd64 host files to Google Storage:
36./prebuilt.py -p /b/cbuild/build -s -u gs://chromeos-prebuilt
37
38Example of uploading x86-dogfood binhosts to Google Storage:
39./prebuilt.py -b x86-dogfood -p /b/cbuild/build/ -u gs://chromeos-prebuilt -g
40
41Example of uploading prebuilt amd64 host files using rsync:
42./prebuilt.py -p /b/cbuild/build -s -u codf30.jail:/tmp
43"""
44
45# as per http://crosbug.com/5855 always filter the below packages
46_FILTER_PACKAGES = set()
47_RETRIES = 3
48_GSUTIL_BIN = '/b/build/third_party/gsutil/gsutil'
49_HOST_PACKAGES_PATH = 'chroot/var/lib/portage/pkgs'
David James05bcb2b2011-02-09 09:25:47 -080050_CATEGORIES_PATH = 'chroot/etc/portage/categories'
David James8c846492011-01-25 17:07:29 -080051_HOST_TARGET = 'amd64'
52_BOARD_PATH = 'chroot/build/%(board)s'
David James8fa34ea2011-04-15 13:00:20 -070053# board/board-target/version/'
54_REL_BOARD_PATH = 'board/%(board)s/%(version)s'
55# host/host-target/version/'
56_REL_HOST_PATH = 'host/%(target)s/%(version)s'
David James8c846492011-01-25 17:07:29 -080057# Private overlays to look at for builds to filter
58# relative to build path
59_PRIVATE_OVERLAY_DIR = 'src/private-overlays'
Scott Zawalskiab1bed32011-03-16 15:24:24 -070060_GOOGLESTORAGE_ACL_FILE = 'googlestorage_acl.xml'
David James8c846492011-01-25 17:07:29 -080061_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
David James8c846492011-01-25 17:07:29 -080082
83def UpdateLocalFile(filename, value, key='PORTAGE_BINHOST'):
84 """Update the key in file with the value passed.
85 File format:
86 key="value"
87 Note quotes are added automatically
88
89 Args:
90 filename: Name of file to modify.
91 value: Value to write with the key.
92 key: The variable key to update. (Default: PORTAGE_BINHOST)
93 """
94 if os.path.exists(filename):
95 file_fh = open(filename)
96 else:
97 file_fh = open(filename, 'w+')
98 file_lines = []
99 found = False
100 keyval_str = '%(key)s=%(value)s'
101 for line in file_fh:
102 # Strip newlines from end of line. We already add newlines below.
103 line = line.rstrip("\n")
104
105 if len(line.split('=')) != 2:
106 # Skip any line that doesn't fit key=val.
107 file_lines.append(line)
108 continue
109
110 file_var, file_val = line.split('=')
111 if file_var == key:
112 found = True
113 print 'Updating %s=%s to %s="%s"' % (file_var, file_val, key, value)
114 value = '"%s"' % value
115 file_lines.append(keyval_str % {'key': key, 'value': value})
116 else:
117 file_lines.append(keyval_str % {'key': file_var, 'value': file_val})
118
119 if not found:
120 file_lines.append(keyval_str % {'key': key, 'value': value})
121
122 file_fh.close()
123 # write out new file
124 new_file_fh = open(filename, 'w')
125 new_file_fh.write('\n'.join(file_lines) + '\n')
126 new_file_fh.close()
127
128
David James8c846492011-01-25 17:07:29 -0800129def RevGitFile(filename, value, retries=5, key='PORTAGE_BINHOST'):
130 """Update and push the git file.
131
132 Args:
133 filename: file to modify that is in a git repo already
134 value: string representing the version of the prebuilt that has been
135 uploaded.
136 retries: The number of times to retry before giving up, default: 5
137 key: The variable key to update in the git file.
138 (Default: PORTAGE_BINHOST)
139 """
140 prebuilt_branch = 'prebuilt_branch'
David James1b6e67a2011-05-19 21:32:38 -0700141 cwd = os.path.abspath(os.path.dirname(filename))
142 commit = cros_build_lib.RunCommand(['git', 'rev-parse', 'HEAD'], cwd=cwd,
Peter Mayofe0e6872011-04-20 00:52:08 -0400143 redirect_stdout=True).output.rstrip()
Peter Mayo193f68f2011-04-19 19:08:21 -0400144 git_ssh_config_cmd = [
145 'git',
146 'config',
Chris Sosac13bba52011-05-24 15:14:09 -0700147 'url.ssh://gerrit.chromium.org:29418.pushinsteadof',
David James1b6e67a2011-05-19 21:32:38 -0700148 'http://git.chromium.org']
149 cros_build_lib.RunCommand(git_ssh_config_cmd, cwd=cwd)
150 cros_build_lib.RunCommand(['git', 'remote', 'update'], cwd=cwd)
151 cros_build_lib.RunCommand(['repo', 'start', prebuilt_branch, '.'], cwd=cwd)
David James8c846492011-01-25 17:07:29 -0800152 description = 'Update %s="%s" in %s' % (key, value, filename)
153 print description
154 try:
155 UpdateLocalFile(filename, value, key)
David James1b6e67a2011-05-19 21:32:38 -0700156 cros_build_lib.RunCommand(['git', 'config', 'push.default', 'tracking'],
157 cwd=cwd)
158 cros_build_lib.RunCommand(['git', 'add', filename], cwd=cwd)
159 cros_build_lib.RunCommand(['git', 'commit', '-m', description], cwd=cwd)
Chris Sosac13bba52011-05-24 15:14:09 -0700160 cros_build_lib.GitPushWithRetry(prebuilt_branch, cwd=cwd)
David James8c846492011-01-25 17:07:29 -0800161 finally:
David James1b6e67a2011-05-19 21:32:38 -0700162 cros_build_lib.RunCommand(['git', 'checkout', commit], cwd=cwd)
163 cros_build_lib.RunCommand(['repo', 'abandon', 'prebuilt_branch', '.'],
164 cwd=cwd)
David James8c846492011-01-25 17:07:29 -0800165
166
167def GetVersion():
168 """Get the version to put in LATEST and update the git version with."""
169 return datetime.datetime.now().strftime('%d.%m.%y.%H%M%S')
170
171
172def LoadPrivateFilters(build_path):
173 """Load private filters based on ebuilds found under _PRIVATE_OVERLAY_DIR.
174
175 This function adds filters to the global set _FILTER_PACKAGES.
176 Args:
177 build_path: Path that _PRIVATE_OVERLAY_DIR is in.
178 """
179 # TODO(scottz): eventually use manifest.xml to find the proper
180 # private overlay path.
181 filter_path = os.path.join(build_path, _PRIVATE_OVERLAY_DIR)
182 files = cros_build_lib.ListFiles(filter_path)
183 filters = []
184 for file in files:
185 if file.endswith('.ebuild'):
186 basename = os.path.basename(file)
187 match = re.match('(.*?)-\d.*.ebuild', basename)
188 if match:
189 filters.append(match.group(1))
190
191 if not filters:
192 raise FiltersEmpty('No filters were returned')
193
194 _FILTER_PACKAGES.update(filters)
195
196
197def ShouldFilterPackage(file_path):
198 """Skip a particular file if it matches a pattern.
199
200 Skip any files that machine the list of packages to filter in
201 _FILTER_PACKAGES.
202
203 Args:
204 file_path: string of a file path to inspect against _FILTER_PACKAGES
205
206 Returns:
207 True if we should filter the package,
208 False otherwise.
209 """
210 for name in _FILTER_PACKAGES:
211 if name in file_path:
212 print 'FILTERING %s' % file_path
213 return True
214
215 return False
216
217
Peter Mayo193f68f2011-04-19 19:08:21 -0400218def _RetryRun(cmd, print_cmd=True, cwd=None):
David James8c846492011-01-25 17:07:29 -0800219 """Run the specified command, retrying if necessary.
220
221 Args:
222 cmd: The command to run.
223 print_cmd: Whether to print out the cmd.
224 shell: Whether to treat the command as a shell.
225 cwd: Working directory to run command in.
226
227 Returns:
228 True if the command succeeded. Otherwise, returns False.
229 """
230
231 # TODO(scottz): port to use _Run or similar when it is available in
232 # cros_build_lib.
233 for attempt in range(_RETRIES):
234 try:
Peter Mayo193f68f2011-04-19 19:08:21 -0400235 output = cros_build_lib.RunCommand(cmd, print_cmd=print_cmd,
David James8c846492011-01-25 17:07:29 -0800236 cwd=cwd)
237 return True
238 except cros_build_lib.RunCommandError:
Peter Mayo193f68f2011-04-19 19:08:21 -0400239 print 'Failed to run %r' % cmd
David James8c846492011-01-25 17:07:29 -0800240 else:
Peter Mayo193f68f2011-04-19 19:08:21 -0400241 print 'Retry failed run %r, giving up' % cmd
David James8c846492011-01-25 17:07:29 -0800242 return False
243
244
245def _GsUpload(args):
246 """Upload to GS bucket.
247
248 Args:
David Jamesfd0b0852011-02-23 11:15:36 -0800249 args: a tuple of three arguments that contains local_file, remote_file, and
250 the acl used for uploading the file.
David James8c846492011-01-25 17:07:29 -0800251
252 Returns:
253 Return the arg tuple of two if the upload failed
254 """
David Jamesfd0b0852011-02-23 11:15:36 -0800255 (local_file, remote_file, acl) = args
Scott Zawalskiab1bed32011-03-16 15:24:24 -0700256 CANNED_ACLS = ['public-read', 'private', 'bucket-owner-read',
257 'authenticated-read', 'bucket-owner-full-control',
258 'public-read-write']
259 acl_cmd = None
260 if acl in CANNED_ACLS:
Peter Mayo193f68f2011-04-19 19:08:21 -0400261 cmd = [_GSUTIL_BIN, 'cp', '-a', acl, local_file, remote_file]
Scott Zawalskiab1bed32011-03-16 15:24:24 -0700262 else:
263 # For private uploads we assume that the overlay board is set up properly
264 # and a googlestore_acl.xml is present, if not this script errors
Peter Mayo193f68f2011-04-19 19:08:21 -0400265 cmd = [_GSUTIL_BIN, 'cp', '-a', 'private', local_file, remote_file]
Scott Zawalskiab1bed32011-03-16 15:24:24 -0700266 if not os.path.exists(acl):
267 print >> sys.stderr, ('You are specifying either a file that does not '
268 'exist or an unknown canned acl: %s. Aborting '
269 'upload') % acl
270 # emulate the failing of an upload since we are not uploading the file
271 return (local_file, remote_file)
David James8c846492011-01-25 17:07:29 -0800272
Peter Mayo193f68f2011-04-19 19:08:21 -0400273 acl_cmd = [_GSUTIL_BIN, 'setacl', acl, remote_file]
Scott Zawalskiab1bed32011-03-16 15:24:24 -0700274
Peter Mayo193f68f2011-04-19 19:08:21 -0400275 if not _RetryRun(cmd, print_cmd=False):
David James8c846492011-01-25 17:07:29 -0800276 return (local_file, remote_file)
277
Scott Zawalskiab1bed32011-03-16 15:24:24 -0700278 if acl_cmd:
279 # Apply the passed in ACL xml file to the uploaded object.
Peter Mayo193f68f2011-04-19 19:08:21 -0400280 _RetryRun(acl_cmd, print_cmd=False)
Scott Zawalskiab1bed32011-03-16 15:24:24 -0700281
282
David Jamesfd0b0852011-02-23 11:15:36 -0800283def RemoteUpload(acl, files, pool=10):
David James8c846492011-01-25 17:07:29 -0800284 """Upload to google storage.
285
286 Create a pool of process and call _GsUpload with the proper arguments.
287
288 Args:
David Jamesfd0b0852011-02-23 11:15:36 -0800289 acl: The canned acl used for uploading. acl can be one of: "public-read",
290 "public-read-write", "authenticated-read", "bucket-owner-read",
291 "bucket-owner-full-control", or "private".
David James8c846492011-01-25 17:07:29 -0800292 files: dictionary with keys to local files and values to remote path.
293 pool: integer of maximum proesses to have at the same time.
294
295 Returns:
296 Return a set of tuple arguments of the failed uploads
297 """
298 # TODO(scottz) port this to use _RunManyParallel when it is available in
299 # cros_build_lib
300 pool = multiprocessing.Pool(processes=pool)
301 workers = []
302 for local_file, remote_path in files.iteritems():
David Jamesfd0b0852011-02-23 11:15:36 -0800303 workers.append((local_file, remote_path, acl))
David James8c846492011-01-25 17:07:29 -0800304
305 result = pool.map_async(_GsUpload, workers, chunksize=1)
306 while True:
307 try:
Chris Sosa471532a2011-02-01 15:10:06 -0800308 return set(result.get(60 * 60))
David James8c846492011-01-25 17:07:29 -0800309 except multiprocessing.TimeoutError:
310 pass
311
312
313def GenerateUploadDict(base_local_path, base_remote_path, pkgs):
314 """Build a dictionary of local remote file key pairs to upload.
315
316 Args:
317 base_local_path: The base path to the files on the local hard drive.
318 remote_path: The base path to the remote paths.
319 pkgs: The packages to upload.
320
321 Returns:
322 Returns a dictionary of local_path/remote_path pairs
323 """
324 upload_files = {}
325 for pkg in pkgs:
326 suffix = pkg['CPV'] + '.tbz2'
327 local_path = os.path.join(base_local_path, suffix)
328 assert os.path.exists(local_path)
329 remote_path = '%s/%s' % (base_remote_path.rstrip('/'), suffix)
330 upload_files[local_path] = remote_path
331
332 return upload_files
333
334def GetBoardPathFromCrosOverlayList(build_path, target):
335 """Use the cros_overlay_list to determine the path to the board overlay
336 Args:
337 build_path: The path to the root of the build directory
338 target: The target that we are looking for, could consist of board and
339 board_variant, we handle that properly
340 Returns:
341 The last line from cros_overlay_list as a string
342 """
Chris Sosa471532a2011-02-01 15:10:06 -0800343 script_dir = os.path.join(build_path, 'src/platform/dev/host')
David James8c846492011-01-25 17:07:29 -0800344 cmd = ['./cros_overlay_list']
345 if re.match('.*?_.*', target):
346 (board, variant) = target.split('_')
347 cmd += ['--board', board, '--variant', variant]
348 elif re.match('.*?-\w+', target):
349 cmd += ['--board', target]
350 else:
351 raise UnknownBoardFormat('Unknown format: %s' % target)
352
353 cmd_output = cros_build_lib.RunCommand(cmd, redirect_stdout=True,
354 cwd=script_dir)
355 # We only care about the last entry
356 return cmd_output.output.splitlines().pop()
357
358
359def DeterminePrebuiltConfFile(build_path, target):
360 """Determine the prebuilt.conf file that needs to be updated for prebuilts.
361
362 Args:
363 build_path: The path to the root of the build directory
364 target: String representation of the board. This includes host and board
365 targets
366
367 Returns
368 A string path to a prebuilt.conf file to be updated.
369 """
370 if _HOST_TARGET == target:
371 # We are host.
372 # Without more examples of hosts this is a kludge for now.
373 # TODO(Scottz): as new host targets come online expand this to
374 # work more like boards.
Chris Sosa471532a2011-02-01 15:10:06 -0800375 make_path = _PREBUILT_MAKE_CONF[target]
David James8c846492011-01-25 17:07:29 -0800376 else:
377 # We are a board
378 board = GetBoardPathFromCrosOverlayList(build_path, target)
379 make_path = os.path.join(board, 'prebuilt.conf')
380
381 return make_path
382
383
384def UpdateBinhostConfFile(path, key, value):
385 """Update binhost config file file with key=value.
386
387 Args:
388 path: Filename to update.
389 key: Key to update.
390 value: New value for key.
391 """
392 cwd = os.path.dirname(os.path.abspath(path))
393 filename = os.path.basename(path)
394 if not os.path.isdir(cwd):
395 os.makedirs(cwd)
396 if not os.path.isfile(path):
397 config_file = file(path, 'w')
David James8c846492011-01-25 17:07:29 -0800398 config_file.close()
399 UpdateLocalFile(path, value, key)
Chris Sosac13bba52011-05-24 15:14:09 -0700400 cros_build_lib.RunCommand(['git', 'add', filename], cwd=cwd)
David James8c846492011-01-25 17:07:29 -0800401 description = 'Update %s=%s in %s' % (key, value, filename)
Peter Mayo193f68f2011-04-19 19:08:21 -0400402 cros_build_lib.RunCommand(['git', 'commit', '-m', description], cwd=cwd)
David James8c846492011-01-25 17:07:29 -0800403
404
David Jamesce093af2011-02-23 15:21:58 -0800405def _GrabAllRemotePackageIndexes(binhost_urls):
David James05bcb2b2011-02-09 09:25:47 -0800406 """Grab all of the packages files associated with a list of binhost_urls.
407
David James05bcb2b2011-02-09 09:25:47 -0800408 Args:
409 binhost_urls: The URLs for the directories containing the Packages files we
410 want to grab.
David James05bcb2b2011-02-09 09:25:47 -0800411
412 Returns:
413 A list of PackageIndex objects.
414 """
415 pkg_indexes = []
416 for url in binhost_urls:
417 pkg_index = GrabRemotePackageIndex(url)
418 if pkg_index:
419 pkg_indexes.append(pkg_index)
David James05bcb2b2011-02-09 09:25:47 -0800420 return pkg_indexes
421
422
David James05bcb2b2011-02-09 09:25:47 -0800423
David Jamesc0f158a2011-02-22 16:07:29 -0800424class PrebuiltUploader(object):
425 """Synchronize host and board prebuilts."""
David James8c846492011-01-25 17:07:29 -0800426
David Jamesfd0b0852011-02-23 11:15:36 -0800427 def __init__(self, upload_location, acl, binhost_base_url, pkg_indexes):
David Jamesc0f158a2011-02-22 16:07:29 -0800428 """Constructor for prebuilt uploader object.
David James8c846492011-01-25 17:07:29 -0800429
David Jamesc0f158a2011-02-22 16:07:29 -0800430 This object can upload host or prebuilt files to Google Storage.
David James8c846492011-01-25 17:07:29 -0800431
David Jamesc0f158a2011-02-22 16:07:29 -0800432 Args:
433 upload_location: The upload location.
David Jamesfd0b0852011-02-23 11:15:36 -0800434 acl: The canned acl used for uploading to Google Storage. acl can be one
435 of: "public-read", "public-read-write", "authenticated-read",
436 "bucket-owner-read", "bucket-owner-full-control", or "private". If
437 we are not uploading to Google Storage, this parameter is unused.
438 binhost_base_url: The URL used for downloading the prebuilts.
David Jamesc0f158a2011-02-22 16:07:29 -0800439 pkg_indexes: Old uploaded prebuilts to compare against. Instead of
440 uploading duplicate files, we just link to the old files.
441 """
442 self._upload_location = upload_location
David Jamesfd0b0852011-02-23 11:15:36 -0800443 self._acl = acl
David Jamesc0f158a2011-02-22 16:07:29 -0800444 self._binhost_base_url = binhost_base_url
445 self._pkg_indexes = pkg_indexes
David James8c846492011-01-25 17:07:29 -0800446
David Jamesc0f158a2011-02-22 16:07:29 -0800447 def _UploadPrebuilt(self, package_path, url_suffix):
448 """Upload host or board prebuilt files to Google Storage space.
David James8c846492011-01-25 17:07:29 -0800449
David Jamesc0f158a2011-02-22 16:07:29 -0800450 Args:
451 package_path: The path to the packages dir.
David Jamesce093af2011-02-23 15:21:58 -0800452 url_suffix: The remote subdirectory where we should upload the packages.
David Jamesc0f158a2011-02-22 16:07:29 -0800453 """
David James8c846492011-01-25 17:07:29 -0800454
David Jamesc0f158a2011-02-22 16:07:29 -0800455 # Process Packages file, removing duplicates and filtered packages.
456 pkg_index = GrabLocalPackageIndex(package_path)
457 pkg_index.SetUploadLocation(self._binhost_base_url, url_suffix)
458 pkg_index.RemoveFilteredPackages(ShouldFilterPackage)
459 uploads = pkg_index.ResolveDuplicateUploads(self._pkg_indexes)
David James05bcb2b2011-02-09 09:25:47 -0800460
David Jamesc0f158a2011-02-22 16:07:29 -0800461 # Write Packages file.
462 tmp_packages_file = pkg_index.WriteToNamedTemporaryFile()
David James05bcb2b2011-02-09 09:25:47 -0800463
David Jamesc0f158a2011-02-22 16:07:29 -0800464 remote_location = '%s/%s' % (self._upload_location.rstrip('/'), url_suffix)
465 if remote_location.startswith('gs://'):
466 # Build list of files to upload.
467 upload_files = GenerateUploadDict(package_path, remote_location, uploads)
468 remote_file = '%s/Packages' % remote_location.rstrip('/')
469 upload_files[tmp_packages_file.name] = remote_file
David James05bcb2b2011-02-09 09:25:47 -0800470
David Jamesfd0b0852011-02-23 11:15:36 -0800471 failed_uploads = RemoteUpload(self._acl, upload_files)
David Jamesc0f158a2011-02-22 16:07:29 -0800472 if len(failed_uploads) > 1 or (None not in failed_uploads):
David Jamesf4db1122011-03-17 16:18:05 -0700473 error_msg = ['%s -> %s\n' % args for args in failed_uploads if args]
David Jamesc0f158a2011-02-22 16:07:29 -0800474 raise UploadFailed('Error uploading:\n%s' % error_msg)
475 else:
Peter Mayo193f68f2011-04-19 19:08:21 -0400476 pkgs = [p['CPV'] + '.tbz2' for p in uploads]
David Jamesc0f158a2011-02-22 16:07:29 -0800477 ssh_server, remote_path = remote_location.split(':', 1)
Peter Mayo193f68f2011-04-19 19:08:21 -0400478 remote_path = remote_path.rstrip('/')
479 pkg_index = tmp_packages_file.name
480 remote_location = remote_location.rstrip('/')
481 remote_packages = '%s/Packages' % remote_location
482 cmds = [['ssh', ssh_server, 'mkdir', '-p', remote_path],
483 ['rsync', '-av', '--chmod=a+r', pkg_index, remote_packages]]
David Jamesc0f158a2011-02-22 16:07:29 -0800484 if pkgs:
Peter Mayo193f68f2011-04-19 19:08:21 -0400485 cmds.append(['rsync', '-Rav'] + pkgs + [remote_location + '/'])
David Jamesc0f158a2011-02-22 16:07:29 -0800486 for cmd in cmds:
Peter Mayo193f68f2011-04-19 19:08:21 -0400487 if not _RetryRun(cmd, cwd=package_path):
488 raise UploadFailed('Could not run %r' % cmd)
David James8c846492011-01-25 17:07:29 -0800489
David James8fa34ea2011-04-15 13:00:20 -0700490 def _UploadBoardTarball(self, board_path, url_suffix):
491 """Upload a tarball of the board at the specified path to Google Storage.
492
493 Args:
494 board_path: The path to the board dir.
495 url_suffix: The remote subdirectory where we should upload the packages.
496 """
497 remote_location = '%s/%s' % (self._upload_location.rstrip('/'), url_suffix)
498 assert remote_location.startswith('gs://')
499 cwd, boardname = os.path.split(board_path.rstrip(os.path.sep))
500 tmpdir = tempfile.mkdtemp()
501 try:
502 tarfile = os.path.join(tmpdir, '%s.tbz2' % boardname)
503 cmd = ['sudo', 'tar', '-I', 'pbzip2', '-cf', tarfile]
504 excluded_paths = ('usr/lib/debug', 'usr/local/autotest', 'packages',
505 'tmp')
506 for path in excluded_paths:
507 cmd.append('--exclude=%s/%s/*' % (boardname, path))
508 cmd.append(boardname)
509 cros_build_lib.RunCommand(cmd, cwd=cwd)
510 remote_tarfile = '%s/%s.tbz2' % (remote_location.rstrip('/'), boardname)
511 if _GsUpload((tarfile, remote_tarfile, self._acl)):
512 sys.exit(1)
513 finally:
514 cros_build_lib.RunCommand(['sudo', 'rm', '-rf', tmpdir], cwd=cwd)
515
David Jamesc0f158a2011-02-22 16:07:29 -0800516 def _SyncHostPrebuilts(self, build_path, version, key, git_sync,
517 sync_binhost_conf):
518 """Synchronize host prebuilt files.
David James05bcb2b2011-02-09 09:25:47 -0800519
David Jamesc0f158a2011-02-22 16:07:29 -0800520 This function will sync both the standard host packages, plus the host
521 packages associated with all targets that have been "setup" with the
522 current host's chroot. For instance, if this host has been used to build
523 x86-generic, it will sync the host packages associated with
524 'i686-pc-linux-gnu'. If this host has also been used to build arm-generic,
525 it will also sync the host packages associated with
526 'armv7a-cros-linux-gnueabi'.
David James05bcb2b2011-02-09 09:25:47 -0800527
David Jamesc0f158a2011-02-22 16:07:29 -0800528 Args:
529 build_path: The path to the directory containing the chroot.
530 version: A unique string, intended to be included in the upload path,
531 which identifies the version number of the uploaded prebuilts.
532 key: The variable key to update in the git file.
533 git_sync: If set, update make.conf of target to reference the latest
534 prebuilt packages generated here.
535 sync_binhost_conf: If set, update binhost config file in
536 chromiumos-overlay for the host.
537 """
538 # Upload prebuilts.
539 package_path = os.path.join(build_path, _HOST_PACKAGES_PATH)
540 url_suffix = _REL_HOST_PATH % {'version': version, 'target': _HOST_TARGET}
David James8fa34ea2011-04-15 13:00:20 -0700541 packages_url_suffix = '%s/packages' % url_suffix.rstrip('/')
542 self._UploadPrebuilt(package_path, packages_url_suffix)
David James05bcb2b2011-02-09 09:25:47 -0800543
David Jamesc0f158a2011-02-22 16:07:29 -0800544 # Record URL where prebuilts were uploaded.
545 url_value = '%s/%s/' % (self._binhost_base_url.rstrip('/'),
David Jamesf0e6fd72011-04-15 15:58:07 -0700546 packages_url_suffix.rstrip('/'))
David Jamesc0f158a2011-02-22 16:07:29 -0800547 if git_sync:
548 git_file = os.path.join(build_path, _PREBUILT_MAKE_CONF[_HOST_TARGET])
549 RevGitFile(git_file, url_value, key=key)
550 if sync_binhost_conf:
551 binhost_conf = os.path.join(build_path, _BINHOST_CONF_DIR, 'host',
552 '%s-%s.conf' % (_HOST_TARGET, key))
553 UpdateBinhostConfFile(binhost_conf, key, url_value)
554
555 def _SyncBoardPrebuilts(self, board, build_path, version, key, git_sync,
David James8fa34ea2011-04-15 13:00:20 -0700556 sync_binhost_conf, upload_board_tarball):
David Jamesc0f158a2011-02-22 16:07:29 -0800557 """Synchronize board prebuilt files.
558
559 Args:
560 board: The board to upload to Google Storage.
561 build_path: The path to the directory containing the chroot.
562 version: A unique string, intended to be included in the upload path,
563 which identifies the version number of the uploaded prebuilts.
564 key: The variable key to update in the git file.
565 git_sync: If set, update make.conf of target to reference the latest
566 prebuilt packages generated here.
567 sync_binhost_conf: If set, update binhost config file in
568 chromiumos-overlay for the current board.
David James8fa34ea2011-04-15 13:00:20 -0700569 upload_board_tarball: Include a tarball of the board in our upload.
David Jamesc0f158a2011-02-22 16:07:29 -0800570 """
David Jamesc0f158a2011-02-22 16:07:29 -0800571 board_path = os.path.join(build_path, _BOARD_PATH % {'board': board})
572 package_path = os.path.join(board_path, 'packages')
573 url_suffix = _REL_BOARD_PATH % {'board': board, 'version': version}
David James8fa34ea2011-04-15 13:00:20 -0700574 packages_url_suffix = '%s/packages' % url_suffix.rstrip('/')
575
576 # Upload board tarballs in the background.
577 if upload_board_tarball:
578 tar_process = multiprocessing.Process(target=self._UploadBoardTarball,
579 args=(board_path, url_suffix))
580 tar_process.start()
581
582 # Upload prebuilts.
583 self._UploadPrebuilt(package_path, packages_url_suffix)
584
585 # Make sure we finished uploading the board tarballs.
586 if upload_board_tarball:
587 tar_process.join()
588 assert tar_process.exitcode == 0
David Jamesc0f158a2011-02-22 16:07:29 -0800589
590 # Record URL where prebuilts were uploaded.
591 url_value = '%s/%s/' % (self._binhost_base_url.rstrip('/'),
David Jamesf0e6fd72011-04-15 15:58:07 -0700592 packages_url_suffix.rstrip('/'))
David Jamesc0f158a2011-02-22 16:07:29 -0800593 if git_sync:
594 git_file = DeterminePrebuiltConfFile(build_path, board)
595 RevGitFile(git_file, url_value, key=key)
596 if sync_binhost_conf:
597 binhost_conf = os.path.join(build_path, _BINHOST_CONF_DIR, 'target',
598 '%s-%s.conf' % (board, key))
599 UpdateBinhostConfFile(binhost_conf, key, url_value)
David James05bcb2b2011-02-09 09:25:47 -0800600
601
David James8c846492011-01-25 17:07:29 -0800602def usage(parser, msg):
603 """Display usage message and parser help then exit with 1."""
604 print >> sys.stderr, msg
605 parser.print_help()
606 sys.exit(1)
607
David Jamesc0f158a2011-02-22 16:07:29 -0800608def ParseOptions():
David James8c846492011-01-25 17:07:29 -0800609 parser = optparse.OptionParser()
610 parser.add_option('-H', '--binhost-base-url', dest='binhost_base_url',
611 default=_BINHOST_BASE_URL,
612 help='Base URL to use for binhost in make.conf updates')
613 parser.add_option('', '--previous-binhost-url', action='append',
614 default=[], dest='previous_binhost_url',
615 help='Previous binhost URL')
616 parser.add_option('-b', '--board', dest='board', default=None,
617 help='Board type that was built on this machine')
618 parser.add_option('-p', '--build-path', dest='build_path',
David James05bcb2b2011-02-09 09:25:47 -0800619 help='Path to the directory containing the chroot')
David James8c846492011-01-25 17:07:29 -0800620 parser.add_option('-s', '--sync-host', dest='sync_host',
621 default=False, action='store_true',
622 help='Sync host prebuilts')
623 parser.add_option('-g', '--git-sync', dest='git_sync',
624 default=False, action='store_true',
625 help='Enable git version sync (This commits to a repo)')
626 parser.add_option('-u', '--upload', dest='upload',
627 default=None,
628 help='Upload location')
629 parser.add_option('-V', '--prepend-version', dest='prepend_version',
630 default=None,
631 help='Add an identifier to the front of the version')
632 parser.add_option('-f', '--filters', dest='filters', action='store_true',
633 default=False,
634 help='Turn on filtering of private ebuild packages')
635 parser.add_option('-k', '--key', dest='key',
636 default='PORTAGE_BINHOST',
637 help='Key to update in make.conf / binhost.conf')
638 parser.add_option('', '--sync-binhost-conf', dest='sync_binhost_conf',
639 default=False, action='store_true',
640 help='Update binhost.conf')
David Jamesfd0b0852011-02-23 11:15:36 -0800641 parser.add_option('-P', '--private', dest='private', action='store_true',
642 default=False, help='Mark gs:// uploads as private.')
David James8fa34ea2011-04-15 13:00:20 -0700643 parser.add_option('', '--upload-board-tarball', dest='upload_board_tarball',
644 action='store_true', default=False,
645 help='Upload board tarball to Google Storage.')
David James8c846492011-01-25 17:07:29 -0800646
647 options, args = parser.parse_args()
David James8c846492011-01-25 17:07:29 -0800648 if not options.build_path:
649 usage(parser, 'Error: you need provide a chroot path')
David James8c846492011-01-25 17:07:29 -0800650 if not options.upload:
651 usage(parser, 'Error: you need to provide an upload location using -u')
Scott Zawalskiab1bed32011-03-16 15:24:24 -0700652
David James8fa34ea2011-04-15 13:00:20 -0700653
654 if options.upload_board_tarball and not options.upload.startswith('gs://'):
655 usage(parser, 'Error: --upload-board-tarball only works with gs:// URLs.\n'
656 '--upload must be a gs:// URL.')
657
Scott Zawalskiab1bed32011-03-16 15:24:24 -0700658 if options.private:
659 if options.sync_host:
660 usage(parser, 'Error: --private and --sync-host/-s cannot be specified '
661 'together, we do not support private host prebuilts')
662
663 if not options.upload.startswith('gs://'):
664 usage(parser, 'Error: --private is only valid for gs:// URLs.\n'
665 '--upload must be a gs:// URL.')
666
667 if options.binhost_base_url != _BINHOST_BASE_URL:
668 usage(parser, 'Error: when using --private the --binhost-base-url '
669 'is automatically derived.')
David Jamesc0f158a2011-02-22 16:07:29 -0800670 return options
671
672def main():
673 options = ParseOptions()
674
David James8c846492011-01-25 17:07:29 -0800675 if options.filters:
676 LoadPrivateFilters(options.build_path)
677
David Jamesfd0b0852011-02-23 11:15:36 -0800678
David James05bcb2b2011-02-09 09:25:47 -0800679 # Calculate a list of Packages index files to compare against. Whenever we
680 # upload a package, we check to make sure it's not already stored in one of
681 # the packages files we uploaded. This list of packages files might contain
682 # both board and host packages.
David Jamesce093af2011-02-23 15:21:58 -0800683 pkg_indexes = _GrabAllRemotePackageIndexes(options.previous_binhost_url)
David James8c846492011-01-25 17:07:29 -0800684
David Jamesc0f158a2011-02-22 16:07:29 -0800685 version = GetVersion()
686 if options.prepend_version:
687 version = '%s-%s' % (options.prepend_version, version)
688
Scott Zawalskiab1bed32011-03-16 15:24:24 -0700689 acl = 'public-read'
690 binhost_base_url = options.binhost_base_url
691
692 if options.private:
693 binhost_base_url = options.upload
694 board_path = GetBoardPathFromCrosOverlayList(options.build_path,
695 options.board)
696 acl = os.path.join(board_path, _GOOGLESTORAGE_ACL_FILE)
697
698 uploader = PrebuiltUploader(options.upload, acl, binhost_base_url,
David Jamesc0f158a2011-02-22 16:07:29 -0800699 pkg_indexes)
700
David James8c846492011-01-25 17:07:29 -0800701 if options.sync_host:
David Jamesc0f158a2011-02-22 16:07:29 -0800702 uploader._SyncHostPrebuilts(options.build_path, version, options.key,
703 options.git_sync, options.sync_binhost_conf)
David James8c846492011-01-25 17:07:29 -0800704
705 if options.board:
David Jamesc0f158a2011-02-22 16:07:29 -0800706 uploader._SyncBoardPrebuilts(options.board, options.build_path, version,
707 options.key, options.git_sync,
David James8fa34ea2011-04-15 13:00:20 -0700708 options.sync_binhost_conf,
709 options.upload_board_tarball)
David James8c846492011-01-25 17:07:29 -0800710
711if __name__ == '__main__':
712 main()