blob: d241240eb2bd6c10ead3a82e94d371324e73a341 [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
Josh Triplette759b232013-03-08 13:03:43 -080018from chromite.lib import namespaces
Brian Harringae0a5322012-09-15 01:46:51 -070019from chromite.lib import osutils
Mike Frysinger8e727a32013-01-16 16:57:53 -050020from chromite.lib import toolchain
Brian Harringb938c782012-02-29 15:14:38 -080021
22cros_build_lib.STRICT_SUDO = True
23
24
Zdenek Behanaa52cea2012-05-30 01:31:11 +020025COMPRESSION_PREFERENCE = ('xz', 'bz2')
Zdenek Behanfd0efe42012-04-13 04:36:40 +020026
Brian Harringb938c782012-02-29 15:14:38 -080027# TODO(zbehan): Remove the dependency on these, reimplement them in python
Mike Frysinger648ba2d2013-01-08 14:19:34 -050028MAKE_CHROOT = [os.path.join(constants.SOURCE_ROOT,
29 'src/scripts/sdk_lib/make_chroot.sh')]
30ENTER_CHROOT = [os.path.join(constants.SOURCE_ROOT,
31 'src/scripts/sdk_lib/enter_chroot.sh')]
Brian Harringb938c782012-02-29 15:14:38 -080032
Josh Triplett9a495f62013-03-15 18:06:55 -070033# We need these tools to run. Very common tools (tar,..) are omitted.
Josh Triplette759b232013-03-08 13:03:43 -080034NEEDED_TOOLS = ('curl', 'xz')
Brian Harringb938c782012-02-29 15:14:38 -080035
Brian Harringb938c782012-02-29 15:14:38 -080036
Brian Harring1790ac42012-09-23 08:53:33 -070037def GetArchStageTarballs(version):
Brian Harringb938c782012-02-29 15:14:38 -080038 """Returns the URL for a given arch/version"""
Brian Harring1790ac42012-09-23 08:53:33 -070039 extension = {'bz2':'tbz2', 'xz':'tar.xz'}
Mike Frysinger8e727a32013-01-16 16:57:53 -050040 return [toolchain.GetSdkURL(suburl='cros-sdk-%s.%s'
41 % (version, extension[compressor]))
Brian Harring1790ac42012-09-23 08:53:33 -070042 for compressor in COMPRESSION_PREFERENCE]
43
44
45def GetStage3Urls(version):
Mike Frysinger8e727a32013-01-16 16:57:53 -050046 return [toolchain.GetSdkURL(suburl='stage3-amd64-%s.tar.%s' % (version, ext))
Brian Harring1790ac42012-09-23 08:53:33 -070047 for ext in COMPRESSION_PREFERENCE]
Brian Harringb938c782012-02-29 15:14:38 -080048
49
Brian Harringae0a5322012-09-15 01:46:51 -070050def FetchRemoteTarballs(storage_dir, urls):
Zdenek Behanfd0efe42012-04-13 04:36:40 +020051 """Fetches a tarball given by url, and place it in sdk/.
52
53 Args:
54 urls: List of URLs to try to download. Download will stop on first success.
55
56 Returns:
57 Full path to the downloaded file
58 """
Zdenek Behanfd0efe42012-04-13 04:36:40 +020059
Brian Harring1790ac42012-09-23 08:53:33 -070060 # Note we track content length ourselves since certain versions of curl
61 # fail if asked to resume a complete file.
62 # pylint: disable=C0301,W0631
63 # https://sourceforge.net/tracker/?func=detail&atid=100976&aid=3482927&group_id=976
Zdenek Behanfd0efe42012-04-13 04:36:40 +020064 for url in urls:
Brian Harring1790ac42012-09-23 08:53:33 -070065 # http://www.logilab.org/ticket/8766
66 # pylint: disable=E1101
67 parsed = urlparse.urlparse(url)
68 tarball_name = os.path.basename(parsed.path)
69 if parsed.scheme in ('', 'file'):
70 if os.path.exists(parsed.path):
71 return parsed.path
72 continue
73 content_length = 0
Zdenek Behanfd0efe42012-04-13 04:36:40 +020074 print 'Attempting download: %s' % url
Brian Harring1790ac42012-09-23 08:53:33 -070075 result = cros_build_lib.RunCurl(
76 ['-I', url], redirect_stdout=True, redirect_stderr=True,
77 print_cmd=False)
78 successful = False
79 for header in result.output.splitlines():
80 # We must walk the output to find the string '200 OK' for use cases where
81 # a proxy is involved and may have pushed down the actual header.
82 if header.find('200 OK') != -1:
83 successful = True
84 elif header.lower().startswith("content-length:"):
85 content_length = int(header.split(":", 1)[-1].strip())
86 if successful:
87 break
88 if successful:
Zdenek Behanfd0efe42012-04-13 04:36:40 +020089 break
90 else:
91 raise Exception('No valid URLs found!')
92
Brian Harringae0a5322012-09-15 01:46:51 -070093 tarball_dest = os.path.join(storage_dir, tarball_name)
Brian Harring1790ac42012-09-23 08:53:33 -070094 current_size = 0
95 if os.path.exists(tarball_dest):
96 current_size = os.path.getsize(tarball_dest)
97 if current_size > content_length:
David James56e6c2c2012-10-24 23:54:41 -070098 osutils.SafeUnlink(tarball_dest)
Brian Harring1790ac42012-09-23 08:53:33 -070099 current_size = 0
Zdenek Behanb2fa72e2012-03-16 04:49:30 +0100100
Brian Harring1790ac42012-09-23 08:53:33 -0700101 if current_size < content_length:
102 cros_build_lib.RunCurl(
103 ['-f', '-L', '-y', '30', '-C', '-', '--output', tarball_dest, url],
104 print_cmd=False)
Brian Harringb938c782012-02-29 15:14:38 -0800105
Brian Harring1790ac42012-09-23 08:53:33 -0700106 # Cleanup old tarballs now since we've successfull fetched; only cleanup
107 # the tarballs for our prefix, or unknown ones.
108 ignored_prefix = ('stage3-' if tarball_name.startswith('cros-sdk-')
109 else 'cros-sdk-')
110 for filename in os.listdir(storage_dir):
111 if filename == tarball_name or filename.startswith(ignored_prefix):
112 continue
Brian Harringb938c782012-02-29 15:14:38 -0800113
Brian Harring1790ac42012-09-23 08:53:33 -0700114 print 'Cleaning up old tarball: %s' % (filename,)
David James56e6c2c2012-10-24 23:54:41 -0700115 osutils.SafeUnlink(os.path.join(storage_dir, filename))
Zdenek Behan9c644dd2012-04-05 06:24:02 +0200116
Brian Harringb938c782012-02-29 15:14:38 -0800117 return tarball_dest
118
119
Brian Harring1790ac42012-09-23 08:53:33 -0700120def CreateChroot(chroot_path, sdk_tarball, cache_dir, nousepkg=False):
Brian Harringb938c782012-02-29 15:14:38 -0800121 """Creates a new chroot from a given SDK"""
Brian Harringb938c782012-02-29 15:14:38 -0800122
Brian Harring1790ac42012-09-23 08:53:33 -0700123 cmd = MAKE_CHROOT + ['--stage3_path', sdk_tarball,
Brian Harringae0a5322012-09-15 01:46:51 -0700124 '--chroot', chroot_path,
125 '--cache_dir', cache_dir]
Mike Frysinger2de7f042012-07-10 04:45:03 -0400126 if nousepkg:
127 cmd.append('--nousepkg')
Brian Harringb938c782012-02-29 15:14:38 -0800128
129 try:
130 cros_build_lib.RunCommand(cmd, print_cmd=False)
131 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700132 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800133
134
135def DeleteChroot(chroot_path):
136 """Deletes an existing chroot"""
137 cmd = MAKE_CHROOT + ['--chroot', chroot_path,
138 '--delete']
139 try:
140 cros_build_lib.RunCommand(cmd, print_cmd=False)
141 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700142 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800143
144
Brian Harringae0a5322012-09-15 01:46:51 -0700145def EnterChroot(chroot_path, cache_dir, chrome_root, chrome_root_mount,
146 additional_args):
Brian Harringb938c782012-02-29 15:14:38 -0800147 """Enters an existing SDK chroot"""
Brian Harringae0a5322012-09-15 01:46:51 -0700148 cmd = ENTER_CHROOT + ['--chroot', chroot_path, '--cache_dir', cache_dir]
Brian Harringb938c782012-02-29 15:14:38 -0800149 if chrome_root:
150 cmd.extend(['--chrome_root', chrome_root])
151 if chrome_root_mount:
152 cmd.extend(['--chrome_root_mount', chrome_root_mount])
153 if len(additional_args) > 0:
154 cmd.append('--')
155 cmd.extend(additional_args)
Brian Harring7199e7d2012-03-23 04:10:08 -0700156
157 ret = cros_build_lib.RunCommand(cmd, print_cmd=False, error_code_ok=True)
158 # If we were in interactive mode, ignore the exit code; it'll be whatever
159 # they last ran w/in the chroot and won't matter to us one way or another.
160 # Note this does allow chroot entrance to fail and be ignored during
161 # interactive; this is however a rare case and the user will immediately
162 # see it (nor will they be checking the exit code manually).
163 if ret.returncode != 0 and additional_args:
164 raise SystemExit('Running %r failed with exit code %i'
165 % (cmd, ret.returncode))
Brian Harringb938c782012-02-29 15:14:38 -0800166
167
David James56e6c2c2012-10-24 23:54:41 -0700168def _SudoCommand():
169 """Get the 'sudo' command, along with all needed environment variables."""
170
David James5a73b4d2013-03-07 10:23:40 -0800171 # Pass in the ENVIRONMENT_WHITELIST and ENV_PASSTHRU variables so that
172 # scripts in the chroot know what variables to pass through.
David James56e6c2c2012-10-24 23:54:41 -0700173 cmd = ['sudo']
David James5a73b4d2013-03-07 10:23:40 -0800174 for key in constants.CHROOT_ENVIRONMENT_WHITELIST + constants.ENV_PASSTHRU:
David James56e6c2c2012-10-24 23:54:41 -0700175 value = os.environ.get(key)
176 if value is not None:
177 cmd += ['%s=%s' % (key, value)]
178
179 # Pass in the path to the depot_tools so that users can access them from
180 # within the chroot.
181 gclient = osutils.Which('gclient')
182 if gclient is not None:
183 cmd += ['DEPOT_TOOLS=%s' % os.path.realpath(os.path.dirname(gclient))]
184
185 return cmd
186
187
Mike Frysingera78a56e2012-11-20 06:02:30 -0500188def _ReExecuteIfNeeded(argv):
David James56e6c2c2012-10-24 23:54:41 -0700189 """Re-execute cros_sdk as root.
190
191 Also unshare the mount namespace so as to ensure that processes outside
192 the chroot can't mess with our mounts.
193 """
194 if os.geteuid() != 0:
Mike Frysingera78a56e2012-11-20 06:02:30 -0500195 cmd = _SudoCommand() + ['--'] + argv
196 os.execvp(cmd[0], cmd)
Mike Frysingera78a56e2012-11-20 06:02:30 -0500197 else:
Josh Triplette759b232013-03-08 13:03:43 -0800198 cgroups.Cgroup.InitSystem()
199 namespaces.Unshare(namespaces.CLONE_NEWNS)
David James56e6c2c2012-10-24 23:54:41 -0700200
201
Brian Harring6be2efc2012-03-01 05:04:00 -0800202def main(argv):
Brian Harring218e13c2012-10-10 16:21:26 -0700203 usage = """usage: %prog [options] [VAR1=val1 .. VARn=valn -- args]
Brian Harringb938c782012-02-29 15:14:38 -0800204
Brian Harring218e13c2012-10-10 16:21:26 -0700205This script is used for manipulating local chroot environments; creating,
206deleting, downloading, etc. If given --enter (or no args), it defaults
207to an interactive bash shell within the chroot.
Brian Harringb938c782012-02-29 15:14:38 -0800208
Brian Harring218e13c2012-10-10 16:21:26 -0700209If given args those are passed to the chroot environment, and executed."""
Mike Frysinger648ba2d2013-01-08 14:19:34 -0500210 conf = cros_build_lib.LoadKeyValueFile(
211 os.path.join(constants.SOURCE_ROOT, constants.SDK_VERSION_FILE),
212 ignore_missing=True)
Brian Harring1790ac42012-09-23 08:53:33 -0700213 sdk_latest_version = conf.get('SDK_LATEST_VERSION', '<unknown>')
214 bootstrap_latest_version = conf.get('BOOTSTRAP_LATEST_VERSION', '<unknown>')
215
Brian Harring218e13c2012-10-10 16:21:26 -0700216 parser = commandline.OptionParser(usage=usage, caching=True)
217
218 commands = parser.add_option_group("Commands")
219 commands.add_option(
220 '--enter', action='store_true', default=False,
221 help='Enter the SDK chroot. Implies --create.')
222 commands.add_option(
223 '--create', action='store_true',default=False,
224 help='Create the chroot only if it does not already exist. '
225 'Implies --download.')
226 commands.add_option(
227 '--bootstrap', action='store_true', default=False,
228 help='Build everything from scratch, including the sdk. '
229 'Use this only if you need to validate a change '
230 'that affects SDK creation itself (toolchain and '
231 'build are typically the only folk who need this). '
232 'Note this will quite heavily slow down the build. '
233 'This option implies --create --nousepkg.')
234 commands.add_option(
235 '-r', '--replace', action='store_true', default=False,
236 help='Replace an existing SDK chroot. Basically an alias '
237 'for --delete --create.')
238 commands.add_option(
239 '--delete', action='store_true', default=False,
240 help='Delete the current SDK chroot if it exists.')
241 commands.add_option(
242 '--download', action='store_true', default=False,
243 help='Download the sdk.')
Brian Harringb938c782012-02-29 15:14:38 -0800244
245 # Global options:
Mike Frysinger648ba2d2013-01-08 14:19:34 -0500246 default_chroot = os.path.join(constants.SOURCE_ROOT,
247 constants.DEFAULT_CHROOT_DIR)
Brian Harring218e13c2012-10-10 16:21:26 -0700248 parser.add_option(
249 '--chroot', dest='chroot', default=default_chroot, type='path',
250 help=('SDK chroot dir name [%s]' % constants.DEFAULT_CHROOT_DIR))
Brian Harringb938c782012-02-29 15:14:38 -0800251
Brian Harring218e13c2012-10-10 16:21:26 -0700252 parser.add_option('--chrome_root', default=None, type='path',
253 help='Mount this chrome root into the SDK chroot')
254 parser.add_option('--chrome_root_mount', default=None, type='path',
255 help='Mount chrome into this path inside SDK chroot')
256 parser.add_option('--nousepkg', action='store_true', default=False,
257 help='Do not use binary packages when creating a chroot.')
Brian Harringb938c782012-02-29 15:14:38 -0800258 parser.add_option('-u', '--url',
Brian Harringb6cf9142012-09-01 20:43:17 -0700259 dest='sdk_url', default=None,
Brian Harringb938c782012-02-29 15:14:38 -0800260 help=('''Use sdk tarball located at this url.
261 Use file:// for local files.'''))
Brian Harring1790ac42012-09-23 08:53:33 -0700262 parser.add_option('--sdk-version', default=None,
263 help='Use this sdk version. For prebuilt, current is %r'
264 ', for bootstrapping its %r.'
265 % (sdk_latest_version, bootstrap_latest_version))
Brian Harring218e13c2012-10-10 16:21:26 -0700266 options, chroot_command = parser.parse_args(argv)
Brian Harringb938c782012-02-29 15:14:38 -0800267
268 # Some sanity checks first, before we ask for sudo credentials.
Mike Frysinger8fd67dc2012-12-03 23:51:18 -0500269 cros_build_lib.AssertOutsideChroot()
Brian Harringb938c782012-02-29 15:14:38 -0800270
Brian Harring1790ac42012-09-23 08:53:33 -0700271 host = os.uname()[4]
Brian Harring1790ac42012-09-23 08:53:33 -0700272 if host != 'x86_64':
273 parser.error(
274 "cros_sdk is currently only supported on x86_64; you're running"
275 " %s. Please find a x86_64 machine." % (host,))
276
David Jamesaad5cc72012-10-26 15:03:13 -0700277 missing = osutils.FindMissingBinaries(NEEDED_TOOLS)
Brian Harring98b54902012-03-23 04:05:42 -0700278 if missing:
279 parser.error((
David James471532c2013-01-21 10:23:31 -0800280 'The tool(s) %s were not found.\n'
281 'Please install the appropriate package in your host.\n'
282 'Example(ubuntu):\n'
Brian Harring98b54902012-03-23 04:05:42 -0700283 ' sudo apt-get install <packagename>'
284 % (', '.join(missing))))
Brian Harringb938c782012-02-29 15:14:38 -0800285
David James471532c2013-01-21 10:23:31 -0800286 _ReExecuteIfNeeded([sys.argv[0]] + argv)
287
Brian Harring218e13c2012-10-10 16:21:26 -0700288 # Expand out the aliases...
289 if options.replace:
290 options.delete = options.create = True
Brian Harringb938c782012-02-29 15:14:38 -0800291
Brian Harring218e13c2012-10-10 16:21:26 -0700292 if options.bootstrap:
293 options.create = True
Brian Harringb938c782012-02-29 15:14:38 -0800294
Brian Harring218e13c2012-10-10 16:21:26 -0700295 # If a command is not given, default to enter.
296 options.enter |= not any(getattr(options, x.dest)
297 for x in commands.option_list)
298 options.enter |= bool(chroot_command)
299
300 if options.enter and options.delete and not options.create:
301 parser.error("Trying to enter the chroot when --delete "
302 "was specified makes no sense.")
303
304 # Finally, discern if we need to create the chroot.
305 chroot_exists = os.path.exists(options.chroot)
306 if options.create or options.enter:
307 # Only create if it's being wiped, or if it doesn't exist.
308 if not options.delete and chroot_exists:
309 options.create = False
310 else:
311 options.download = True
312
313 # Finally, flip create if necessary.
314 if options.enter:
315 options.create |= not chroot_exists
Brian Harringb938c782012-02-29 15:14:38 -0800316
Brian Harringb938c782012-02-29 15:14:38 -0800317 if not options.sdk_version:
Brian Harring1790ac42012-09-23 08:53:33 -0700318 sdk_version = (bootstrap_latest_version if options.bootstrap
319 else sdk_latest_version)
Brian Harringb938c782012-02-29 15:14:38 -0800320 else:
321 sdk_version = options.sdk_version
322
Brian Harring1790ac42012-09-23 08:53:33 -0700323 # Based on selections, fetch the tarball.
324 if options.sdk_url:
325 urls = [options.sdk_url]
326 elif options.bootstrap:
327 urls = GetStage3Urls(sdk_version)
328 else:
329 urls = GetArchStageTarballs(sdk_version)
330
Brian Harringb6cf9142012-09-01 20:43:17 -0700331 lock_path = os.path.dirname(options.chroot)
Brian Harringb938c782012-02-29 15:14:38 -0800332 lock_path = os.path.join(lock_path,
Brian Harringb6cf9142012-09-01 20:43:17 -0700333 '.%s_lock' % os.path.basename(options.chroot))
David James56e6c2c2012-10-24 23:54:41 -0700334 with cgroups.SimpleContainChildren('cros_sdk'):
335 with locking.FileLock(lock_path, 'chroot lock') as lock:
Brian Harring1790ac42012-09-23 08:53:33 -0700336
David James56e6c2c2012-10-24 23:54:41 -0700337 if options.delete and os.path.exists(options.chroot):
338 lock.write_lock()
339 DeleteChroot(options.chroot)
Brian Harringb938c782012-02-29 15:14:38 -0800340
David James56e6c2c2012-10-24 23:54:41 -0700341 sdk_cache = os.path.join(options.cache_dir, 'sdks')
342 distfiles_cache = os.path.join(options.cache_dir, 'distfiles')
343 osutils.SafeMakedirs(options.cache_dir)
Brian Harringae0a5322012-09-15 01:46:51 -0700344
David James56e6c2c2012-10-24 23:54:41 -0700345 for target in (sdk_cache, distfiles_cache):
Mike Frysinger648ba2d2013-01-08 14:19:34 -0500346 src = os.path.join(constants.SOURCE_ROOT, os.path.basename(target))
David James56e6c2c2012-10-24 23:54:41 -0700347 if not os.path.exists(src):
348 osutils.SafeMakedirs(target)
349 continue
350 lock.write_lock(
351 "Upgrade to %r needed but chroot is locked; please exit "
352 "all instances so this upgrade can finish." % src)
353 if not os.path.exists(src):
354 # Note that while waiting for the write lock, src may've vanished;
355 # it's a rare race during the upgrade process that's a byproduct
356 # of us avoiding taking a write lock to do the src check. If we
357 # took a write lock for that check, it would effectively limit
358 # all cros_sdk for a chroot to a single instance.
359 osutils.SafeMakedirs(target)
360 elif not os.path.exists(target):
361 # Upgrade occurred, but a reversion, or something whacky
362 # occurred writing to the old location. Wipe and continue.
363 os.rename(src, target)
364 else:
365 # Upgrade occurred once already, but either a reversion or
366 # some before/after separate cros_sdk usage is at play.
367 # Wipe and continue.
368 osutils.RmDir(src)
Brian Harringae0a5322012-09-15 01:46:51 -0700369
David James56e6c2c2012-10-24 23:54:41 -0700370 if options.download:
371 lock.write_lock()
372 sdk_tarball = FetchRemoteTarballs(sdk_cache, urls)
Brian Harring218e13c2012-10-10 16:21:26 -0700373
David James56e6c2c2012-10-24 23:54:41 -0700374 if options.create:
375 lock.write_lock()
376 CreateChroot(options.chroot, sdk_tarball, options.cache_dir,
377 nousepkg=(options.bootstrap or options.nousepkg))
Brian Harring1790ac42012-09-23 08:53:33 -0700378
David James56e6c2c2012-10-24 23:54:41 -0700379 if options.enter:
380 lock.read_lock()
381 EnterChroot(options.chroot, options.cache_dir, options.chrome_root,
382 options.chrome_root_mount, chroot_command)