blob: efbf00624525f2e5b4824cb824dcf78e1b913339 [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 Harring218e13c2012-10-10 16:21:26 -07009import errno
Brian Harringb938c782012-02-29 15:14:38 -080010import os
David James56e6c2c2012-10-24 23:54:41 -070011import sys
Brian Harringb938c782012-02-29 15:14:38 -080012import urlparse
13
14from chromite.buildbot import constants
Brian Harringcfe762a2012-02-29 13:03:53 -080015from chromite.lib import cgroups
Brian Harringb6cf9142012-09-01 20:43:17 -070016from chromite.lib import commandline
Brian Harringb938c782012-02-29 15:14:38 -080017from chromite.lib import cros_build_lib
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
Brian Harring1790ac42012-09-23 08:53:33 -070024DEFAULT_URL = 'https://commondatastorage.googleapis.com/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 -080027SRC_ROOT = os.path.realpath(constants.SOURCE_ROOT)
Brian Harringb938c782012-02-29 15:14:38 -080028OVERLAY_DIR = os.path.join(SRC_ROOT, 'src/third_party/chromiumos-overlay')
29SDK_VERSION_FILE = os.path.join(OVERLAY_DIR,
30 'chromeos/binhost/host/sdk_version.conf')
31
32# TODO(zbehan): Remove the dependency on these, reimplement them in python
33MAKE_CHROOT = [os.path.join(SRC_ROOT, 'src/scripts/sdk_lib/make_chroot.sh')]
34ENTER_CHROOT = [os.path.join(SRC_ROOT, 'src/scripts/sdk_lib/enter_chroot.sh')]
35
36# We need these tools to run. Very common tools (tar,..) are ommited.
David James56e6c2c2012-10-24 23:54:41 -070037NEEDED_TOOLS = ('curl', 'xz', 'unshare')
Brian Harringb938c782012-02-29 15:14:38 -080038
Brian Harringb938c782012-02-29 15:14:38 -080039
Brian Harring1790ac42012-09-23 08:53:33 -070040def GetSdkConfig():
Brian Harringb938c782012-02-29 15:14:38 -080041 """Extracts latest version from chromiumos-overlay."""
Brian Harring1790ac42012-09-23 08:53:33 -070042 d = {}
Brian Harring218e13c2012-10-10 16:21:26 -070043 try:
44 with open(SDK_VERSION_FILE) as f:
45 for raw_line in f:
46 line = raw_line.split('#')[0].strip()
47 if not line:
48 continue
49 chunks = line.split('=', 1)
50 if len(chunks) != 2:
51 raise Exception('Malformed version file; line %r' % raw_line)
52 d[chunks[0]] = chunks[1].strip().strip('"')
53 except EnvironmentError, e:
David James0c474e02012-11-29 15:32:23 -080054 if e.errno != errno.ENOENT:
Brian Harring218e13c2012-10-10 16:21:26 -070055 raise
Brian Harring1790ac42012-09-23 08:53:33 -070056 return d
Brian Harringb938c782012-02-29 15:14:38 -080057
58
Brian Harring1790ac42012-09-23 08:53:33 -070059def GetArchStageTarballs(version):
Brian Harringb938c782012-02-29 15:14:38 -080060 """Returns the URL for a given arch/version"""
Brian Harring1790ac42012-09-23 08:53:33 -070061 extension = {'bz2':'tbz2', 'xz':'tar.xz'}
62 return ['%s/cros-sdk-%s.%s'
63 % (DEFAULT_URL, version, extension[compressor])
64 for compressor in COMPRESSION_PREFERENCE]
65
66
67def GetStage3Urls(version):
68 return ['%s/stage3-amd64-%s.tar.%s' % (DEFAULT_URL, version, ext)
69 for ext in COMPRESSION_PREFERENCE]
Brian Harringb938c782012-02-29 15:14:38 -080070
71
Brian Harringae0a5322012-09-15 01:46:51 -070072def FetchRemoteTarballs(storage_dir, urls):
Zdenek Behanfd0efe42012-04-13 04:36:40 +020073 """Fetches a tarball given by url, and place it in sdk/.
74
75 Args:
76 urls: List of URLs to try to download. Download will stop on first success.
77
78 Returns:
79 Full path to the downloaded file
80 """
Zdenek Behanfd0efe42012-04-13 04:36:40 +020081
Brian Harring1790ac42012-09-23 08:53:33 -070082 # Note we track content length ourselves since certain versions of curl
83 # fail if asked to resume a complete file.
84 # pylint: disable=C0301,W0631
85 # https://sourceforge.net/tracker/?func=detail&atid=100976&aid=3482927&group_id=976
Zdenek Behanfd0efe42012-04-13 04:36:40 +020086 for url in urls:
Brian Harring1790ac42012-09-23 08:53:33 -070087 # http://www.logilab.org/ticket/8766
88 # pylint: disable=E1101
89 parsed = urlparse.urlparse(url)
90 tarball_name = os.path.basename(parsed.path)
91 if parsed.scheme in ('', 'file'):
92 if os.path.exists(parsed.path):
93 return parsed.path
94 continue
95 content_length = 0
Zdenek Behanfd0efe42012-04-13 04:36:40 +020096 print 'Attempting download: %s' % url
Brian Harring1790ac42012-09-23 08:53:33 -070097 result = cros_build_lib.RunCurl(
98 ['-I', url], redirect_stdout=True, redirect_stderr=True,
99 print_cmd=False)
100 successful = False
101 for header in result.output.splitlines():
102 # We must walk the output to find the string '200 OK' for use cases where
103 # a proxy is involved and may have pushed down the actual header.
104 if header.find('200 OK') != -1:
105 successful = True
106 elif header.lower().startswith("content-length:"):
107 content_length = int(header.split(":", 1)[-1].strip())
108 if successful:
109 break
110 if successful:
Zdenek Behanfd0efe42012-04-13 04:36:40 +0200111 break
112 else:
113 raise Exception('No valid URLs found!')
114
Brian Harringae0a5322012-09-15 01:46:51 -0700115 tarball_dest = os.path.join(storage_dir, tarball_name)
Brian Harring1790ac42012-09-23 08:53:33 -0700116 current_size = 0
117 if os.path.exists(tarball_dest):
118 current_size = os.path.getsize(tarball_dest)
119 if current_size > content_length:
David James56e6c2c2012-10-24 23:54:41 -0700120 osutils.SafeUnlink(tarball_dest)
Brian Harring1790ac42012-09-23 08:53:33 -0700121 current_size = 0
Zdenek Behanb2fa72e2012-03-16 04:49:30 +0100122
Brian Harring1790ac42012-09-23 08:53:33 -0700123 if current_size < content_length:
124 cros_build_lib.RunCurl(
125 ['-f', '-L', '-y', '30', '-C', '-', '--output', tarball_dest, url],
126 print_cmd=False)
Brian Harringb938c782012-02-29 15:14:38 -0800127
Brian Harring1790ac42012-09-23 08:53:33 -0700128 # Cleanup old tarballs now since we've successfull fetched; only cleanup
129 # the tarballs for our prefix, or unknown ones.
130 ignored_prefix = ('stage3-' if tarball_name.startswith('cros-sdk-')
131 else 'cros-sdk-')
132 for filename in os.listdir(storage_dir):
133 if filename == tarball_name or filename.startswith(ignored_prefix):
134 continue
Brian Harringb938c782012-02-29 15:14:38 -0800135
Brian Harring1790ac42012-09-23 08:53:33 -0700136 print 'Cleaning up old tarball: %s' % (filename,)
David James56e6c2c2012-10-24 23:54:41 -0700137 osutils.SafeUnlink(os.path.join(storage_dir, filename))
Zdenek Behan9c644dd2012-04-05 06:24:02 +0200138
Brian Harringb938c782012-02-29 15:14:38 -0800139 return tarball_dest
140
141
Brian Harring1790ac42012-09-23 08:53:33 -0700142def CreateChroot(chroot_path, sdk_tarball, cache_dir, nousepkg=False):
Brian Harringb938c782012-02-29 15:14:38 -0800143 """Creates a new chroot from a given SDK"""
Brian Harringb938c782012-02-29 15:14:38 -0800144
Brian Harring1790ac42012-09-23 08:53:33 -0700145 cmd = MAKE_CHROOT + ['--stage3_path', sdk_tarball,
Brian Harringae0a5322012-09-15 01:46:51 -0700146 '--chroot', chroot_path,
147 '--cache_dir', cache_dir]
Mike Frysinger2de7f042012-07-10 04:45:03 -0400148 if nousepkg:
149 cmd.append('--nousepkg')
Brian Harringb938c782012-02-29 15:14:38 -0800150
151 try:
152 cros_build_lib.RunCommand(cmd, print_cmd=False)
153 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700154 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800155
156
157def DeleteChroot(chroot_path):
158 """Deletes an existing chroot"""
159 cmd = MAKE_CHROOT + ['--chroot', chroot_path,
160 '--delete']
161 try:
162 cros_build_lib.RunCommand(cmd, print_cmd=False)
163 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700164 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800165
166
Brian Harringae0a5322012-09-15 01:46:51 -0700167def EnterChroot(chroot_path, cache_dir, chrome_root, chrome_root_mount,
168 additional_args):
Brian Harringb938c782012-02-29 15:14:38 -0800169 """Enters an existing SDK chroot"""
Brian Harringae0a5322012-09-15 01:46:51 -0700170 cmd = ENTER_CHROOT + ['--chroot', chroot_path, '--cache_dir', cache_dir]
Brian Harringb938c782012-02-29 15:14:38 -0800171 if chrome_root:
172 cmd.extend(['--chrome_root', chrome_root])
173 if chrome_root_mount:
174 cmd.extend(['--chrome_root_mount', chrome_root_mount])
175 if len(additional_args) > 0:
176 cmd.append('--')
177 cmd.extend(additional_args)
Brian Harring7199e7d2012-03-23 04:10:08 -0700178
179 ret = cros_build_lib.RunCommand(cmd, print_cmd=False, error_code_ok=True)
180 # If we were in interactive mode, ignore the exit code; it'll be whatever
181 # they last ran w/in the chroot and won't matter to us one way or another.
182 # Note this does allow chroot entrance to fail and be ignored during
183 # interactive; this is however a rare case and the user will immediately
184 # see it (nor will they be checking the exit code manually).
185 if ret.returncode != 0 and additional_args:
186 raise SystemExit('Running %r failed with exit code %i'
187 % (cmd, ret.returncode))
Brian Harringb938c782012-02-29 15:14:38 -0800188
189
David James56e6c2c2012-10-24 23:54:41 -0700190def _SudoCommand():
191 """Get the 'sudo' command, along with all needed environment variables."""
192
193 # Pass in the ENVIRONMENT_WHITELIST variable so that scripts in the chroot
194 # know what variables to pass through.
195 cmd = ['sudo']
196 for key in constants.CHROOT_ENVIRONMENT_WHITELIST:
197 value = os.environ.get(key)
198 if value is not None:
199 cmd += ['%s=%s' % (key, value)]
200
201 # Pass in the path to the depot_tools so that users can access them from
202 # within the chroot.
203 gclient = osutils.Which('gclient')
204 if gclient is not None:
205 cmd += ['DEPOT_TOOLS=%s' % os.path.realpath(os.path.dirname(gclient))]
206
207 return cmd
208
209
Mike Frysingera78a56e2012-11-20 06:02:30 -0500210def _ReExecuteIfNeeded(argv):
David James56e6c2c2012-10-24 23:54:41 -0700211 """Re-execute cros_sdk as root.
212
213 Also unshare the mount namespace so as to ensure that processes outside
214 the chroot can't mess with our mounts.
215 """
Mike Frysingera78a56e2012-11-20 06:02:30 -0500216 MAGIC_VAR = '%CROS_SDK_MOUNT_NS'
David James56e6c2c2012-10-24 23:54:41 -0700217 if os.geteuid() != 0:
Mike Frysingera78a56e2012-11-20 06:02:30 -0500218 cmd = _SudoCommand() + ['--'] + argv
219 os.execvp(cmd[0], cmd)
220 elif os.environ.get(MAGIC_VAR, '0') == '0':
221 cgroups.Cgroup.InitSystem()
222 os.environ[MAGIC_VAR] = '1'
223 os.execvp('unshare', ['unshare', '-m', '--'] + argv)
224 else:
225 os.environ.pop(MAGIC_VAR)
David James56e6c2c2012-10-24 23:54:41 -0700226
227
Brian Harring6be2efc2012-03-01 05:04:00 -0800228def main(argv):
Brian Harring218e13c2012-10-10 16:21:26 -0700229 usage = """usage: %prog [options] [VAR1=val1 .. VARn=valn -- args]
Brian Harringb938c782012-02-29 15:14:38 -0800230
Brian Harring218e13c2012-10-10 16:21:26 -0700231This script is used for manipulating local chroot environments; creating,
232deleting, downloading, etc. If given --enter (or no args), it defaults
233to an interactive bash shell within the chroot.
Brian Harringb938c782012-02-29 15:14:38 -0800234
Brian Harring218e13c2012-10-10 16:21:26 -0700235If given args those are passed to the chroot environment, and executed."""
Brian Harring1790ac42012-09-23 08:53:33 -0700236 conf = GetSdkConfig()
237 sdk_latest_version = conf.get('SDK_LATEST_VERSION', '<unknown>')
238 bootstrap_latest_version = conf.get('BOOTSTRAP_LATEST_VERSION', '<unknown>')
239
Brian Harring218e13c2012-10-10 16:21:26 -0700240 parser = commandline.OptionParser(usage=usage, caching=True)
241
242 commands = parser.add_option_group("Commands")
243 commands.add_option(
244 '--enter', action='store_true', default=False,
245 help='Enter the SDK chroot. Implies --create.')
246 commands.add_option(
247 '--create', action='store_true',default=False,
248 help='Create the chroot only if it does not already exist. '
249 'Implies --download.')
250 commands.add_option(
251 '--bootstrap', action='store_true', default=False,
252 help='Build everything from scratch, including the sdk. '
253 'Use this only if you need to validate a change '
254 'that affects SDK creation itself (toolchain and '
255 'build are typically the only folk who need this). '
256 'Note this will quite heavily slow down the build. '
257 'This option implies --create --nousepkg.')
258 commands.add_option(
259 '-r', '--replace', action='store_true', default=False,
260 help='Replace an existing SDK chroot. Basically an alias '
261 'for --delete --create.')
262 commands.add_option(
263 '--delete', action='store_true', default=False,
264 help='Delete the current SDK chroot if it exists.')
265 commands.add_option(
266 '--download', action='store_true', default=False,
267 help='Download the sdk.')
Brian Harringb938c782012-02-29 15:14:38 -0800268
269 # Global options:
Brian Harringb6cf9142012-09-01 20:43:17 -0700270 default_chroot = os.path.join(SRC_ROOT, constants.DEFAULT_CHROOT_DIR)
Brian Harring218e13c2012-10-10 16:21:26 -0700271 parser.add_option(
272 '--chroot', dest='chroot', default=default_chroot, type='path',
273 help=('SDK chroot dir name [%s]' % constants.DEFAULT_CHROOT_DIR))
Brian Harringb938c782012-02-29 15:14:38 -0800274
Brian Harring218e13c2012-10-10 16:21:26 -0700275 parser.add_option('--chrome_root', default=None, type='path',
276 help='Mount this chrome root into the SDK chroot')
277 parser.add_option('--chrome_root_mount', default=None, type='path',
278 help='Mount chrome into this path inside SDK chroot')
279 parser.add_option('--nousepkg', action='store_true', default=False,
280 help='Do not use binary packages when creating a chroot.')
Brian Harringb938c782012-02-29 15:14:38 -0800281 parser.add_option('-u', '--url',
Brian Harringb6cf9142012-09-01 20:43:17 -0700282 dest='sdk_url', default=None,
Brian Harringb938c782012-02-29 15:14:38 -0800283 help=('''Use sdk tarball located at this url.
284 Use file:// for local files.'''))
Brian Harring1790ac42012-09-23 08:53:33 -0700285 parser.add_option('--sdk-version', default=None,
286 help='Use this sdk version. For prebuilt, current is %r'
287 ', for bootstrapping its %r.'
288 % (sdk_latest_version, bootstrap_latest_version))
Brian Harring218e13c2012-10-10 16:21:26 -0700289 options, chroot_command = parser.parse_args(argv)
Brian Harringb938c782012-02-29 15:14:38 -0800290
291 # Some sanity checks first, before we ask for sudo credentials.
292 if cros_build_lib.IsInsideChroot():
Brian Harring98b54902012-03-23 04:05:42 -0700293 parser.error("This needs to be ran outside the chroot")
Brian Harringb938c782012-02-29 15:14:38 -0800294
Mike Frysingera78a56e2012-11-20 06:02:30 -0500295 _ReExecuteIfNeeded([sys.argv[0]] + argv)
David James56e6c2c2012-10-24 23:54:41 -0700296
Brian Harring1790ac42012-09-23 08:53:33 -0700297 host = os.uname()[4]
Brian Harring1790ac42012-09-23 08:53:33 -0700298 if host != 'x86_64':
299 parser.error(
300 "cros_sdk is currently only supported on x86_64; you're running"
301 " %s. Please find a x86_64 machine." % (host,))
302
David Jamesaad5cc72012-10-26 15:03:13 -0700303 missing = osutils.FindMissingBinaries(NEEDED_TOOLS)
Brian Harring98b54902012-03-23 04:05:42 -0700304 if missing:
305 parser.error((
306 'The tool(s) %s were not found.'
307 'Please install the appropriate package in your host.'
308 'Example(ubuntu):'
309 ' sudo apt-get install <packagename>'
310 % (', '.join(missing))))
Brian Harringb938c782012-02-29 15:14:38 -0800311
Brian Harring218e13c2012-10-10 16:21:26 -0700312 # Expand out the aliases...
313 if options.replace:
314 options.delete = options.create = True
Brian Harringb938c782012-02-29 15:14:38 -0800315
Brian Harring218e13c2012-10-10 16:21:26 -0700316 if options.bootstrap:
317 options.create = True
Brian Harringb938c782012-02-29 15:14:38 -0800318
Brian Harring218e13c2012-10-10 16:21:26 -0700319 # If a command is not given, default to enter.
320 options.enter |= not any(getattr(options, x.dest)
321 for x in commands.option_list)
322 options.enter |= bool(chroot_command)
323
324 if options.enter and options.delete and not options.create:
325 parser.error("Trying to enter the chroot when --delete "
326 "was specified makes no sense.")
327
328 # Finally, discern if we need to create the chroot.
329 chroot_exists = os.path.exists(options.chroot)
330 if options.create or options.enter:
331 # Only create if it's being wiped, or if it doesn't exist.
332 if not options.delete and chroot_exists:
333 options.create = False
334 else:
335 options.download = True
336
337 # Finally, flip create if necessary.
338 if options.enter:
339 options.create |= not chroot_exists
Brian Harringb938c782012-02-29 15:14:38 -0800340
Brian Harringb938c782012-02-29 15:14:38 -0800341 if not options.sdk_version:
Brian Harring1790ac42012-09-23 08:53:33 -0700342 sdk_version = (bootstrap_latest_version if options.bootstrap
343 else sdk_latest_version)
Brian Harringb938c782012-02-29 15:14:38 -0800344 else:
345 sdk_version = options.sdk_version
346
Brian Harring1790ac42012-09-23 08:53:33 -0700347 # Based on selections, fetch the tarball.
348 if options.sdk_url:
349 urls = [options.sdk_url]
350 elif options.bootstrap:
351 urls = GetStage3Urls(sdk_version)
352 else:
353 urls = GetArchStageTarballs(sdk_version)
354
Brian Harringb6cf9142012-09-01 20:43:17 -0700355 lock_path = os.path.dirname(options.chroot)
Brian Harringb938c782012-02-29 15:14:38 -0800356 lock_path = os.path.join(lock_path,
Brian Harringb6cf9142012-09-01 20:43:17 -0700357 '.%s_lock' % os.path.basename(options.chroot))
David James56e6c2c2012-10-24 23:54:41 -0700358 with cgroups.SimpleContainChildren('cros_sdk'):
359 with locking.FileLock(lock_path, 'chroot lock') as lock:
Brian Harring1790ac42012-09-23 08:53:33 -0700360
David James56e6c2c2012-10-24 23:54:41 -0700361 if options.delete and os.path.exists(options.chroot):
362 lock.write_lock()
363 DeleteChroot(options.chroot)
Brian Harringb938c782012-02-29 15:14:38 -0800364
David James56e6c2c2012-10-24 23:54:41 -0700365 sdk_cache = os.path.join(options.cache_dir, 'sdks')
366 distfiles_cache = os.path.join(options.cache_dir, 'distfiles')
367 osutils.SafeMakedirs(options.cache_dir)
Brian Harringae0a5322012-09-15 01:46:51 -0700368
David James56e6c2c2012-10-24 23:54:41 -0700369 for target in (sdk_cache, distfiles_cache):
370 src = os.path.join(SRC_ROOT, os.path.basename(target))
371 if not os.path.exists(src):
372 osutils.SafeMakedirs(target)
373 continue
374 lock.write_lock(
375 "Upgrade to %r needed but chroot is locked; please exit "
376 "all instances so this upgrade can finish." % src)
377 if not os.path.exists(src):
378 # Note that while waiting for the write lock, src may've vanished;
379 # it's a rare race during the upgrade process that's a byproduct
380 # of us avoiding taking a write lock to do the src check. If we
381 # took a write lock for that check, it would effectively limit
382 # all cros_sdk for a chroot to a single instance.
383 osutils.SafeMakedirs(target)
384 elif not os.path.exists(target):
385 # Upgrade occurred, but a reversion, or something whacky
386 # occurred writing to the old location. Wipe and continue.
387 os.rename(src, target)
388 else:
389 # Upgrade occurred once already, but either a reversion or
390 # some before/after separate cros_sdk usage is at play.
391 # Wipe and continue.
392 osutils.RmDir(src)
Brian Harringae0a5322012-09-15 01:46:51 -0700393
David James56e6c2c2012-10-24 23:54:41 -0700394 if options.download:
395 lock.write_lock()
396 sdk_tarball = FetchRemoteTarballs(sdk_cache, urls)
Brian Harring218e13c2012-10-10 16:21:26 -0700397
David James56e6c2c2012-10-24 23:54:41 -0700398 if options.create:
399 lock.write_lock()
400 CreateChroot(options.chroot, sdk_tarball, options.cache_dir,
401 nousepkg=(options.bootstrap or options.nousepkg))
Brian Harring1790ac42012-09-23 08:53:33 -0700402
David James56e6c2c2012-10-24 23:54:41 -0700403 if options.enter:
404 lock.read_lock()
405 EnterChroot(options.chroot, options.cache_dir, options.chrome_root,
406 options.chrome_root_mount, chroot_command)