blob: a21caeb85f484b5bf9c17b829368c7b6e529c66b [file] [log] [blame]
Brian Harringb938c782012-02-29 15:14:38 -08001#!/usr/bin/env python
Mike Frysinger2de7f042012-07-10 04:45:03 -04002# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Brian Harringb938c782012-02-29 15:14:38 -08003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""This script fetches and prepares an SDK chroot.
7"""
8
Brian Harringb938c782012-02-29 15:14:38 -08009import os
David James56e6c2c2012-10-24 23:54:41 -070010import sys
Brian Harringb938c782012-02-29 15:14:38 -080011import urlparse
12
13from chromite.buildbot import constants
Brian Harringcfe762a2012-02-29 13:03:53 -080014from chromite.lib import cgroups
Brian Harringb6cf9142012-09-01 20:43:17 -070015from chromite.lib import commandline
Brian Harringb938c782012-02-29 15:14:38 -080016from chromite.lib import cros_build_lib
Brian Harringb938c782012-02-29 15:14:38 -080017from chromite.lib import locking
Brian Harringae0a5322012-09-15 01:46:51 -070018from chromite.lib import osutils
Brian Harringb938c782012-02-29 15:14:38 -080019
20cros_build_lib.STRICT_SUDO = True
21
22
Brian Harring1790ac42012-09-23 08:53:33 -070023DEFAULT_URL = 'https://commondatastorage.googleapis.com/chromiumos-sdk'
Zdenek Behanaa52cea2012-05-30 01:31:11 +020024COMPRESSION_PREFERENCE = ('xz', 'bz2')
Zdenek Behanfd0efe42012-04-13 04:36:40 +020025
Brian Harringb938c782012-02-29 15:14:38 -080026SRC_ROOT = os.path.realpath(constants.SOURCE_ROOT)
Brian Harringb938c782012-02-29 15:14:38 -080027OVERLAY_DIR = os.path.join(SRC_ROOT, 'src/third_party/chromiumos-overlay')
28SDK_VERSION_FILE = os.path.join(OVERLAY_DIR,
29 'chromeos/binhost/host/sdk_version.conf')
30
31# TODO(zbehan): Remove the dependency on these, reimplement them in python
32MAKE_CHROOT = [os.path.join(SRC_ROOT, 'src/scripts/sdk_lib/make_chroot.sh')]
33ENTER_CHROOT = [os.path.join(SRC_ROOT, 'src/scripts/sdk_lib/enter_chroot.sh')]
34
35# We need these tools to run. Very common tools (tar,..) are ommited.
David James56e6c2c2012-10-24 23:54:41 -070036NEEDED_TOOLS = ('curl', 'xz', 'unshare')
Brian Harringb938c782012-02-29 15:14:38 -080037
Brian Harringb938c782012-02-29 15:14:38 -080038
Brian Harring1790ac42012-09-23 08:53:33 -070039def GetArchStageTarballs(version):
Brian Harringb938c782012-02-29 15:14:38 -080040 """Returns the URL for a given arch/version"""
Brian Harring1790ac42012-09-23 08:53:33 -070041 extension = {'bz2':'tbz2', 'xz':'tar.xz'}
42 return ['%s/cros-sdk-%s.%s'
43 % (DEFAULT_URL, version, extension[compressor])
44 for compressor in COMPRESSION_PREFERENCE]
45
46
47def GetStage3Urls(version):
48 return ['%s/stage3-amd64-%s.tar.%s' % (DEFAULT_URL, version, ext)
49 for ext in COMPRESSION_PREFERENCE]
Brian Harringb938c782012-02-29 15:14:38 -080050
51
Brian Harringae0a5322012-09-15 01:46:51 -070052def FetchRemoteTarballs(storage_dir, urls):
Zdenek Behanfd0efe42012-04-13 04:36:40 +020053 """Fetches a tarball given by url, and place it in sdk/.
54
55 Args:
56 urls: List of URLs to try to download. Download will stop on first success.
57
58 Returns:
59 Full path to the downloaded file
60 """
Zdenek Behanfd0efe42012-04-13 04:36:40 +020061
Brian Harring1790ac42012-09-23 08:53:33 -070062 # Note we track content length ourselves since certain versions of curl
63 # fail if asked to resume a complete file.
64 # pylint: disable=C0301,W0631
65 # https://sourceforge.net/tracker/?func=detail&atid=100976&aid=3482927&group_id=976
Zdenek Behanfd0efe42012-04-13 04:36:40 +020066 for url in urls:
Brian Harring1790ac42012-09-23 08:53:33 -070067 # http://www.logilab.org/ticket/8766
68 # pylint: disable=E1101
69 parsed = urlparse.urlparse(url)
70 tarball_name = os.path.basename(parsed.path)
71 if parsed.scheme in ('', 'file'):
72 if os.path.exists(parsed.path):
73 return parsed.path
74 continue
75 content_length = 0
Zdenek Behanfd0efe42012-04-13 04:36:40 +020076 print 'Attempting download: %s' % url
Brian Harring1790ac42012-09-23 08:53:33 -070077 result = cros_build_lib.RunCurl(
78 ['-I', url], redirect_stdout=True, redirect_stderr=True,
79 print_cmd=False)
80 successful = False
81 for header in result.output.splitlines():
82 # We must walk the output to find the string '200 OK' for use cases where
83 # a proxy is involved and may have pushed down the actual header.
84 if header.find('200 OK') != -1:
85 successful = True
86 elif header.lower().startswith("content-length:"):
87 content_length = int(header.split(":", 1)[-1].strip())
88 if successful:
89 break
90 if successful:
Zdenek Behanfd0efe42012-04-13 04:36:40 +020091 break
92 else:
93 raise Exception('No valid URLs found!')
94
Brian Harringae0a5322012-09-15 01:46:51 -070095 tarball_dest = os.path.join(storage_dir, tarball_name)
Brian Harring1790ac42012-09-23 08:53:33 -070096 current_size = 0
97 if os.path.exists(tarball_dest):
98 current_size = os.path.getsize(tarball_dest)
99 if current_size > content_length:
David James56e6c2c2012-10-24 23:54:41 -0700100 osutils.SafeUnlink(tarball_dest)
Brian Harring1790ac42012-09-23 08:53:33 -0700101 current_size = 0
Zdenek Behanb2fa72e2012-03-16 04:49:30 +0100102
Brian Harring1790ac42012-09-23 08:53:33 -0700103 if current_size < content_length:
104 cros_build_lib.RunCurl(
105 ['-f', '-L', '-y', '30', '-C', '-', '--output', tarball_dest, url],
106 print_cmd=False)
Brian Harringb938c782012-02-29 15:14:38 -0800107
Brian Harring1790ac42012-09-23 08:53:33 -0700108 # Cleanup old tarballs now since we've successfull fetched; only cleanup
109 # the tarballs for our prefix, or unknown ones.
110 ignored_prefix = ('stage3-' if tarball_name.startswith('cros-sdk-')
111 else 'cros-sdk-')
112 for filename in os.listdir(storage_dir):
113 if filename == tarball_name or filename.startswith(ignored_prefix):
114 continue
Brian Harringb938c782012-02-29 15:14:38 -0800115
Brian Harring1790ac42012-09-23 08:53:33 -0700116 print 'Cleaning up old tarball: %s' % (filename,)
David James56e6c2c2012-10-24 23:54:41 -0700117 osutils.SafeUnlink(os.path.join(storage_dir, filename))
Zdenek Behan9c644dd2012-04-05 06:24:02 +0200118
Brian Harringb938c782012-02-29 15:14:38 -0800119 return tarball_dest
120
121
Brian Harring1790ac42012-09-23 08:53:33 -0700122def CreateChroot(chroot_path, sdk_tarball, cache_dir, nousepkg=False):
Brian Harringb938c782012-02-29 15:14:38 -0800123 """Creates a new chroot from a given SDK"""
Brian Harringb938c782012-02-29 15:14:38 -0800124
Brian Harring1790ac42012-09-23 08:53:33 -0700125 cmd = MAKE_CHROOT + ['--stage3_path', sdk_tarball,
Brian Harringae0a5322012-09-15 01:46:51 -0700126 '--chroot', chroot_path,
127 '--cache_dir', cache_dir]
Mike Frysinger2de7f042012-07-10 04:45:03 -0400128 if nousepkg:
129 cmd.append('--nousepkg')
Brian Harringb938c782012-02-29 15:14:38 -0800130
131 try:
132 cros_build_lib.RunCommand(cmd, print_cmd=False)
133 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700134 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800135
136
137def DeleteChroot(chroot_path):
138 """Deletes an existing chroot"""
139 cmd = MAKE_CHROOT + ['--chroot', chroot_path,
140 '--delete']
141 try:
142 cros_build_lib.RunCommand(cmd, print_cmd=False)
143 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700144 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800145
146
Brian Harringae0a5322012-09-15 01:46:51 -0700147def EnterChroot(chroot_path, cache_dir, chrome_root, chrome_root_mount,
148 additional_args):
Brian Harringb938c782012-02-29 15:14:38 -0800149 """Enters an existing SDK chroot"""
Brian Harringae0a5322012-09-15 01:46:51 -0700150 cmd = ENTER_CHROOT + ['--chroot', chroot_path, '--cache_dir', cache_dir]
Brian Harringb938c782012-02-29 15:14:38 -0800151 if chrome_root:
152 cmd.extend(['--chrome_root', chrome_root])
153 if chrome_root_mount:
154 cmd.extend(['--chrome_root_mount', chrome_root_mount])
155 if len(additional_args) > 0:
156 cmd.append('--')
157 cmd.extend(additional_args)
Brian Harring7199e7d2012-03-23 04:10:08 -0700158
159 ret = cros_build_lib.RunCommand(cmd, print_cmd=False, error_code_ok=True)
160 # If we were in interactive mode, ignore the exit code; it'll be whatever
161 # they last ran w/in the chroot and won't matter to us one way or another.
162 # Note this does allow chroot entrance to fail and be ignored during
163 # interactive; this is however a rare case and the user will immediately
164 # see it (nor will they be checking the exit code manually).
165 if ret.returncode != 0 and additional_args:
166 raise SystemExit('Running %r failed with exit code %i'
167 % (cmd, ret.returncode))
Brian Harringb938c782012-02-29 15:14:38 -0800168
169
David James56e6c2c2012-10-24 23:54:41 -0700170def _SudoCommand():
171 """Get the 'sudo' command, along with all needed environment variables."""
172
173 # Pass in the ENVIRONMENT_WHITELIST variable so that scripts in the chroot
174 # know what variables to pass through.
175 cmd = ['sudo']
176 for key in constants.CHROOT_ENVIRONMENT_WHITELIST:
177 value = os.environ.get(key)
178 if value is not None:
179 cmd += ['%s=%s' % (key, value)]
180
181 # Pass in the path to the depot_tools so that users can access them from
182 # within the chroot.
183 gclient = osutils.Which('gclient')
184 if gclient is not None:
185 cmd += ['DEPOT_TOOLS=%s' % os.path.realpath(os.path.dirname(gclient))]
186
187 return cmd
188
189
Mike Frysingera78a56e2012-11-20 06:02:30 -0500190def _ReExecuteIfNeeded(argv):
David James56e6c2c2012-10-24 23:54:41 -0700191 """Re-execute cros_sdk as root.
192
193 Also unshare the mount namespace so as to ensure that processes outside
194 the chroot can't mess with our mounts.
195 """
Mike Frysingera78a56e2012-11-20 06:02:30 -0500196 MAGIC_VAR = '%CROS_SDK_MOUNT_NS'
David James56e6c2c2012-10-24 23:54:41 -0700197 if os.geteuid() != 0:
Mike Frysingera78a56e2012-11-20 06:02:30 -0500198 cmd = _SudoCommand() + ['--'] + argv
199 os.execvp(cmd[0], cmd)
200 elif os.environ.get(MAGIC_VAR, '0') == '0':
201 cgroups.Cgroup.InitSystem()
202 os.environ[MAGIC_VAR] = '1'
203 os.execvp('unshare', ['unshare', '-m', '--'] + argv)
204 else:
205 os.environ.pop(MAGIC_VAR)
David James56e6c2c2012-10-24 23:54:41 -0700206
207
Brian Harring6be2efc2012-03-01 05:04:00 -0800208def main(argv):
Brian Harring218e13c2012-10-10 16:21:26 -0700209 usage = """usage: %prog [options] [VAR1=val1 .. VARn=valn -- args]
Brian Harringb938c782012-02-29 15:14:38 -0800210
Brian Harring218e13c2012-10-10 16:21:26 -0700211This script is used for manipulating local chroot environments; creating,
212deleting, downloading, etc. If given --enter (or no args), it defaults
213to an interactive bash shell within the chroot.
Brian Harringb938c782012-02-29 15:14:38 -0800214
Brian Harring218e13c2012-10-10 16:21:26 -0700215If given args those are passed to the chroot environment, and executed."""
Mike Frysinger95f55582013-01-08 12:18:53 -0500216 conf = cros_build_lib.LoadKeyValueFile(SDK_VERSION_FILE, ignore_missing=True)
Brian Harring1790ac42012-09-23 08:53:33 -0700217 sdk_latest_version = conf.get('SDK_LATEST_VERSION', '<unknown>')
218 bootstrap_latest_version = conf.get('BOOTSTRAP_LATEST_VERSION', '<unknown>')
219
Brian Harring218e13c2012-10-10 16:21:26 -0700220 parser = commandline.OptionParser(usage=usage, caching=True)
221
222 commands = parser.add_option_group("Commands")
223 commands.add_option(
224 '--enter', action='store_true', default=False,
225 help='Enter the SDK chroot. Implies --create.')
226 commands.add_option(
227 '--create', action='store_true',default=False,
228 help='Create the chroot only if it does not already exist. '
229 'Implies --download.')
230 commands.add_option(
231 '--bootstrap', action='store_true', default=False,
232 help='Build everything from scratch, including the sdk. '
233 'Use this only if you need to validate a change '
234 'that affects SDK creation itself (toolchain and '
235 'build are typically the only folk who need this). '
236 'Note this will quite heavily slow down the build. '
237 'This option implies --create --nousepkg.')
238 commands.add_option(
239 '-r', '--replace', action='store_true', default=False,
240 help='Replace an existing SDK chroot. Basically an alias '
241 'for --delete --create.')
242 commands.add_option(
243 '--delete', action='store_true', default=False,
244 help='Delete the current SDK chroot if it exists.')
245 commands.add_option(
246 '--download', action='store_true', default=False,
247 help='Download the sdk.')
Brian Harringb938c782012-02-29 15:14:38 -0800248
249 # Global options:
Brian Harringb6cf9142012-09-01 20:43:17 -0700250 default_chroot = os.path.join(SRC_ROOT, constants.DEFAULT_CHROOT_DIR)
Brian Harring218e13c2012-10-10 16:21:26 -0700251 parser.add_option(
252 '--chroot', dest='chroot', default=default_chroot, type='path',
253 help=('SDK chroot dir name [%s]' % constants.DEFAULT_CHROOT_DIR))
Brian Harringb938c782012-02-29 15:14:38 -0800254
Brian Harring218e13c2012-10-10 16:21:26 -0700255 parser.add_option('--chrome_root', default=None, type='path',
256 help='Mount this chrome root into the SDK chroot')
257 parser.add_option('--chrome_root_mount', default=None, type='path',
258 help='Mount chrome into this path inside SDK chroot')
259 parser.add_option('--nousepkg', action='store_true', default=False,
260 help='Do not use binary packages when creating a chroot.')
Brian Harringb938c782012-02-29 15:14:38 -0800261 parser.add_option('-u', '--url',
Brian Harringb6cf9142012-09-01 20:43:17 -0700262 dest='sdk_url', default=None,
Brian Harringb938c782012-02-29 15:14:38 -0800263 help=('''Use sdk tarball located at this url.
264 Use file:// for local files.'''))
Brian Harring1790ac42012-09-23 08:53:33 -0700265 parser.add_option('--sdk-version', default=None,
266 help='Use this sdk version. For prebuilt, current is %r'
267 ', for bootstrapping its %r.'
268 % (sdk_latest_version, bootstrap_latest_version))
Brian Harring218e13c2012-10-10 16:21:26 -0700269 options, chroot_command = parser.parse_args(argv)
Brian Harringb938c782012-02-29 15:14:38 -0800270
271 # Some sanity checks first, before we ask for sudo credentials.
Mike Frysinger8fd67dc2012-12-03 23:51:18 -0500272 cros_build_lib.AssertOutsideChroot()
Brian Harringb938c782012-02-29 15:14:38 -0800273
Mike Frysingera78a56e2012-11-20 06:02:30 -0500274 _ReExecuteIfNeeded([sys.argv[0]] + argv)
David James56e6c2c2012-10-24 23:54:41 -0700275
Brian Harring1790ac42012-09-23 08:53:33 -0700276 host = os.uname()[4]
Brian Harring1790ac42012-09-23 08:53:33 -0700277 if host != 'x86_64':
278 parser.error(
279 "cros_sdk is currently only supported on x86_64; you're running"
280 " %s. Please find a x86_64 machine." % (host,))
281
David Jamesaad5cc72012-10-26 15:03:13 -0700282 missing = osutils.FindMissingBinaries(NEEDED_TOOLS)
Brian Harring98b54902012-03-23 04:05:42 -0700283 if missing:
284 parser.error((
285 'The tool(s) %s were not found.'
286 'Please install the appropriate package in your host.'
287 'Example(ubuntu):'
288 ' sudo apt-get install <packagename>'
289 % (', '.join(missing))))
Brian Harringb938c782012-02-29 15:14:38 -0800290
Brian Harring218e13c2012-10-10 16:21:26 -0700291 # Expand out the aliases...
292 if options.replace:
293 options.delete = options.create = True
Brian Harringb938c782012-02-29 15:14:38 -0800294
Brian Harring218e13c2012-10-10 16:21:26 -0700295 if options.bootstrap:
296 options.create = True
Brian Harringb938c782012-02-29 15:14:38 -0800297
Brian Harring218e13c2012-10-10 16:21:26 -0700298 # If a command is not given, default to enter.
299 options.enter |= not any(getattr(options, x.dest)
300 for x in commands.option_list)
301 options.enter |= bool(chroot_command)
302
303 if options.enter and options.delete and not options.create:
304 parser.error("Trying to enter the chroot when --delete "
305 "was specified makes no sense.")
306
307 # Finally, discern if we need to create the chroot.
308 chroot_exists = os.path.exists(options.chroot)
309 if options.create or options.enter:
310 # Only create if it's being wiped, or if it doesn't exist.
311 if not options.delete and chroot_exists:
312 options.create = False
313 else:
314 options.download = True
315
316 # Finally, flip create if necessary.
317 if options.enter:
318 options.create |= not chroot_exists
Brian Harringb938c782012-02-29 15:14:38 -0800319
Brian Harringb938c782012-02-29 15:14:38 -0800320 if not options.sdk_version:
Brian Harring1790ac42012-09-23 08:53:33 -0700321 sdk_version = (bootstrap_latest_version if options.bootstrap
322 else sdk_latest_version)
Brian Harringb938c782012-02-29 15:14:38 -0800323 else:
324 sdk_version = options.sdk_version
325
Brian Harring1790ac42012-09-23 08:53:33 -0700326 # Based on selections, fetch the tarball.
327 if options.sdk_url:
328 urls = [options.sdk_url]
329 elif options.bootstrap:
330 urls = GetStage3Urls(sdk_version)
331 else:
332 urls = GetArchStageTarballs(sdk_version)
333
Brian Harringb6cf9142012-09-01 20:43:17 -0700334 lock_path = os.path.dirname(options.chroot)
Brian Harringb938c782012-02-29 15:14:38 -0800335 lock_path = os.path.join(lock_path,
Brian Harringb6cf9142012-09-01 20:43:17 -0700336 '.%s_lock' % os.path.basename(options.chroot))
David James56e6c2c2012-10-24 23:54:41 -0700337 with cgroups.SimpleContainChildren('cros_sdk'):
338 with locking.FileLock(lock_path, 'chroot lock') as lock:
Brian Harring1790ac42012-09-23 08:53:33 -0700339
David James56e6c2c2012-10-24 23:54:41 -0700340 if options.delete and os.path.exists(options.chroot):
341 lock.write_lock()
342 DeleteChroot(options.chroot)
Brian Harringb938c782012-02-29 15:14:38 -0800343
David James56e6c2c2012-10-24 23:54:41 -0700344 sdk_cache = os.path.join(options.cache_dir, 'sdks')
345 distfiles_cache = os.path.join(options.cache_dir, 'distfiles')
346 osutils.SafeMakedirs(options.cache_dir)
Brian Harringae0a5322012-09-15 01:46:51 -0700347
David James56e6c2c2012-10-24 23:54:41 -0700348 for target in (sdk_cache, distfiles_cache):
349 src = os.path.join(SRC_ROOT, os.path.basename(target))
350 if not os.path.exists(src):
351 osutils.SafeMakedirs(target)
352 continue
353 lock.write_lock(
354 "Upgrade to %r needed but chroot is locked; please exit "
355 "all instances so this upgrade can finish." % src)
356 if not os.path.exists(src):
357 # Note that while waiting for the write lock, src may've vanished;
358 # it's a rare race during the upgrade process that's a byproduct
359 # of us avoiding taking a write lock to do the src check. If we
360 # took a write lock for that check, it would effectively limit
361 # all cros_sdk for a chroot to a single instance.
362 osutils.SafeMakedirs(target)
363 elif not os.path.exists(target):
364 # Upgrade occurred, but a reversion, or something whacky
365 # occurred writing to the old location. Wipe and continue.
366 os.rename(src, target)
367 else:
368 # Upgrade occurred once already, but either a reversion or
369 # some before/after separate cros_sdk usage is at play.
370 # Wipe and continue.
371 osutils.RmDir(src)
Brian Harringae0a5322012-09-15 01:46:51 -0700372
David James56e6c2c2012-10-24 23:54:41 -0700373 if options.download:
374 lock.write_lock()
375 sdk_tarball = FetchRemoteTarballs(sdk_cache, urls)
Brian Harring218e13c2012-10-10 16:21:26 -0700376
David James56e6c2c2012-10-24 23:54:41 -0700377 if options.create:
378 lock.write_lock()
379 CreateChroot(options.chroot, sdk_tarball, options.cache_dir,
380 nousepkg=(options.bootstrap or options.nousepkg))
Brian Harring1790ac42012-09-23 08:53:33 -0700381
David James56e6c2c2012-10-24 23:54:41 -0700382 if options.enter:
383 lock.read_lock()
384 EnterChroot(options.chroot, options.cache_dir, options.chrome_root,
385 options.chrome_root_mount, chroot_command)