blob: 02e49f3be7e287cbef7e7c3d6d509ef481bb3505 [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
Mike Frysinger5aba4dd2013-01-16 16:42:36 -050017from chromite.lib import gs
Brian Harringb938c782012-02-29 15:14:38 -080018from chromite.lib import locking
Brian Harringae0a5322012-09-15 01:46:51 -070019from chromite.lib import osutils
Brian Harringb938c782012-02-29 15:14:38 -080020
21cros_build_lib.STRICT_SUDO = True
22
23
Mike Frysinger5aba4dd2013-01-16 16:42:36 -050024DEFAULT_URL = gs.PUBLIC_BASE_HTTPS_URL + 'chromiumos-sdk'
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
33# We need these tools to run. Very common tools (tar,..) are ommited.
David James56e6c2c2012-10-24 23:54:41 -070034NEEDED_TOOLS = ('curl', 'xz', 'unshare')
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'}
40 return ['%s/cros-sdk-%s.%s'
41 % (DEFAULT_URL, version, extension[compressor])
42 for compressor in COMPRESSION_PREFERENCE]
43
44
45def GetStage3Urls(version):
46 return ['%s/stage3-amd64-%s.tar.%s' % (DEFAULT_URL, version, ext)
47 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
171 # Pass in the ENVIRONMENT_WHITELIST variable so that scripts in the chroot
172 # know what variables to pass through.
173 cmd = ['sudo']
174 for key in constants.CHROOT_ENVIRONMENT_WHITELIST:
175 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 """
Mike Frysingera78a56e2012-11-20 06:02:30 -0500194 MAGIC_VAR = '%CROS_SDK_MOUNT_NS'
David James56e6c2c2012-10-24 23:54:41 -0700195 if os.geteuid() != 0:
Mike Frysingera78a56e2012-11-20 06:02:30 -0500196 cmd = _SudoCommand() + ['--'] + argv
197 os.execvp(cmd[0], cmd)
198 elif os.environ.get(MAGIC_VAR, '0') == '0':
199 cgroups.Cgroup.InitSystem()
200 os.environ[MAGIC_VAR] = '1'
201 os.execvp('unshare', ['unshare', '-m', '--'] + argv)
202 else:
203 os.environ.pop(MAGIC_VAR)
David James56e6c2c2012-10-24 23:54:41 -0700204
205
Brian Harring6be2efc2012-03-01 05:04:00 -0800206def main(argv):
Brian Harring218e13c2012-10-10 16:21:26 -0700207 usage = """usage: %prog [options] [VAR1=val1 .. VARn=valn -- args]
Brian Harringb938c782012-02-29 15:14:38 -0800208
Brian Harring218e13c2012-10-10 16:21:26 -0700209This script is used for manipulating local chroot environments; creating,
210deleting, downloading, etc. If given --enter (or no args), it defaults
211to an interactive bash shell within the chroot.
Brian Harringb938c782012-02-29 15:14:38 -0800212
Brian Harring218e13c2012-10-10 16:21:26 -0700213If given args those are passed to the chroot environment, and executed."""
Mike Frysinger648ba2d2013-01-08 14:19:34 -0500214 conf = cros_build_lib.LoadKeyValueFile(
215 os.path.join(constants.SOURCE_ROOT, constants.SDK_VERSION_FILE),
216 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:
Mike Frysinger648ba2d2013-01-08 14:19:34 -0500250 default_chroot = os.path.join(constants.SOURCE_ROOT,
251 constants.DEFAULT_CHROOT_DIR)
Brian Harring218e13c2012-10-10 16:21:26 -0700252 parser.add_option(
253 '--chroot', dest='chroot', default=default_chroot, type='path',
254 help=('SDK chroot dir name [%s]' % constants.DEFAULT_CHROOT_DIR))
Brian Harringb938c782012-02-29 15:14:38 -0800255
Brian Harring218e13c2012-10-10 16:21:26 -0700256 parser.add_option('--chrome_root', default=None, type='path',
257 help='Mount this chrome root into the SDK chroot')
258 parser.add_option('--chrome_root_mount', default=None, type='path',
259 help='Mount chrome into this path inside SDK chroot')
260 parser.add_option('--nousepkg', action='store_true', default=False,
261 help='Do not use binary packages when creating a chroot.')
Brian Harringb938c782012-02-29 15:14:38 -0800262 parser.add_option('-u', '--url',
Brian Harringb6cf9142012-09-01 20:43:17 -0700263 dest='sdk_url', default=None,
Brian Harringb938c782012-02-29 15:14:38 -0800264 help=('''Use sdk tarball located at this url.
265 Use file:// for local files.'''))
Brian Harring1790ac42012-09-23 08:53:33 -0700266 parser.add_option('--sdk-version', default=None,
267 help='Use this sdk version. For prebuilt, current is %r'
268 ', for bootstrapping its %r.'
269 % (sdk_latest_version, bootstrap_latest_version))
Brian Harring218e13c2012-10-10 16:21:26 -0700270 options, chroot_command = parser.parse_args(argv)
Brian Harringb938c782012-02-29 15:14:38 -0800271
272 # Some sanity checks first, before we ask for sudo credentials.
Mike Frysinger8fd67dc2012-12-03 23:51:18 -0500273 cros_build_lib.AssertOutsideChroot()
Brian Harringb938c782012-02-29 15:14:38 -0800274
Mike Frysingera78a56e2012-11-20 06:02:30 -0500275 _ReExecuteIfNeeded([sys.argv[0]] + argv)
David James56e6c2c2012-10-24 23:54:41 -0700276
Brian Harring1790ac42012-09-23 08:53:33 -0700277 host = os.uname()[4]
Brian Harring1790ac42012-09-23 08:53:33 -0700278 if host != 'x86_64':
279 parser.error(
280 "cros_sdk is currently only supported on x86_64; you're running"
281 " %s. Please find a x86_64 machine." % (host,))
282
David Jamesaad5cc72012-10-26 15:03:13 -0700283 missing = osutils.FindMissingBinaries(NEEDED_TOOLS)
Brian Harring98b54902012-03-23 04:05:42 -0700284 if missing:
285 parser.error((
286 'The tool(s) %s were not found.'
287 'Please install the appropriate package in your host.'
288 'Example(ubuntu):'
289 ' sudo apt-get install <packagename>'
290 % (', '.join(missing))))
Brian Harringb938c782012-02-29 15:14:38 -0800291
Brian Harring218e13c2012-10-10 16:21:26 -0700292 # Expand out the aliases...
293 if options.replace:
294 options.delete = options.create = True
Brian Harringb938c782012-02-29 15:14:38 -0800295
Brian Harring218e13c2012-10-10 16:21:26 -0700296 if options.bootstrap:
297 options.create = True
Brian Harringb938c782012-02-29 15:14:38 -0800298
Brian Harring218e13c2012-10-10 16:21:26 -0700299 # If a command is not given, default to enter.
300 options.enter |= not any(getattr(options, x.dest)
301 for x in commands.option_list)
302 options.enter |= bool(chroot_command)
303
304 if options.enter and options.delete and not options.create:
305 parser.error("Trying to enter the chroot when --delete "
306 "was specified makes no sense.")
307
308 # Finally, discern if we need to create the chroot.
309 chroot_exists = os.path.exists(options.chroot)
310 if options.create or options.enter:
311 # Only create if it's being wiped, or if it doesn't exist.
312 if not options.delete and chroot_exists:
313 options.create = False
314 else:
315 options.download = True
316
317 # Finally, flip create if necessary.
318 if options.enter:
319 options.create |= not chroot_exists
Brian Harringb938c782012-02-29 15:14:38 -0800320
Brian Harringb938c782012-02-29 15:14:38 -0800321 if not options.sdk_version:
Brian Harring1790ac42012-09-23 08:53:33 -0700322 sdk_version = (bootstrap_latest_version if options.bootstrap
323 else sdk_latest_version)
Brian Harringb938c782012-02-29 15:14:38 -0800324 else:
325 sdk_version = options.sdk_version
326
Brian Harring1790ac42012-09-23 08:53:33 -0700327 # Based on selections, fetch the tarball.
328 if options.sdk_url:
329 urls = [options.sdk_url]
330 elif options.bootstrap:
331 urls = GetStage3Urls(sdk_version)
332 else:
333 urls = GetArchStageTarballs(sdk_version)
334
Brian Harringb6cf9142012-09-01 20:43:17 -0700335 lock_path = os.path.dirname(options.chroot)
Brian Harringb938c782012-02-29 15:14:38 -0800336 lock_path = os.path.join(lock_path,
Brian Harringb6cf9142012-09-01 20:43:17 -0700337 '.%s_lock' % os.path.basename(options.chroot))
David James56e6c2c2012-10-24 23:54:41 -0700338 with cgroups.SimpleContainChildren('cros_sdk'):
339 with locking.FileLock(lock_path, 'chroot lock') as lock:
Brian Harring1790ac42012-09-23 08:53:33 -0700340
David James56e6c2c2012-10-24 23:54:41 -0700341 if options.delete and os.path.exists(options.chroot):
342 lock.write_lock()
343 DeleteChroot(options.chroot)
Brian Harringb938c782012-02-29 15:14:38 -0800344
David James56e6c2c2012-10-24 23:54:41 -0700345 sdk_cache = os.path.join(options.cache_dir, 'sdks')
346 distfiles_cache = os.path.join(options.cache_dir, 'distfiles')
347 osutils.SafeMakedirs(options.cache_dir)
Brian Harringae0a5322012-09-15 01:46:51 -0700348
David James56e6c2c2012-10-24 23:54:41 -0700349 for target in (sdk_cache, distfiles_cache):
Mike Frysinger648ba2d2013-01-08 14:19:34 -0500350 src = os.path.join(constants.SOURCE_ROOT, os.path.basename(target))
David James56e6c2c2012-10-24 23:54:41 -0700351 if not os.path.exists(src):
352 osutils.SafeMakedirs(target)
353 continue
354 lock.write_lock(
355 "Upgrade to %r needed but chroot is locked; please exit "
356 "all instances so this upgrade can finish." % src)
357 if not os.path.exists(src):
358 # Note that while waiting for the write lock, src may've vanished;
359 # it's a rare race during the upgrade process that's a byproduct
360 # of us avoiding taking a write lock to do the src check. If we
361 # took a write lock for that check, it would effectively limit
362 # all cros_sdk for a chroot to a single instance.
363 osutils.SafeMakedirs(target)
364 elif not os.path.exists(target):
365 # Upgrade occurred, but a reversion, or something whacky
366 # occurred writing to the old location. Wipe and continue.
367 os.rename(src, target)
368 else:
369 # Upgrade occurred once already, but either a reversion or
370 # some before/after separate cros_sdk usage is at play.
371 # Wipe and continue.
372 osutils.RmDir(src)
Brian Harringae0a5322012-09-15 01:46:51 -0700373
David James56e6c2c2012-10-24 23:54:41 -0700374 if options.download:
375 lock.write_lock()
376 sdk_tarball = FetchRemoteTarballs(sdk_cache, urls)
Brian Harring218e13c2012-10-10 16:21:26 -0700377
David James56e6c2c2012-10-24 23:54:41 -0700378 if options.create:
379 lock.write_lock()
380 CreateChroot(options.chroot, sdk_tarball, options.cache_dir,
381 nousepkg=(options.bootstrap or options.nousepkg))
Brian Harring1790ac42012-09-23 08:53:33 -0700382
David James56e6c2c2012-10-24 23:54:41 -0700383 if options.enter:
384 lock.read_lock()
385 EnterChroot(options.chroot, options.cache_dir, options.chrome_root,
386 options.chrome_root_mount, chroot_command)