blob: 29ae3209e7946f56c6f06f77f59b48e775c9bd34 [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/'
24SRC_ROOT = os.path.realpath(constants.SOURCE_ROOT)
25SDK_DIR = os.path.join(SRC_ROOT, 'sdks')
26OVERLAY_DIR = os.path.join(SRC_ROOT, 'src/third_party/chromiumos-overlay')
27SDK_VERSION_FILE = os.path.join(OVERLAY_DIR,
28 'chromeos/binhost/host/sdk_version.conf')
29
30# TODO(zbehan): Remove the dependency on these, reimplement them in python
31MAKE_CHROOT = [os.path.join(SRC_ROOT, 'src/scripts/sdk_lib/make_chroot.sh')]
32ENTER_CHROOT = [os.path.join(SRC_ROOT, 'src/scripts/sdk_lib/enter_chroot.sh')]
33
34# We need these tools to run. Very common tools (tar,..) are ommited.
35NEEDED_TOOLS = ['curl']
36
37def GetHostArch():
38 """Returns a string for the host architecture"""
39 out = cros_build_lib.RunCommand(['uname', '-m'],
40 redirect_stdout=True, print_cmd=False).output
41 return out.rstrip('\n')
42
43def CheckPrerequisites(needed_tools):
44 """Verifies that the required tools are present on the system.
45
46 This is especially important as this script is intended to run
47 outside the chroot.
48
49 Arguments:
50 needed_tools: an array of string specified binaries to look for.
51
52 Returns:
53 True if all needed tools were found.
54 """
Brian Harring98b54902012-03-23 04:05:42 -070055 missing = []
Brian Harringb938c782012-02-29 15:14:38 -080056 for tool in needed_tools:
57 cmd = ['which', tool]
58 try:
59 cros_build_lib.RunCommand(cmd, print_cmd=False, redirect_stdout=True,
60 combine_stdout_stderr=True)
61 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -070062 missing.append(tool)
63 return missing
64
Brian Harringb938c782012-02-29 15:14:38 -080065
66def GetLatestVersion():
67 """Extracts latest version from chromiumos-overlay."""
68 sdk_file = open(SDK_VERSION_FILE)
69 buf = sdk_file.readline().rstrip('\n').split('=')
70 if buf[0] != 'SDK_LATEST_VERSION':
71 raise Exception('Malformed version file')
72 return buf[1].strip('"')
73
74
75def GetArchStageTarball(tarballArch, version):
76 """Returns the URL for a given arch/version"""
77 D = { 'x86_64': 'cros-sdk-' }
78 try:
79 return DEFAULT_URL + D[tarballArch] + version + '.tbz2'
80 except KeyError:
Brian Harring98b54902012-03-23 04:05:42 -070081 raise SystemExit('Unsupported arch: %s' % (tarballArch,))
Brian Harringb938c782012-02-29 15:14:38 -080082
83
84def FetchRemoteTarball(url):
85 """Fetches a tarball given by url, and place it in sdk/."""
Zdenek Behanb2fa72e2012-03-16 04:49:30 +010086 tarball_name = os.path.basename(urlparse.urlparse(url).path)
87 tarball_dest = os.path.join(SDK_DIR, tarball_name)
88
89 # Cleanup old tarballs.
90 files_to_delete = [f for f in os.listdir(SDK_DIR) if f != tarball_name]
91 if files_to_delete:
92 print 'Cleaning up old tarballs: ' + str(files_to_delete)
93 for f in files_to_delete:
94 f_path = os.path.join(SDK_DIR, f)
95 # Only delete regular files that belong to us.
96 if os.path.isfile(f_path) and os.stat(f_path).st_uid == os.getuid():
97 os.remove(f_path)
Brian Harringb938c782012-02-29 15:14:38 -080098
99 print 'Downloading sdk: "%s"' % url
100 cmd = ['curl', '-f', '--retry', '5', '-L', '-y', '30',
101 '--output', tarball_dest]
102
103 if not url.startswith('file://') and os.path.exists(tarball_dest):
104 # Only resume for remote URLs. If the file is local, there's no
105 # real speedup, and using the same filename for different files
106 # locally will cause issues.
107 cmd.extend(['-C', '-'])
108
109 # Additionally, certain versions of curl incorrectly fail if
110 # told to resume a file that is fully downloaded, thus do a
111 # check on our own.
112 # see:
113 # https://sourceforge.net/tracker/?func=detail&atid=100976&aid=3482927&group_id=976
114 result = cros_build_lib.RunCommand(['curl', '-I', url],
115 redirect_stdout=True, print_cmd=False)
116 for x in result.output.splitlines():
117 if x.lower().startswith("content-length:"):
118 length = int(x.split(":", 1)[-1].strip())
119 if length == os.path.getsize(tarball_dest):
120 # Fully fetched; bypass invoking curl, since it can screw up handling
121 # of this (>=7.21.4 and up).
122 return tarball_dest
123 break
124
125 cmd.append(url)
126
127 cros_build_lib.RunCommand(cmd)
128 return tarball_dest
129
130
131def BootstrapChroot(chroot_path, stage_url, replace):
132 """Builds a new chroot from source"""
133 cmd = MAKE_CHROOT + ['--chroot', chroot_path,
134 '--nousepkg']
135
136 stage = None
137 if stage_url:
138 stage = FetchRemoteTarball(stage_url)
139
140 if stage:
141 cmd.extend(['--stage3_path', stage])
142
143 if replace:
144 cmd.append('--replace')
145
146 try:
147 cros_build_lib.RunCommand(cmd, print_cmd=False)
148 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700149 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800150
151
152def CreateChroot(sdk_url, sdk_version, chroot_path, replace):
153 """Creates a new chroot from a given SDK"""
154 if not os.path.exists(SDK_DIR):
155 cros_build_lib.RunCommand(['mkdir', '-p', SDK_DIR], print_cmd=False)
156
157 # Based on selections, fetch the tarball
158 if sdk_url:
159 url = sdk_url
160 else:
161 arch = GetHostArch()
162 if sdk_version:
163 url = GetArchStageTarball(arch, sdk_version)
164 else:
165 url = GetArchStageTarball(arch)
166
167 sdk = FetchRemoteTarball(url)
168
169 # TODO(zbehan): Unpack and install
170 # For now, we simply call make_chroot on the prebuilt chromeos-sdk.
171 # make_chroot provides a variety of hacks to make the chroot useable.
172 # These should all be eliminated/minimised, after which, we can change
173 # this to just unpacking the sdk.
174 cmd = MAKE_CHROOT + ['--stage3_path', sdk,
175 '--chroot', chroot_path]
176
177 if replace:
178 cmd.append('--replace')
179
180 try:
181 cros_build_lib.RunCommand(cmd, print_cmd=False)
182 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700183 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800184
185
186def DeleteChroot(chroot_path):
187 """Deletes an existing chroot"""
188 cmd = MAKE_CHROOT + ['--chroot', chroot_path,
189 '--delete']
190 try:
191 cros_build_lib.RunCommand(cmd, print_cmd=False)
192 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700193 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800194
195
196def _CreateLockFile(path):
197 """Create a lockfile via sudo that is writable by current user."""
198 cros_build_lib.SudoRunCommand(['touch', path], print_cmd=False)
199 cros_build_lib.SudoRunCommand(['chown', str(os.getuid()), path],
200 print_cmd=False)
201 cros_build_lib.SudoRunCommand(['chmod', '644', path], print_cmd=False)
202
203
204def EnterChroot(chroot_path, chrome_root, chrome_root_mount, additional_args):
205 """Enters an existing SDK chroot"""
206 cmd = ENTER_CHROOT + ['--chroot', chroot_path]
207 if chrome_root:
208 cmd.extend(['--chrome_root', chrome_root])
209 if chrome_root_mount:
210 cmd.extend(['--chrome_root_mount', chrome_root_mount])
211 if len(additional_args) > 0:
212 cmd.append('--')
213 cmd.extend(additional_args)
Brian Harring7199e7d2012-03-23 04:10:08 -0700214
215 ret = cros_build_lib.RunCommand(cmd, print_cmd=False, error_code_ok=True)
216 # If we were in interactive mode, ignore the exit code; it'll be whatever
217 # they last ran w/in the chroot and won't matter to us one way or another.
218 # Note this does allow chroot entrance to fail and be ignored during
219 # interactive; this is however a rare case and the user will immediately
220 # see it (nor will they be checking the exit code manually).
221 if ret.returncode != 0 and additional_args:
222 raise SystemExit('Running %r failed with exit code %i'
223 % (cmd, ret.returncode))
Brian Harringb938c782012-02-29 15:14:38 -0800224
225
Brian Harring6be2efc2012-03-01 05:04:00 -0800226def main(argv):
Brian Harringb938c782012-02-29 15:14:38 -0800227 # TODO(ferringb): make argv required once depot_tools is fixed.
Brian Harringb938c782012-02-29 15:14:38 -0800228 usage="""usage: %prog [options] [VAR1=val1 .. VARn=valn -- <args>]
229
230This script manages a local CrOS SDK chroot. Depending on the flags,
231it can download, build or enter a chroot.
232
233Action taken is the following:
234--enter (default) .. Installs and enters a chroot
235--download .. Just download a chroot (enter if combined with --enter)
236--bootstrap .. Builds a chroot from source (enter if --enter)
237--delete .. Removes a chroot
238"""
239 sdk_latest_version = GetLatestVersion()
240 parser = optparse.OptionParser(usage)
241 # Actions:
242 parser.add_option('', '--bootstrap',
243 action='store_true', dest='bootstrap', default=False,
244 help=('Build a new SDK chroot from source'))
245 parser.add_option('', '--delete',
246 action='store_true', dest='delete', default=False,
247 help=('Delete the current SDK chroot'))
248 parser.add_option('', '--download',
249 action='store_true', dest='download', default=False,
250 help=('Download and install a prebuilt SDK'))
251 parser.add_option('', '--enter',
252 action='store_true', dest='enter', default=False,
253 help=('Enter the SDK chroot, possibly (re)create first'))
254
255 # Global options:
256 parser.add_option('', '--chroot',
257 dest='chroot', default=constants.DEFAULT_CHROOT_DIR,
258 help=('SDK chroot dir name [%s]' %
259 constants.DEFAULT_CHROOT_DIR))
260
261 # Additional options:
262 parser.add_option('', '--chrome_root',
263 dest='chrome_root', default='',
264 help=('Mount this chrome root into the SDK chroot'))
265 parser.add_option('', '--chrome_root_mount',
266 dest='chrome_root_mount', default='',
267 help=('Mount chrome into this path inside SDK chroot'))
268 parser.add_option('-r', '--replace',
269 action='store_true', dest='replace', default=False,
270 help=('Replace an existing SDK chroot'))
271 parser.add_option('-u', '--url',
272 dest='sdk_url', default='',
273 help=('''Use sdk tarball located at this url.
274 Use file:// for local files.'''))
275 parser.add_option('-v', '--version',
276 dest='sdk_version', default='',
277 help=('Use this sdk version [%s]' % sdk_latest_version))
278 (options, remaining_arguments) = parser.parse_args(argv)
279
280 # Some sanity checks first, before we ask for sudo credentials.
281 if cros_build_lib.IsInsideChroot():
Brian Harring98b54902012-03-23 04:05:42 -0700282 parser.error("This needs to be ran outside the chroot")
Brian Harringb938c782012-02-29 15:14:38 -0800283
Brian Harring98b54902012-03-23 04:05:42 -0700284 missing = CheckPrerequisites(NEEDED_TOOLS)
285 if missing:
286 parser.error((
287 'The tool(s) %s were not found.'
288 'Please install the appropriate package in your host.'
289 'Example(ubuntu):'
290 ' sudo apt-get install <packagename>'
291 % (', '.join(missing))))
Brian Harringb938c782012-02-29 15:14:38 -0800292
293 # Default action is --enter, if no other is selected.
294 if not (options.bootstrap or options.download or options.delete):
295 options.enter = True
296
297 # Only --enter can process additional args as passthrough commands.
298 # Warn and exit for least surprise.
299 if len(remaining_arguments) > 0 and not options.enter:
Brian Harring98b54902012-03-23 04:05:42 -0700300 parser.error("Additional arguments are not permitted, unless running "
301 "with --enter")
Brian Harringb938c782012-02-29 15:14:38 -0800302
303 # Some actions can be combined, as they merely modify how is the chroot
304 # going to be made. The only option that hates all others is --delete.
305 if options.delete and \
306 (options.enter or options.download or options.bootstrap):
Brian Harring98b54902012-03-23 04:05:42 -0700307 parser.error("--delete cannot be combined with --enter, "
308 "--download or --bootstrap")
Brian Harringb938c782012-02-29 15:14:38 -0800309 # NOTE: --delete is a true hater, it doesn't like other options either, but
310 # those will hardly lead to confusion. Nobody can expect to pass --version to
311 # delete and actually change something.
312
313 if options.bootstrap and options.download:
Brian Harring98b54902012-03-23 04:05:42 -0700314 parser.error("Either --bootstrap or --download, not both")
Brian Harringb938c782012-02-29 15:14:38 -0800315
316 # Bootstrap will start off from a non-selectable stage3 tarball. Attempts to
317 # select sdk by version are confusing. Warn and exit. We can still specify a
318 # tarball by path or URL though.
319 if options.bootstrap and options.sdk_version:
Brian Harring98b54902012-03-23 04:05:42 -0700320 parser.error("Cannot use --version when bootstrapping")
Brian Harringb938c782012-02-29 15:14:38 -0800321
322 chroot_path = os.path.join(SRC_ROOT, options.chroot)
323 chroot_path = os.path.abspath(chroot_path)
324 chroot_path = os.path.normpath(chroot_path)
325
326 if not options.sdk_version:
327 sdk_version = sdk_latest_version
328 else:
329 sdk_version = options.sdk_version
330
331 if options.delete and not os.path.exists(chroot_path):
332 print "Not doing anything. The chroot you want to remove doesn't exist."
Brian Harring98b54902012-03-23 04:05:42 -0700333 return 0
Brian Harringb938c782012-02-29 15:14:38 -0800334
335 lock_path = os.path.dirname(chroot_path)
336 lock_path = os.path.join(lock_path,
337 '.%s_lock' % os.path.basename(chroot_path))
338 with sudo.SudoKeepAlive():
Brian Harring4e6412d2012-03-09 20:54:02 -0800339 with cgroups.SimpleContainChildren('cros_sdk'):
Brian Harringcfe762a2012-02-29 13:03:53 -0800340 _CreateLockFile(lock_path)
341 with locking.FileLock(lock_path, 'chroot lock') as lock:
342 if options.delete:
343 lock.write_lock()
344 DeleteChroot(chroot_path)
Brian Harring98b54902012-03-23 04:05:42 -0700345 return 0
Brian Harringb938c782012-02-29 15:14:38 -0800346
Brian Harringcfe762a2012-02-29 13:03:53 -0800347 # Print a suggestion for replacement, but not if running just --enter.
348 if os.path.exists(chroot_path) and not options.replace and \
349 (options.bootstrap or options.download):
350 print "Chroot already exists. Run with --replace to re-create."
Brian Harringb938c782012-02-29 15:14:38 -0800351
Brian Harringcfe762a2012-02-29 13:03:53 -0800352 # Chroot doesn't exist or asked to replace.
353 if not os.path.exists(chroot_path) or options.replace:
354 lock.write_lock()
355 if options.bootstrap:
356 BootstrapChroot(chroot_path, options.sdk_url,
357 options.replace)
358 else:
359 CreateChroot(options.sdk_url, sdk_version,
360 chroot_path, options.replace)
361 if options.enter:
362 lock.read_lock()
363 EnterChroot(chroot_path, options.chrome_root,
364 options.chrome_root_mount, remaining_arguments)