Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 1 | #!/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 | |
| 9 | import optparse |
| 10 | import os |
| 11 | import sys |
| 12 | import urlparse |
| 13 | |
| 14 | from chromite.buildbot import constants |
Brian Harring | cfe762a | 2012-02-29 13:03:53 -0800 | [diff] [blame] | 15 | from chromite.lib import cgroups |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 16 | from chromite.lib import cros_build_lib |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 17 | from chromite.lib import locking |
Brian Harring | cfe762a | 2012-02-29 13:03:53 -0800 | [diff] [blame] | 18 | from chromite.lib import sudo |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 19 | |
| 20 | cros_build_lib.STRICT_SUDO = True |
| 21 | |
| 22 | |
| 23 | DEFAULT_URL = 'https://commondatastorage.googleapis.com/chromiumos-sdk/' |
| 24 | SRC_ROOT = os.path.realpath(constants.SOURCE_ROOT) |
| 25 | SDK_DIR = os.path.join(SRC_ROOT, 'sdks') |
| 26 | OVERLAY_DIR = os.path.join(SRC_ROOT, 'src/third_party/chromiumos-overlay') |
| 27 | SDK_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 |
| 31 | MAKE_CHROOT = [os.path.join(SRC_ROOT, 'src/scripts/sdk_lib/make_chroot.sh')] |
| 32 | ENTER_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. |
| 35 | NEEDED_TOOLS = ['curl'] |
| 36 | |
| 37 | def 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 | |
| 43 | def 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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 55 | missing = [] |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 56 | 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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 62 | missing.append(tool) |
| 63 | return missing |
| 64 | |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 65 | |
| 66 | def 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 | |
| 75 | def 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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 81 | raise SystemExit('Unsupported arch: %s' % (tarballArch,)) |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 82 | |
| 83 | |
| 84 | def FetchRemoteTarball(url): |
| 85 | """Fetches a tarball given by url, and place it in sdk/.""" |
Zdenek Behan | b2fa72e | 2012-03-16 04:49:30 +0100 | [diff] [blame] | 86 | 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 Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 98 | |
| 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 | |
| 131 | def 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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 149 | raise SystemExit('Running %r failed!' % cmd) |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 150 | |
| 151 | |
| 152 | def 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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 183 | raise SystemExit('Running %r failed!' % cmd) |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 184 | |
| 185 | |
| 186 | def 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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 193 | raise SystemExit('Running %r failed!' % cmd) |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 194 | |
| 195 | |
| 196 | def _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 | |
| 204 | def 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 Harring | 7199e7d | 2012-03-23 04:10:08 -0700 | [diff] [blame] | 214 | |
| 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 Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 224 | |
| 225 | |
Brian Harring | 6be2efc | 2012-03-01 05:04:00 -0800 | [diff] [blame] | 226 | def main(argv): |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 227 | # TODO(ferringb): make argv required once depot_tools is fixed. |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 228 | usage="""usage: %prog [options] [VAR1=val1 .. VARn=valn -- <args>] |
| 229 | |
| 230 | This script manages a local CrOS SDK chroot. Depending on the flags, |
| 231 | it can download, build or enter a chroot. |
| 232 | |
| 233 | Action 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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 282 | parser.error("This needs to be ran outside the chroot") |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 283 | |
Brian Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 284 | 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 Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 292 | |
| 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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 300 | parser.error("Additional arguments are not permitted, unless running " |
| 301 | "with --enter") |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 302 | |
| 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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 307 | parser.error("--delete cannot be combined with --enter, " |
| 308 | "--download or --bootstrap") |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 309 | # 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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 314 | parser.error("Either --bootstrap or --download, not both") |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 315 | |
| 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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 320 | parser.error("Cannot use --version when bootstrapping") |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 321 | |
| 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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 333 | return 0 |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 334 | |
| 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 Harring | 4e6412d | 2012-03-09 20:54:02 -0800 | [diff] [blame] | 339 | with cgroups.SimpleContainChildren('cros_sdk'): |
Brian Harring | cfe762a | 2012-02-29 13:03:53 -0800 | [diff] [blame] | 340 | _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 Harring | 98b5490 | 2012-03-23 04:05:42 -0700 | [diff] [blame] | 345 | return 0 |
Brian Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 346 | |
Brian Harring | cfe762a | 2012-02-29 13:03:53 -0800 | [diff] [blame] | 347 | # 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 Harring | b938c78 | 2012-02-29 15:14:38 -0800 | [diff] [blame] | 351 | |
Brian Harring | cfe762a | 2012-02-29 13:03:53 -0800 | [diff] [blame] | 352 | # 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) |