blob: 2cd3b32d20e827420d1ed6382a7509c32d775fde [file] [log] [blame]
Brian Harringb938c782012-02-29 15:14:38 -08001#!/usr/bin/env python
2# Copyright (c) 2011-2012 The Chromium OS Authors. All rights reserved.
3# 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
9import optparse
10import os
11import sys
12import urlparse
13
14from chromite.buildbot import constants
Brian Harringcfe762a2012-02-29 13:03:53 -080015from chromite.lib import cgroups
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 Harringcfe762a2012-02-29 13:03:53 -080018from chromite.lib import sudo
Brian Harringb938c782012-02-29 15:14:38 -080019
20cros_build_lib.STRICT_SUDO = True
21
22
23DEFAULT_URL = 'https://commondatastorage.googleapis.com/chromiumos-sdk/'
Zdenek Behan2cc93c92012-04-13 04:36:40 +020024SDK_SUFFIXES = ['.tbz2', '.tar.xz']
25
Brian Harringb938c782012-02-29 15:14:38 -080026SRC_ROOT = os.path.realpath(constants.SOURCE_ROOT)
27SDK_DIR = os.path.join(SRC_ROOT, 'sdks')
28OVERLAY_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.
37NEEDED_TOOLS = ['curl']
38
39def GetHostArch():
40 """Returns a string for the host architecture"""
41 out = cros_build_lib.RunCommand(['uname', '-m'],
42 redirect_stdout=True, print_cmd=False).output
43 return out.rstrip('\n')
44
45def CheckPrerequisites(needed_tools):
46 """Verifies that the required tools are present on the system.
47
48 This is especially important as this script is intended to run
49 outside the chroot.
50
51 Arguments:
52 needed_tools: an array of string specified binaries to look for.
53
54 Returns:
55 True if all needed tools were found.
56 """
Brian Harring98b54902012-03-23 04:05:42 -070057 missing = []
Brian Harringb938c782012-02-29 15:14:38 -080058 for tool in needed_tools:
59 cmd = ['which', tool]
60 try:
61 cros_build_lib.RunCommand(cmd, print_cmd=False, redirect_stdout=True,
62 combine_stdout_stderr=True)
63 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -070064 missing.append(tool)
65 return missing
66
Brian Harringb938c782012-02-29 15:14:38 -080067
68def GetLatestVersion():
69 """Extracts latest version from chromiumos-overlay."""
70 sdk_file = open(SDK_VERSION_FILE)
71 buf = sdk_file.readline().rstrip('\n').split('=')
72 if buf[0] != 'SDK_LATEST_VERSION':
73 raise Exception('Malformed version file')
74 return buf[1].strip('"')
75
76
Zdenek Behan2cc93c92012-04-13 04:36:40 +020077def GetArchStageTarballs(tarballArch, version):
Brian Harringb938c782012-02-29 15:14:38 -080078 """Returns the URL for a given arch/version"""
79 D = { 'x86_64': 'cros-sdk-' }
80 try:
Zdenek Behan2cc93c92012-04-13 04:36:40 +020081 return [DEFAULT_URL + D[tarballArch] + version + x for x in SDK_SUFFIXES]
Brian Harringb938c782012-02-29 15:14:38 -080082 except KeyError:
Brian Harring98b54902012-03-23 04:05:42 -070083 raise SystemExit('Unsupported arch: %s' % (tarballArch,))
Brian Harringb938c782012-02-29 15:14:38 -080084
85
Zdenek Behan2cc93c92012-04-13 04:36:40 +020086def FetchRemoteTarballs(urls):
87 """Fetches a tarball given by url, and place it in sdk/.
88
89 Args:
90 urls: List of URLs to try to download. Download will stop on first success.
91
92 Returns:
93 Full path to the downloaded file
94 """
Zdenek Behan9c644dd2012-04-05 06:24:02 +020095
96 def RunCurl(args, **kwargs):
97 """Runs curl and wraps around all necessary hacks."""
98 cmd = ['curl']
99 cmd.extend(args)
100
101 result = cros_build_lib.RunCommand(cmd, error_ok=True, **kwargs)
102 if result.returncode > 0:
103 # These are the return codes of failing certs as per 'man curl'.
104 if result.returncode in (51, 58, 60):
105 print 'Download failed with certificate error? Try "sudo c_rehash".'
106 else:
107 print 'Curl failed!'
108 sys.exit(1)
109
110 return result
111
Zdenek Behan2cc93c92012-04-13 04:36:40 +0200112 def RemoteTarballExists(url):
113 """Tests if a remote tarball exists."""
114 result = RunCurl(['-I', url],
115 redirect_stdout=True, redirect_stderr=True,
116 print_cmd=False)
117 header = result.output.splitlines()[0]
118 return header.find('200 OK') != -1
119
120 url = None
121 for url in urls:
122 print 'Attempting download: %s' % url
123 if RemoteTarballExists(url):
124 break
125 else:
126 raise Exception('No valid URLs found!')
127
Zdenek Behanb2fa72e2012-03-16 04:49:30 +0100128 tarball_name = os.path.basename(urlparse.urlparse(url).path)
129 tarball_dest = os.path.join(SDK_DIR, tarball_name)
130
131 # Cleanup old tarballs.
132 files_to_delete = [f for f in os.listdir(SDK_DIR) if f != tarball_name]
133 if files_to_delete:
134 print 'Cleaning up old tarballs: ' + str(files_to_delete)
135 for f in files_to_delete:
136 f_path = os.path.join(SDK_DIR, f)
137 # Only delete regular files that belong to us.
138 if os.path.isfile(f_path) and os.stat(f_path).st_uid == os.getuid():
139 os.remove(f_path)
Brian Harringb938c782012-02-29 15:14:38 -0800140
Zdenek Behan9c644dd2012-04-05 06:24:02 +0200141 curl_opts = ['-f', '--retry', '5', '-L', '-y', '30',
142 '--output', tarball_dest]
Brian Harringb938c782012-02-29 15:14:38 -0800143 if not url.startswith('file://') and os.path.exists(tarball_dest):
144 # Only resume for remote URLs. If the file is local, there's no
145 # real speedup, and using the same filename for different files
146 # locally will cause issues.
Zdenek Behan9c644dd2012-04-05 06:24:02 +0200147 curl_opts.extend(['-C', '-'])
Brian Harringb938c782012-02-29 15:14:38 -0800148
149 # Additionally, certain versions of curl incorrectly fail if
150 # told to resume a file that is fully downloaded, thus do a
151 # check on our own.
152 # see:
153 # https://sourceforge.net/tracker/?func=detail&atid=100976&aid=3482927&group_id=976
Zdenek Behan9c644dd2012-04-05 06:24:02 +0200154 result = RunCurl(['-I', url],
155 redirect_stdout=True,
156 redirect_stderr=True,
157 print_cmd=False)
158
Brian Harringb938c782012-02-29 15:14:38 -0800159 for x in result.output.splitlines():
160 if x.lower().startswith("content-length:"):
161 length = int(x.split(":", 1)[-1].strip())
162 if length == os.path.getsize(tarball_dest):
163 # Fully fetched; bypass invoking curl, since it can screw up handling
164 # of this (>=7.21.4 and up).
165 return tarball_dest
166 break
Zdenek Behan9c644dd2012-04-05 06:24:02 +0200167 curl_opts.append(url)
168 RunCurl(curl_opts)
Brian Harringb938c782012-02-29 15:14:38 -0800169 return tarball_dest
170
171
172def BootstrapChroot(chroot_path, stage_url, replace):
173 """Builds a new chroot from source"""
174 cmd = MAKE_CHROOT + ['--chroot', chroot_path,
175 '--nousepkg']
176
177 stage = None
178 if stage_url:
Zdenek Behan2cc93c92012-04-13 04:36:40 +0200179 stage = FetchRemoteTarballs([stage_url])
Brian Harringb938c782012-02-29 15:14:38 -0800180
181 if stage:
182 cmd.extend(['--stage3_path', stage])
183
184 if replace:
185 cmd.append('--replace')
186
187 try:
188 cros_build_lib.RunCommand(cmd, print_cmd=False)
189 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700190 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800191
192
193def CreateChroot(sdk_url, sdk_version, chroot_path, replace):
194 """Creates a new chroot from a given SDK"""
195 if not os.path.exists(SDK_DIR):
196 cros_build_lib.RunCommand(['mkdir', '-p', SDK_DIR], print_cmd=False)
197
198 # Based on selections, fetch the tarball
199 if sdk_url:
Zdenek Behan2cc93c92012-04-13 04:36:40 +0200200 urls = [sdk_url]
Brian Harringb938c782012-02-29 15:14:38 -0800201 else:
202 arch = GetHostArch()
Zdenek Behan2cc93c92012-04-13 04:36:40 +0200203 urls = GetArchStageTarballs(arch, sdk_version)
Brian Harringb938c782012-02-29 15:14:38 -0800204
Zdenek Behan2cc93c92012-04-13 04:36:40 +0200205 sdk = FetchRemoteTarballs(urls)
Brian Harringb938c782012-02-29 15:14:38 -0800206
207 # TODO(zbehan): Unpack and install
208 # For now, we simply call make_chroot on the prebuilt chromeos-sdk.
209 # make_chroot provides a variety of hacks to make the chroot useable.
210 # These should all be eliminated/minimised, after which, we can change
211 # this to just unpacking the sdk.
212 cmd = MAKE_CHROOT + ['--stage3_path', sdk,
213 '--chroot', chroot_path]
214
215 if replace:
216 cmd.append('--replace')
217
218 try:
219 cros_build_lib.RunCommand(cmd, print_cmd=False)
220 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700221 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800222
223
224def DeleteChroot(chroot_path):
225 """Deletes an existing chroot"""
226 cmd = MAKE_CHROOT + ['--chroot', chroot_path,
227 '--delete']
228 try:
229 cros_build_lib.RunCommand(cmd, print_cmd=False)
230 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700231 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800232
233
234def _CreateLockFile(path):
Zdenek Behan2cc93c92012-04-13 04:36:40 +0200235 """Create a lockfile via sudo that is writable by current user."""
236 cros_build_lib.SudoRunCommand(['touch', path], print_cmd=False)
237 cros_build_lib.SudoRunCommand(['chown', str(os.getuid()), path],
238 print_cmd=False)
239 cros_build_lib.SudoRunCommand(['chmod', '644', path], print_cmd=False)
Brian Harringb938c782012-02-29 15:14:38 -0800240
241
242def EnterChroot(chroot_path, chrome_root, chrome_root_mount, additional_args):
243 """Enters an existing SDK chroot"""
244 cmd = ENTER_CHROOT + ['--chroot', chroot_path]
245 if chrome_root:
246 cmd.extend(['--chrome_root', chrome_root])
247 if chrome_root_mount:
248 cmd.extend(['--chrome_root_mount', chrome_root_mount])
249 if len(additional_args) > 0:
250 cmd.append('--')
251 cmd.extend(additional_args)
Brian Harring7199e7d2012-03-23 04:10:08 -0700252
253 ret = cros_build_lib.RunCommand(cmd, print_cmd=False, error_code_ok=True)
254 # If we were in interactive mode, ignore the exit code; it'll be whatever
255 # they last ran w/in the chroot and won't matter to us one way or another.
256 # Note this does allow chroot entrance to fail and be ignored during
257 # interactive; this is however a rare case and the user will immediately
258 # see it (nor will they be checking the exit code manually).
259 if ret.returncode != 0 and additional_args:
260 raise SystemExit('Running %r failed with exit code %i'
261 % (cmd, ret.returncode))
Brian Harringb938c782012-02-29 15:14:38 -0800262
263
Brian Harring6be2efc2012-03-01 05:04:00 -0800264def main(argv):
Brian Harringb938c782012-02-29 15:14:38 -0800265 # TODO(ferringb): make argv required once depot_tools is fixed.
Zdenek Behan2cc93c92012-04-13 04:36:40 +0200266 usage = """usage: %prog [options] [VAR1=val1 .. VARn=valn -- <args>]
Brian Harringb938c782012-02-29 15:14:38 -0800267
268This script manages a local CrOS SDK chroot. Depending on the flags,
269it can download, build or enter a chroot.
270
271Action taken is the following:
272--enter (default) .. Installs and enters a chroot
273--download .. Just download a chroot (enter if combined with --enter)
274--bootstrap .. Builds a chroot from source (enter if --enter)
275--delete .. Removes a chroot
276"""
277 sdk_latest_version = GetLatestVersion()
278 parser = optparse.OptionParser(usage)
279 # Actions:
280 parser.add_option('', '--bootstrap',
281 action='store_true', dest='bootstrap', default=False,
282 help=('Build a new SDK chroot from source'))
283 parser.add_option('', '--delete',
284 action='store_true', dest='delete', default=False,
285 help=('Delete the current SDK chroot'))
286 parser.add_option('', '--download',
287 action='store_true', dest='download', default=False,
288 help=('Download and install a prebuilt SDK'))
289 parser.add_option('', '--enter',
290 action='store_true', dest='enter', default=False,
291 help=('Enter the SDK chroot, possibly (re)create first'))
292
293 # Global options:
294 parser.add_option('', '--chroot',
295 dest='chroot', default=constants.DEFAULT_CHROOT_DIR,
296 help=('SDK chroot dir name [%s]' %
297 constants.DEFAULT_CHROOT_DIR))
298
299 # Additional options:
300 parser.add_option('', '--chrome_root',
301 dest='chrome_root', default='',
302 help=('Mount this chrome root into the SDK chroot'))
303 parser.add_option('', '--chrome_root_mount',
304 dest='chrome_root_mount', default='',
305 help=('Mount chrome into this path inside SDK chroot'))
306 parser.add_option('-r', '--replace',
307 action='store_true', dest='replace', default=False,
308 help=('Replace an existing SDK chroot'))
309 parser.add_option('-u', '--url',
310 dest='sdk_url', default='',
311 help=('''Use sdk tarball located at this url.
312 Use file:// for local files.'''))
313 parser.add_option('-v', '--version',
314 dest='sdk_version', default='',
315 help=('Use this sdk version [%s]' % sdk_latest_version))
316 (options, remaining_arguments) = parser.parse_args(argv)
317
318 # Some sanity checks first, before we ask for sudo credentials.
319 if cros_build_lib.IsInsideChroot():
Brian Harring98b54902012-03-23 04:05:42 -0700320 parser.error("This needs to be ran outside the chroot")
Brian Harringb938c782012-02-29 15:14:38 -0800321
Brian Harring98b54902012-03-23 04:05:42 -0700322 missing = CheckPrerequisites(NEEDED_TOOLS)
323 if missing:
324 parser.error((
325 'The tool(s) %s were not found.'
326 'Please install the appropriate package in your host.'
327 'Example(ubuntu):'
328 ' sudo apt-get install <packagename>'
329 % (', '.join(missing))))
Brian Harringb938c782012-02-29 15:14:38 -0800330
331 # Default action is --enter, if no other is selected.
332 if not (options.bootstrap or options.download or options.delete):
333 options.enter = True
334
335 # Only --enter can process additional args as passthrough commands.
336 # Warn and exit for least surprise.
337 if len(remaining_arguments) > 0 and not options.enter:
Brian Harring98b54902012-03-23 04:05:42 -0700338 parser.error("Additional arguments are not permitted, unless running "
339 "with --enter")
Brian Harringb938c782012-02-29 15:14:38 -0800340
341 # Some actions can be combined, as they merely modify how is the chroot
342 # going to be made. The only option that hates all others is --delete.
343 if options.delete and \
344 (options.enter or options.download or options.bootstrap):
Brian Harring98b54902012-03-23 04:05:42 -0700345 parser.error("--delete cannot be combined with --enter, "
346 "--download or --bootstrap")
Brian Harringb938c782012-02-29 15:14:38 -0800347 # NOTE: --delete is a true hater, it doesn't like other options either, but
348 # those will hardly lead to confusion. Nobody can expect to pass --version to
349 # delete and actually change something.
350
351 if options.bootstrap and options.download:
Brian Harring98b54902012-03-23 04:05:42 -0700352 parser.error("Either --bootstrap or --download, not both")
Brian Harringb938c782012-02-29 15:14:38 -0800353
354 # Bootstrap will start off from a non-selectable stage3 tarball. Attempts to
355 # select sdk by version are confusing. Warn and exit. We can still specify a
356 # tarball by path or URL though.
357 if options.bootstrap and options.sdk_version:
Brian Harring98b54902012-03-23 04:05:42 -0700358 parser.error("Cannot use --version when bootstrapping")
Brian Harringb938c782012-02-29 15:14:38 -0800359
360 chroot_path = os.path.join(SRC_ROOT, options.chroot)
361 chroot_path = os.path.abspath(chroot_path)
362 chroot_path = os.path.normpath(chroot_path)
363
364 if not options.sdk_version:
365 sdk_version = sdk_latest_version
366 else:
367 sdk_version = options.sdk_version
368
369 if options.delete and not os.path.exists(chroot_path):
370 print "Not doing anything. The chroot you want to remove doesn't exist."
Brian Harring98b54902012-03-23 04:05:42 -0700371 return 0
Brian Harringb938c782012-02-29 15:14:38 -0800372
373 lock_path = os.path.dirname(chroot_path)
374 lock_path = os.path.join(lock_path,
375 '.%s_lock' % os.path.basename(chroot_path))
376 with sudo.SudoKeepAlive():
Brian Harring4e6412d2012-03-09 20:54:02 -0800377 with cgroups.SimpleContainChildren('cros_sdk'):
Brian Harringcfe762a2012-02-29 13:03:53 -0800378 _CreateLockFile(lock_path)
379 with locking.FileLock(lock_path, 'chroot lock') as lock:
380 if options.delete:
381 lock.write_lock()
382 DeleteChroot(chroot_path)
Brian Harring98b54902012-03-23 04:05:42 -0700383 return 0
Brian Harringb938c782012-02-29 15:14:38 -0800384
Brian Harringcfe762a2012-02-29 13:03:53 -0800385 # Print a suggestion for replacement, but not if running just --enter.
386 if os.path.exists(chroot_path) and not options.replace and \
387 (options.bootstrap or options.download):
388 print "Chroot already exists. Run with --replace to re-create."
Brian Harringb938c782012-02-29 15:14:38 -0800389
Brian Harringcfe762a2012-02-29 13:03:53 -0800390 # Chroot doesn't exist or asked to replace.
391 if not os.path.exists(chroot_path) or options.replace:
392 lock.write_lock()
393 if options.bootstrap:
394 BootstrapChroot(chroot_path, options.sdk_url,
395 options.replace)
396 else:
397 CreateChroot(options.sdk_url, sdk_version,
398 chroot_path, options.replace)
399 if options.enter:
400 lock.read_lock()
401 EnterChroot(chroot_path, options.chrome_root,
402 options.chrome_root_mount, remaining_arguments)