blob: 16ff90dabb30f2588683ece58256bad1c9a6b648 [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)
214 try:
215 cros_build_lib.RunCommand(cmd, print_cmd=False)
216 except cros_build_lib.RunCommandError:
Brian Harring98b54902012-03-23 04:05:42 -0700217 raise SystemExit('Running %r failed!' % cmd)
Brian Harringb938c782012-02-29 15:14:38 -0800218
219
Brian Harring6be2efc2012-03-01 05:04:00 -0800220def main(argv):
Brian Harringb938c782012-02-29 15:14:38 -0800221 # TODO(ferringb): make argv required once depot_tools is fixed.
Brian Harringb938c782012-02-29 15:14:38 -0800222 usage="""usage: %prog [options] [VAR1=val1 .. VARn=valn -- <args>]
223
224This script manages a local CrOS SDK chroot. Depending on the flags,
225it can download, build or enter a chroot.
226
227Action taken is the following:
228--enter (default) .. Installs and enters a chroot
229--download .. Just download a chroot (enter if combined with --enter)
230--bootstrap .. Builds a chroot from source (enter if --enter)
231--delete .. Removes a chroot
232"""
233 sdk_latest_version = GetLatestVersion()
234 parser = optparse.OptionParser(usage)
235 # Actions:
236 parser.add_option('', '--bootstrap',
237 action='store_true', dest='bootstrap', default=False,
238 help=('Build a new SDK chroot from source'))
239 parser.add_option('', '--delete',
240 action='store_true', dest='delete', default=False,
241 help=('Delete the current SDK chroot'))
242 parser.add_option('', '--download',
243 action='store_true', dest='download', default=False,
244 help=('Download and install a prebuilt SDK'))
245 parser.add_option('', '--enter',
246 action='store_true', dest='enter', default=False,
247 help=('Enter the SDK chroot, possibly (re)create first'))
248
249 # Global options:
250 parser.add_option('', '--chroot',
251 dest='chroot', default=constants.DEFAULT_CHROOT_DIR,
252 help=('SDK chroot dir name [%s]' %
253 constants.DEFAULT_CHROOT_DIR))
254
255 # Additional options:
256 parser.add_option('', '--chrome_root',
257 dest='chrome_root', default='',
258 help=('Mount this chrome root into the SDK chroot'))
259 parser.add_option('', '--chrome_root_mount',
260 dest='chrome_root_mount', default='',
261 help=('Mount chrome into this path inside SDK chroot'))
262 parser.add_option('-r', '--replace',
263 action='store_true', dest='replace', default=False,
264 help=('Replace an existing SDK chroot'))
265 parser.add_option('-u', '--url',
266 dest='sdk_url', default='',
267 help=('''Use sdk tarball located at this url.
268 Use file:// for local files.'''))
269 parser.add_option('-v', '--version',
270 dest='sdk_version', default='',
271 help=('Use this sdk version [%s]' % sdk_latest_version))
272 (options, remaining_arguments) = parser.parse_args(argv)
273
274 # Some sanity checks first, before we ask for sudo credentials.
275 if cros_build_lib.IsInsideChroot():
Brian Harring98b54902012-03-23 04:05:42 -0700276 parser.error("This needs to be ran outside the chroot")
Brian Harringb938c782012-02-29 15:14:38 -0800277
Brian Harring98b54902012-03-23 04:05:42 -0700278 missing = CheckPrerequisites(NEEDED_TOOLS)
279 if missing:
280 parser.error((
281 'The tool(s) %s were not found.'
282 'Please install the appropriate package in your host.'
283 'Example(ubuntu):'
284 ' sudo apt-get install <packagename>'
285 % (', '.join(missing))))
Brian Harringb938c782012-02-29 15:14:38 -0800286
287 # Default action is --enter, if no other is selected.
288 if not (options.bootstrap or options.download or options.delete):
289 options.enter = True
290
291 # Only --enter can process additional args as passthrough commands.
292 # Warn and exit for least surprise.
293 if len(remaining_arguments) > 0 and not options.enter:
Brian Harring98b54902012-03-23 04:05:42 -0700294 parser.error("Additional arguments are not permitted, unless running "
295 "with --enter")
Brian Harringb938c782012-02-29 15:14:38 -0800296
297 # Some actions can be combined, as they merely modify how is the chroot
298 # going to be made. The only option that hates all others is --delete.
299 if options.delete and \
300 (options.enter or options.download or options.bootstrap):
Brian Harring98b54902012-03-23 04:05:42 -0700301 parser.error("--delete cannot be combined with --enter, "
302 "--download or --bootstrap")
Brian Harringb938c782012-02-29 15:14:38 -0800303 # NOTE: --delete is a true hater, it doesn't like other options either, but
304 # those will hardly lead to confusion. Nobody can expect to pass --version to
305 # delete and actually change something.
306
307 if options.bootstrap and options.download:
Brian Harring98b54902012-03-23 04:05:42 -0700308 parser.error("Either --bootstrap or --download, not both")
Brian Harringb938c782012-02-29 15:14:38 -0800309
310 # Bootstrap will start off from a non-selectable stage3 tarball. Attempts to
311 # select sdk by version are confusing. Warn and exit. We can still specify a
312 # tarball by path or URL though.
313 if options.bootstrap and options.sdk_version:
Brian Harring98b54902012-03-23 04:05:42 -0700314 parser.error("Cannot use --version when bootstrapping")
Brian Harringb938c782012-02-29 15:14:38 -0800315
316 chroot_path = os.path.join(SRC_ROOT, options.chroot)
317 chroot_path = os.path.abspath(chroot_path)
318 chroot_path = os.path.normpath(chroot_path)
319
320 if not options.sdk_version:
321 sdk_version = sdk_latest_version
322 else:
323 sdk_version = options.sdk_version
324
325 if options.delete and not os.path.exists(chroot_path):
326 print "Not doing anything. The chroot you want to remove doesn't exist."
Brian Harring98b54902012-03-23 04:05:42 -0700327 return 0
Brian Harringb938c782012-02-29 15:14:38 -0800328
329 lock_path = os.path.dirname(chroot_path)
330 lock_path = os.path.join(lock_path,
331 '.%s_lock' % os.path.basename(chroot_path))
332 with sudo.SudoKeepAlive():
Brian Harring4e6412d2012-03-09 20:54:02 -0800333 with cgroups.SimpleContainChildren('cros_sdk'):
Brian Harringcfe762a2012-02-29 13:03:53 -0800334 _CreateLockFile(lock_path)
335 with locking.FileLock(lock_path, 'chroot lock') as lock:
336 if options.delete:
337 lock.write_lock()
338 DeleteChroot(chroot_path)
Brian Harring98b54902012-03-23 04:05:42 -0700339 return 0
Brian Harringb938c782012-02-29 15:14:38 -0800340
Brian Harringcfe762a2012-02-29 13:03:53 -0800341 # Print a suggestion for replacement, but not if running just --enter.
342 if os.path.exists(chroot_path) and not options.replace and \
343 (options.bootstrap or options.download):
344 print "Chroot already exists. Run with --replace to re-create."
Brian Harringb938c782012-02-29 15:14:38 -0800345
Brian Harringcfe762a2012-02-29 13:03:53 -0800346 # Chroot doesn't exist or asked to replace.
347 if not os.path.exists(chroot_path) or options.replace:
348 lock.write_lock()
349 if options.bootstrap:
350 BootstrapChroot(chroot_path, options.sdk_url,
351 options.replace)
352 else:
353 CreateChroot(options.sdk_url, sdk_version,
354 chroot_path, options.replace)
355 if options.enter:
356 lock.read_lock()
357 EnterChroot(chroot_path, options.chrome_root,
358 options.chrome_root_mount, remaining_arguments)