Chris Sosa | 47a7d4e | 2012-03-28 18:26:55 | [diff] [blame] | 1 | # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
| 5 | """Helper class for interacting with the Dev Server.""" |
| 6 | |
beeps | bd33724 | 2013-07-10 05:44:06 | [diff] [blame] | 7 | import ast |
Gilad Arnold | 55a2a37 | 2012-10-02 16:46:32 | [diff] [blame] | 8 | import base64 |
| 9 | import binascii |
Chris Sosa | 4b95160 | 2014-04-10 03:26:07 | [diff] [blame] | 10 | import cherrypy |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 11 | import distutils.version |
| 12 | import errno |
Gilad Arnold | 55a2a37 | 2012-10-02 16:46:32 | [diff] [blame] | 13 | import hashlib |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 14 | import os |
| 15 | import shutil |
Alex Deymo | 3e2d495 | 2013-09-04 04:49:41 | [diff] [blame] | 16 | import tempfile |
Chris Sosa | 76e44b9 | 2013-01-31 20:11:38 | [diff] [blame] | 17 | import threading |
Simran Basi | 4baad08 | 2013-02-14 21:39:18 | [diff] [blame] | 18 | import subprocess |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 19 | |
Gilad Arnold | c65330c | 2012-09-20 22:17:48 | [diff] [blame] | 20 | import log_util |
| 21 | |
| 22 | |
| 23 | # Module-local log function. |
Chris Sosa | 6a3697f | 2013-01-30 00:44:43 | [diff] [blame] | 24 | def _Log(message, *args): |
| 25 | return log_util.LogWithTag('UTIL', message, *args) |
Gilad Arnold | c65330c | 2012-09-20 22:17:48 | [diff] [blame] | 26 | |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 27 | |
Gilad Arnold | 55a2a37 | 2012-10-02 16:46:32 | [diff] [blame] | 28 | _HASH_BLOCK_SIZE = 8192 |
| 29 | |
Gilad Arnold | 6f99b98 | 2012-09-12 17:49:40 | [diff] [blame] | 30 | |
Gilad Arnold | 17fe03d | 2012-10-02 17:05:01 | [diff] [blame] | 31 | class CommonUtilError(Exception): |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 32 | """Exception classes used by this module.""" |
| 33 | pass |
| 34 | |
| 35 | |
Chris Sosa | 4b95160 | 2014-04-10 03:26:07 | [diff] [blame] | 36 | class DevServerHTTPError(cherrypy.HTTPError): |
| 37 | """Exception class to log the HTTPResponse before routing it to cherrypy.""" |
| 38 | def __init__(self, status, message): |
| 39 | """CherryPy error with logging. |
| 40 | |
Chris Sosa | fc71544 | 2014-04-10 03:45:23 | [diff] [blame] | 41 | Args: |
| 42 | status: HTTPResponse status. |
| 43 | message: Message associated with the response. |
Chris Sosa | 4b95160 | 2014-04-10 03:26:07 | [diff] [blame] | 44 | """ |
| 45 | cherrypy.HTTPError.__init__(self, status, message) |
| 46 | _Log('HTTPError status: %s message: %s', status, message) |
| 47 | |
| 48 | |
Chris Sosa | 76e44b9 | 2013-01-31 20:11:38 | [diff] [blame] | 49 | def MkDirP(directory): |
Yiming Chen | 4e3741f | 2014-12-02 00:38:17 | [diff] [blame] | 50 | """Thread-safely create a directory like mkdir -p. |
| 51 | |
| 52 | If the directory already exists, call chown on the directory and its subfiles |
| 53 | recursively with current user and group to make sure current process has full |
| 54 | access to the directory. |
| 55 | """ |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 56 | try: |
Chris Sosa | 76e44b9 | 2013-01-31 20:11:38 | [diff] [blame] | 57 | os.makedirs(directory) |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 58 | except OSError, e: |
Yiming Chen | 4e3741f | 2014-12-02 00:38:17 | [diff] [blame] | 59 | if e.errno == errno.EEXIST and os.path.isdir(directory): |
| 60 | # Fix permissions and ownership of the directory and its subfiles by |
| 61 | # calling chown recursively with current user and group. |
| 62 | chown_command = [ |
| 63 | 'sudo', 'chown', '-R', '%s:%s' % (os.getuid(), os.getgid()), directory |
| 64 | ] |
| 65 | subprocess.Popen(chown_command).wait() |
| 66 | else: |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 67 | raise |
| 68 | |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 69 | |
Scott Zawalski | 1695453 | 2012-03-20 19:31:36 | [diff] [blame] | 70 | def GetLatestBuildVersion(static_dir, target, milestone=None): |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 71 | """Retrieves the latest build version for a given board. |
| 72 | |
joychen | 921e1fb | 2013-06-28 18:12:20 | [diff] [blame] | 73 | Searches the static_dir for builds for target, and returns the highest |
| 74 | version number currently available locally. |
| 75 | |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 76 | Args: |
| 77 | static_dir: Directory where builds are served from. |
Scott Zawalski | 1695453 | 2012-03-20 19:31:36 | [diff] [blame] | 78 | target: The build target, typically a combination of the board and the |
| 79 | type of build e.g. x86-mario-release. |
| 80 | milestone: For latest build set to None, for builds only in a specific |
| 81 | milestone set to a str of format Rxx (e.g. R16). Default: None. |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 82 | |
| 83 | Returns: |
Scott Zawalski | 1695453 | 2012-03-20 19:31:36 | [diff] [blame] | 84 | If latest found, a full build string is returned e.g. R17-1234.0.0-a1-b983. |
| 85 | If no latest is found for some reason or another a '' string is returned. |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 86 | |
| 87 | Raises: |
Gilad Arnold | 17fe03d | 2012-10-02 17:05:01 | [diff] [blame] | 88 | CommonUtilError: If for some reason the latest build cannot be |
Scott Zawalski | 1695453 | 2012-03-20 19:31:36 | [diff] [blame] | 89 | deteremined, this could be due to the dir not existing or no builds |
| 90 | being present after filtering on milestone. |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 91 | """ |
Scott Zawalski | 1695453 | 2012-03-20 19:31:36 | [diff] [blame] | 92 | target_path = os.path.join(static_dir, target) |
| 93 | if not os.path.isdir(target_path): |
Gilad Arnold | 17fe03d | 2012-10-02 17:05:01 | [diff] [blame] | 94 | raise CommonUtilError('Cannot find path %s' % target_path) |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 95 | |
Scott Zawalski | 1695453 | 2012-03-20 19:31:36 | [diff] [blame] | 96 | builds = [distutils.version.LooseVersion(build) for build in |
Dan Shi | 9fa4bde | 2013-12-02 21:40:07 | [diff] [blame] | 97 | os.listdir(target_path) if not build.endswith('.exception')] |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 98 | |
Scott Zawalski | 1695453 | 2012-03-20 19:31:36 | [diff] [blame] | 99 | if milestone and builds: |
| 100 | # Check if milestone Rxx is in the string representation of the build. |
| 101 | builds = filter(lambda x: milestone.upper() in str(x), builds) |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 102 | |
Scott Zawalski | 1695453 | 2012-03-20 19:31:36 | [diff] [blame] | 103 | if not builds: |
Gilad Arnold | 17fe03d | 2012-10-02 17:05:01 | [diff] [blame] | 104 | raise CommonUtilError('Could not determine build for %s' % target) |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 105 | |
Scott Zawalski | 1695453 | 2012-03-20 19:31:36 | [diff] [blame] | 106 | return str(max(builds)) |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 107 | |
| 108 | |
Chris Sosa | 76e44b9 | 2013-01-31 20:11:38 | [diff] [blame] | 109 | def PathInDir(directory, path): |
| 110 | """Returns True if the path is in directory. |
| 111 | |
| 112 | Args: |
| 113 | directory: Directory where the path should be in. |
| 114 | path: Path to check. |
| 115 | |
| 116 | Returns: |
| 117 | True if path is in static_dir, False otherwise |
| 118 | """ |
| 119 | directory = os.path.realpath(directory) |
| 120 | path = os.path.realpath(path) |
| 121 | return (path.startswith(directory) and len(path) != len(directory)) |
| 122 | |
| 123 | |
Scott Zawalski | 84a39c9 | 2012-01-13 20:12:42 | [diff] [blame] | 124 | def GetControlFile(static_dir, build, control_path): |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 125 | """Attempts to pull the requested control file from the Dev Server. |
| 126 | |
| 127 | Args: |
| 128 | static_dir: Directory where builds are served from. |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 129 | build: Fully qualified build string; e.g. R17-1234.0.0-a1-b983. |
| 130 | control_path: Path to control file on Dev Server relative to Autotest root. |
| 131 | |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 132 | Returns: |
| 133 | Content of the requested control file. |
Chris Sosa | fc71544 | 2014-04-10 03:45:23 | [diff] [blame] | 134 | |
| 135 | Raises: |
| 136 | CommonUtilError: If lock can't be acquired. |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 137 | """ |
Scott Zawalski | 1572d15 | 2012-01-16 19:36:02 | [diff] [blame] | 138 | # Be forgiving if the user passes in the control_path with a leading / |
| 139 | control_path = control_path.lstrip('/') |
Scott Zawalski | 84a39c9 | 2012-01-13 20:12:42 | [diff] [blame] | 140 | control_path = os.path.join(static_dir, build, 'autotest', |
Scott Zawalski | 4647ce6 | 2012-01-03 22:17:28 | [diff] [blame] | 141 | control_path) |
Chris Sosa | 76e44b9 | 2013-01-31 20:11:38 | [diff] [blame] | 142 | if not PathInDir(static_dir, control_path): |
Gilad Arnold | 55a2a37 | 2012-10-02 16:46:32 | [diff] [blame] | 143 | raise CommonUtilError('Invalid control file "%s".' % control_path) |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 144 | |
Scott Zawalski | 84a39c9 | 2012-01-13 20:12:42 | [diff] [blame] | 145 | if not os.path.exists(control_path): |
| 146 | # TODO(scottz): Come up with some sort of error mechanism. |
| 147 | # crosbug.com/25040 |
| 148 | return 'Unknown control path %s' % control_path |
| 149 | |
Frank Farzan | 37761d1 | 2011-12-01 22:29:08 | [diff] [blame] | 150 | with open(control_path, 'r') as control_file: |
| 151 | return control_file.read() |
| 152 | |
| 153 | |
beeps | bd33724 | 2013-07-10 05:44:06 | [diff] [blame] | 154 | def GetControlFileListForSuite(static_dir, build, suite_name): |
| 155 | """List all control files for a specified build, for the given suite. |
| 156 | |
| 157 | If the specified suite_name isn't found in the suite to control file |
| 158 | map, this method will return all control files for the build by calling |
| 159 | GetControlFileList. |
| 160 | |
| 161 | Args: |
| 162 | static_dir: Directory where builds are served from. |
| 163 | build: Fully qualified build string; e.g. R17-1234.0.0-a1-b983. |
| 164 | suite_name: Name of the suite for which we require control files. |
| 165 | |
Chris Sosa | fc71544 | 2014-04-10 03:45:23 | [diff] [blame] | 166 | Returns: |
| 167 | String of each control file separated by a newline. |
| 168 | |
beeps | bd33724 | 2013-07-10 05:44:06 | [diff] [blame] | 169 | Raises: |
| 170 | CommonUtilError: If the suite_to_control_file_map isn't found in |
| 171 | the specified build's staged directory. |
beeps | bd33724 | 2013-07-10 05:44:06 | [diff] [blame] | 172 | """ |
| 173 | suite_to_control_map = os.path.join(static_dir, build, |
| 174 | 'autotest', 'test_suites', |
| 175 | 'suite_to_control_file_map') |
| 176 | |
| 177 | if not PathInDir(static_dir, suite_to_control_map): |
| 178 | raise CommonUtilError('suite_to_control_map not in "%s".' % |
| 179 | suite_to_control_map) |
| 180 | |
| 181 | if not os.path.exists(suite_to_control_map): |
| 182 | raise CommonUtilError('Could not find this file. ' |
| 183 | 'Is it staged? %s' % suite_to_control_map) |
| 184 | |
| 185 | with open(suite_to_control_map, 'r') as fd: |
| 186 | try: |
| 187 | return '\n'.join(ast.literal_eval(fd.read())[suite_name]) |
| 188 | except KeyError: |
| 189 | return GetControlFileList(static_dir, build) |
| 190 | |
| 191 | |
Scott Zawalski | 84a39c9 | 2012-01-13 20:12:42 | [diff] [blame] | 192 | def GetControlFileList(static_dir, build): |
Scott Zawalski | 4647ce6 | 2012-01-03 22:17:28 | [diff] [blame] | 193 | """List all control|control. files in the specified board/build path. |
| 194 | |
| 195 | Args: |
| 196 | static_dir: Directory where builds are served from. |
Scott Zawalski | 4647ce6 | 2012-01-03 22:17:28 | [diff] [blame] | 197 | build: Fully qualified build string; e.g. R17-1234.0.0-a1-b983. |
| 198 | |
Scott Zawalski | 4647ce6 | 2012-01-03 22:17:28 | [diff] [blame] | 199 | Returns: |
| 200 | String of each file separated by a newline. |
Chris Sosa | fc71544 | 2014-04-10 03:45:23 | [diff] [blame] | 201 | |
| 202 | Raises: |
| 203 | CommonUtilError: If path is outside of sandbox. |
Scott Zawalski | 4647ce6 | 2012-01-03 22:17:28 | [diff] [blame] | 204 | """ |
Scott Zawalski | 1572d15 | 2012-01-16 19:36:02 | [diff] [blame] | 205 | autotest_dir = os.path.join(static_dir, build, 'autotest/') |
Chris Sosa | 76e44b9 | 2013-01-31 20:11:38 | [diff] [blame] | 206 | if not PathInDir(static_dir, autotest_dir): |
Gilad Arnold | 17fe03d | 2012-10-02 17:05:01 | [diff] [blame] | 207 | raise CommonUtilError('Autotest dir not in sandbox "%s".' % autotest_dir) |
Scott Zawalski | 4647ce6 | 2012-01-03 22:17:28 | [diff] [blame] | 208 | |
| 209 | control_files = set() |
Scott Zawalski | 84a39c9 | 2012-01-13 20:12:42 | [diff] [blame] | 210 | if not os.path.exists(autotest_dir): |
joychen | 3d164bd | 2013-06-25 01:12:23 | [diff] [blame] | 211 | raise CommonUtilError('Could not find this directory.' |
| 212 | 'Is it staged? %s' % autotest_dir) |
Scott Zawalski | 84a39c9 | 2012-01-13 20:12:42 | [diff] [blame] | 213 | |
Scott Zawalski | 4647ce6 | 2012-01-03 22:17:28 | [diff] [blame] | 214 | for entry in os.walk(autotest_dir): |
| 215 | dir_path, _, files = entry |
| 216 | for file_entry in files: |
| 217 | if file_entry.startswith('control.') or file_entry == 'control': |
| 218 | control_files.add(os.path.join(dir_path, |
Chris Sosa | ea148d9 | 2012-03-07 00:22:04 | [diff] [blame] | 219 | file_entry).replace(autotest_dir, '')) |
Scott Zawalski | 4647ce6 | 2012-01-03 22:17:28 | [diff] [blame] | 220 | |
| 221 | return '\n'.join(control_files) |
| 222 | |
| 223 | |
Gilad Arnold | 55a2a37 | 2012-10-02 16:46:32 | [diff] [blame] | 224 | def GetFileSize(file_path): |
| 225 | """Returns the size in bytes of the file given.""" |
| 226 | return os.path.getsize(file_path) |
| 227 | |
| 228 | |
Chris Sosa | 6a3697f | 2013-01-30 00:44:43 | [diff] [blame] | 229 | # Hashlib is strange and doesn't actually define these in a sane way that |
| 230 | # pylint can find them. Disable checks for them. |
| 231 | # pylint: disable=E1101,W0106 |
Gilad Arnold | 55a2a37 | 2012-10-02 16:46:32 | [diff] [blame] | 232 | def GetFileHashes(file_path, do_sha1=False, do_sha256=False, do_md5=False): |
| 233 | """Computes and returns a list of requested hashes. |
| 234 | |
| 235 | Args: |
| 236 | file_path: path to file to be hashed |
Chris Sosa | fc71544 | 2014-04-10 03:45:23 | [diff] [blame] | 237 | do_sha1: whether or not to compute a SHA1 hash |
Gilad Arnold | 55a2a37 | 2012-10-02 16:46:32 | [diff] [blame] | 238 | do_sha256: whether or not to compute a SHA256 hash |
Chris Sosa | fc71544 | 2014-04-10 03:45:23 | [diff] [blame] | 239 | do_md5: whether or not to compute a MD5 hash |
| 240 | |
Gilad Arnold | 55a2a37 | 2012-10-02 16:46:32 | [diff] [blame] | 241 | Returns: |
| 242 | A dictionary containing binary hash values, keyed by 'sha1', 'sha256' and |
| 243 | 'md5', respectively. |
| 244 | """ |
| 245 | hashes = {} |
| 246 | if (do_sha1 or do_sha256 or do_md5): |
| 247 | # Initialize hashers. |
| 248 | hasher_sha1 = hashlib.sha1() if do_sha1 else None |
| 249 | hasher_sha256 = hashlib.sha256() if do_sha256 else None |
| 250 | hasher_md5 = hashlib.md5() if do_md5 else None |
| 251 | |
| 252 | # Read blocks from file, update hashes. |
| 253 | with open(file_path, 'rb') as fd: |
| 254 | while True: |
| 255 | block = fd.read(_HASH_BLOCK_SIZE) |
| 256 | if not block: |
| 257 | break |
| 258 | hasher_sha1 and hasher_sha1.update(block) |
| 259 | hasher_sha256 and hasher_sha256.update(block) |
| 260 | hasher_md5 and hasher_md5.update(block) |
| 261 | |
| 262 | # Update return values. |
| 263 | if hasher_sha1: |
| 264 | hashes['sha1'] = hasher_sha1.digest() |
| 265 | if hasher_sha256: |
| 266 | hashes['sha256'] = hasher_sha256.digest() |
| 267 | if hasher_md5: |
| 268 | hashes['md5'] = hasher_md5.digest() |
| 269 | |
| 270 | return hashes |
| 271 | |
| 272 | |
| 273 | def GetFileSha1(file_path): |
| 274 | """Returns the SHA1 checksum of the file given (base64 encoded).""" |
| 275 | return base64.b64encode(GetFileHashes(file_path, do_sha1=True)['sha1']) |
| 276 | |
| 277 | |
| 278 | def GetFileSha256(file_path): |
| 279 | """Returns the SHA256 checksum of the file given (base64 encoded).""" |
| 280 | return base64.b64encode(GetFileHashes(file_path, do_sha256=True)['sha256']) |
| 281 | |
| 282 | |
| 283 | def GetFileMd5(file_path): |
| 284 | """Returns the MD5 checksum of the file given (hex encoded).""" |
| 285 | return binascii.hexlify(GetFileHashes(file_path, do_md5=True)['md5']) |
| 286 | |
| 287 | |
| 288 | def CopyFile(source, dest): |
| 289 | """Copies a file from |source| to |dest|.""" |
| 290 | _Log('Copy File %s -> %s' % (source, dest)) |
| 291 | shutil.copy(source, dest) |
Chris Sosa | 76e44b9 | 2013-01-31 20:11:38 | [diff] [blame] | 292 | |
| 293 | |
Alex Deymo | 3e2d495 | 2013-09-04 04:49:41 | [diff] [blame] | 294 | def SymlinkFile(target, link): |
| 295 | """Atomically creates or replaces the symlink |link| pointing to |target|. |
| 296 | |
| 297 | If the specified |link| file already exists it is replaced with the new link |
| 298 | atomically. |
| 299 | """ |
| 300 | if not os.path.exists(target): |
Chris Sosa | 7549080 | 2013-10-01 00:21:45 | [diff] [blame] | 301 | _Log('Could not find target for symlink: %s', target) |
Alex Deymo | 3e2d495 | 2013-09-04 04:49:41 | [diff] [blame] | 302 | return |
Chris Sosa | 7549080 | 2013-10-01 00:21:45 | [diff] [blame] | 303 | |
Alex Deymo | 3e2d495 | 2013-09-04 04:49:41 | [diff] [blame] | 304 | _Log('Creating symlink: %s --> %s', link, target) |
| 305 | |
| 306 | # Use the created link_base file to prevent other calls to SymlinkFile() to |
| 307 | # pick the same link_base temp file, thanks to mkstemp(). |
| 308 | with tempfile.NamedTemporaryFile(prefix=os.path.basename(link)) as link_fd: |
| 309 | link_base = link_fd.name |
| 310 | |
| 311 | # Use the unique link_base filename to create a symlink, but on the same |
| 312 | # directory as the required |link| to ensure the created symlink is in the |
| 313 | # same file system as |link|. |
| 314 | link_name = os.path.join(os.path.dirname(link), |
| 315 | os.path.basename(link_base) + "-link") |
| 316 | |
| 317 | # Create the symlink and then rename it to the final position. This ensures |
| 318 | # the symlink creation is atomic. |
| 319 | os.symlink(target, link_name) |
| 320 | os.rename(link_name, link) |
| 321 | |
| 322 | |
Chris Sosa | 76e44b9 | 2013-01-31 20:11:38 | [diff] [blame] | 323 | class LockDict(object): |
| 324 | """A dictionary of locks. |
| 325 | |
| 326 | This class provides a thread-safe store of threading.Lock objects, which can |
| 327 | be used to regulate access to any set of hashable resources. Usage: |
| 328 | |
| 329 | foo_lock_dict = LockDict() |
| 330 | ... |
| 331 | with foo_lock_dict.lock('bar'): |
| 332 | # Critical section for 'bar' |
| 333 | """ |
| 334 | def __init__(self): |
| 335 | self._lock = self._new_lock() |
| 336 | self._dict = {} |
| 337 | |
| 338 | @staticmethod |
| 339 | def _new_lock(): |
| 340 | return threading.Lock() |
| 341 | |
| 342 | def lock(self, key): |
| 343 | with self._lock: |
| 344 | lock = self._dict.get(key) |
| 345 | if not lock: |
| 346 | lock = self._new_lock() |
| 347 | self._dict[key] = lock |
| 348 | return lock |
Simran Basi | 4baad08 | 2013-02-14 21:39:18 | [diff] [blame] | 349 | |
| 350 | |
| 351 | def ExtractTarball(tarball_path, install_path, files_to_extract=None, |
Gilad Arnold | 1638d82 | 2013-11-08 07:38:16 | [diff] [blame] | 352 | excluded_files=None, return_extracted_files=False): |
Simran Basi | 4baad08 | 2013-02-14 21:39:18 | [diff] [blame] | 353 | """Extracts a tarball using tar. |
| 354 | |
| 355 | Detects whether the tarball is compressed or not based on the file |
| 356 | extension and extracts the tarball into the install_path. |
| 357 | |
| 358 | Args: |
| 359 | tarball_path: Path to the tarball to extract. |
| 360 | install_path: Path to extract the tarball to. |
| 361 | files_to_extract: String of specific files in the tarball to extract. |
| 362 | excluded_files: String of files to not extract. |
Chris Sosa | fc71544 | 2014-04-10 03:45:23 | [diff] [blame] | 363 | return_extracted_files: whether or not the caller expects the list of |
Gilad Arnold | 1638d82 | 2013-11-08 07:38:16 | [diff] [blame] | 364 | files extracted; if False, returns an empty list. |
Chris Sosa | fc71544 | 2014-04-10 03:45:23 | [diff] [blame] | 365 | |
Gilad Arnold | 1638d82 | 2013-11-08 07:38:16 | [diff] [blame] | 366 | Returns: |
| 367 | List of absolute paths of the files extracted (possibly empty). |
Simran Basi | 4baad08 | 2013-02-14 21:39:18 | [diff] [blame] | 368 | """ |
| 369 | # Deal with exclusions. |
| 370 | cmd = ['tar', 'xf', tarball_path, '--directory', install_path] |
| 371 | |
Gilad Arnold | 1638d82 | 2013-11-08 07:38:16 | [diff] [blame] | 372 | # If caller requires the list of extracted files, get verbose. |
| 373 | if return_extracted_files: |
| 374 | cmd += ['--verbose'] |
| 375 | |
Simran Basi | 4baad08 | 2013-02-14 21:39:18 | [diff] [blame] | 376 | # Determine how to decompress. |
| 377 | tarball = os.path.basename(tarball_path) |
| 378 | if tarball.endswith('.tar.bz2'): |
| 379 | cmd.append('--use-compress-prog=pbzip2') |
| 380 | elif tarball.endswith('.tgz') or tarball.endswith('.tar.gz'): |
| 381 | cmd.append('--gzip') |
| 382 | |
| 383 | if excluded_files: |
| 384 | for exclude in excluded_files: |
| 385 | cmd.extend(['--exclude', exclude]) |
| 386 | |
| 387 | if files_to_extract: |
| 388 | cmd.extend(files_to_extract) |
| 389 | |
| 390 | try: |
Gilad Arnold | 1638d82 | 2013-11-08 07:38:16 | [diff] [blame] | 391 | cmd_output = subprocess.check_output(cmd) |
| 392 | if return_extracted_files: |
| 393 | return [os.path.join(install_path, filename) |
| 394 | for filename in cmd_output.strip('\n').splitlines() |
| 395 | if not filename.endswith('/')] |
| 396 | return [] |
Simran Basi | 4baad08 | 2013-02-14 21:39:18 | [diff] [blame] | 397 | except subprocess.CalledProcessError, e: |
| 398 | raise CommonUtilError( |
| 399 | 'An error occurred when attempting to untar %s:\n%s' % |
joychen | 3d164bd | 2013-06-25 01:12:23 | [diff] [blame] | 400 | (tarball_path, e)) |
joychen | 7c2054a | 2013-07-25 18:14:07 | [diff] [blame] | 401 | |
| 402 | |
| 403 | def IsInsideChroot(): |
| 404 | """Returns True if we are inside chroot.""" |
| 405 | return os.path.exists('/etc/debian_chroot') |