maruel | ea586f3 | 2016-04-05 11:11:33 -0700 | [diff] [blame] | 1 | # Copyright 2014 The LUCI Authors. All rights reserved. |
maruel | f1f5e2a | 2016-05-25 17:10:39 -0700 | [diff] [blame] | 2 | # Use of this source code is governed under the Apache License, Version 2.0 |
| 3 | # that can be found in the LICENSE file. |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 4 | |
| 5 | """Understands .isolated files and can do local operations on them.""" |
| 6 | |
| 7 | import hashlib |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 8 | import json |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 9 | import logging |
| 10 | import os |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 11 | import re |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 12 | import stat |
| 13 | import sys |
| 14 | |
| 15 | from utils import file_path |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 16 | from utils import fs |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 17 | from utils import tools |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 18 | |
| 19 | |
| 20 | # Version stored and expected in .isolated files. |
tansell | 26de79e | 2016-11-13 18:41:11 -0800 | [diff] [blame] | 21 | ISOLATED_FILE_VERSION = '1.6' |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 22 | |
| 23 | |
| 24 | # Chunk size to use when doing disk I/O. |
| 25 | DISK_FILE_CHUNK = 1024 * 1024 |
| 26 | |
| 27 | |
Adrian Ludwin | b4ebc09 | 2017-09-13 07:46:24 -0400 | [diff] [blame] | 28 | # Sadly, hashlib uses 'shaX' instead of the standard 'sha-X' so explicitly |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 29 | # specify the names here. |
| 30 | SUPPORTED_ALGOS = { |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 31 | 'sha-1': hashlib.sha1, |
Adrian Ludwin | b4ebc09 | 2017-09-13 07:46:24 -0400 | [diff] [blame] | 32 | 'sha-256': hashlib.sha256, |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 33 | 'sha-512': hashlib.sha512, |
| 34 | } |
| 35 | |
| 36 | |
| 37 | # Used for serialization. |
| 38 | SUPPORTED_ALGOS_REVERSE = dict((v, k) for k, v in SUPPORTED_ALGOS.iteritems()) |
| 39 | |
Marc-Antoine Ruel | 7dafa77 | 2017-09-12 19:25:59 -0400 | [diff] [blame] | 40 | |
| 41 | SUPPORTED_FILE_TYPES = ['basic', 'tar'] |
tansell | e4288c3 | 2016-07-28 09:45:40 -0700 | [diff] [blame] | 42 | |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 43 | |
Marc-Antoine Ruel | 1e7658c | 2014-08-28 19:46:39 -0400 | [diff] [blame] | 44 | class IsolatedError(ValueError): |
| 45 | """Generic failure to load a .isolated file.""" |
| 46 | pass |
| 47 | |
| 48 | |
| 49 | class MappingError(OSError): |
| 50 | """Failed to recreate the tree.""" |
| 51 | pass |
| 52 | |
| 53 | |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 54 | def is_valid_hash(value, algo): |
| 55 | """Returns if the value is a valid hash for the corresponding algorithm.""" |
| 56 | size = 2 * algo().digest_size |
| 57 | return bool(re.match(r'^[a-fA-F0-9]{%d}$' % size, value)) |
| 58 | |
| 59 | |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 60 | def hash_file(filepath, algo): |
| 61 | """Calculates the hash of a file without reading it all in memory at once. |
| 62 | |
| 63 | |algo| should be one of hashlib hashing algorithm. |
| 64 | """ |
| 65 | digest = algo() |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 66 | with fs.open(filepath, 'rb') as f: |
Marc-Antoine Ruel | 8bee66d | 2014-08-28 19:02:07 -0400 | [diff] [blame] | 67 | while True: |
| 68 | chunk = f.read(DISK_FILE_CHUNK) |
| 69 | if not chunk: |
| 70 | break |
| 71 | digest.update(chunk) |
| 72 | return digest.hexdigest() |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 73 | |
| 74 | |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 75 | class IsolatedFile(object): |
| 76 | """Represents a single parsed .isolated file.""" |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 77 | |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 78 | def __init__(self, obj_hash, algo): |
Adrian Ludwin | b4ebc09 | 2017-09-13 07:46:24 -0400 | [diff] [blame] | 79 | """|obj_hash| is really the hash of the file.""" |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 80 | self.obj_hash = obj_hash |
| 81 | self.algo = algo |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 82 | |
| 83 | # Raw data. |
| 84 | self.data = {} |
| 85 | # A IsolatedFile instance, one per object in self.includes. |
| 86 | self.children = [] |
| 87 | |
| 88 | # Set once the .isolated file is loaded. |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 89 | self._is_loaded = False |
| 90 | |
| 91 | def __repr__(self): |
| 92 | return 'IsolatedFile(%s, loaded: %s)' % (self.obj_hash, self._is_loaded) |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 93 | |
| 94 | def load(self, content): |
| 95 | """Verifies the .isolated file is valid and loads this object with the json |
| 96 | data. |
| 97 | """ |
| 98 | logging.debug('IsolatedFile.load(%s)' % self.obj_hash) |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 99 | assert not self._is_loaded |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 100 | self.data = load_isolated(content, self.algo) |
| 101 | self.children = [ |
| 102 | IsolatedFile(i, self.algo) for i in self.data.get('includes', []) |
| 103 | ] |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 104 | self._is_loaded = True |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 105 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 106 | @property |
| 107 | def is_loaded(self): |
| 108 | """Returns True if 'load' was already called.""" |
| 109 | return self._is_loaded |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 110 | |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 111 | |
Vadim Shtayura | 7f7459c | 2014-09-04 13:25:10 -0700 | [diff] [blame] | 112 | def walk_includes(isolated): |
| 113 | """Walks IsolatedFile include graph and yields IsolatedFile objects. |
| 114 | |
| 115 | Visits root node first, then recursively all children, left to right. |
| 116 | Not yet loaded nodes are considered childless. |
| 117 | """ |
| 118 | yield isolated |
| 119 | for child in isolated.children: |
| 120 | for x in walk_includes(child): |
| 121 | yield x |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 122 | |
| 123 | |
Vadim Shtayura | c28b74f | 2014-10-06 20:00:08 -0700 | [diff] [blame] | 124 | @tools.profile |
Marc-Antoine Ruel | dcff646 | 2018-12-04 16:35:18 +0000 | [diff] [blame] | 125 | def _expand_symlinks(indir, relfile): |
| 126 | """Finds symlinks in relfile. |
| 127 | |
| 128 | Follows symlinks in |relfile|, but treating symlinks that point outside the |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 129 | build tree as if they were ordinary directories/files. Returns the final |
| 130 | symlink-free target and a list of paths to symlinks encountered in the |
| 131 | process. |
| 132 | |
| 133 | The rule about symlinks outside the build tree is for the benefit of the |
| 134 | Chromium OS ebuild, which symlinks the output directory to an unrelated path |
| 135 | in the chroot. |
| 136 | |
| 137 | Fails when a directory loop is detected, although in theory we could support |
| 138 | that case. |
Marc-Antoine Ruel | dcff646 | 2018-12-04 16:35:18 +0000 | [diff] [blame] | 139 | |
| 140 | Arguments: |
| 141 | - indir: base directory; symlinks in indir are not processed; this is |
| 142 | the base directory that is considered 'outside of the tree'. |
| 143 | - relfile: part of the path to expand symlink. |
| 144 | |
| 145 | Returns: |
| 146 | tuple(relfile, list(symlinks)): relfile is real path of relfile where all |
| 147 | symlinks were evaluated. symlinks if the chain of symlinks found along the |
| 148 | way, if any. |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 149 | """ |
| 150 | is_directory = relfile.endswith(os.path.sep) |
| 151 | done = indir |
| 152 | todo = relfile.strip(os.path.sep) |
| 153 | symlinks = [] |
| 154 | |
| 155 | while todo: |
Vadim Shtayura | 56c1756 | 2014-10-07 17:13:34 -0700 | [diff] [blame] | 156 | pre_symlink, symlink, post_symlink = file_path.split_at_symlink(done, todo) |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 157 | if not symlink: |
| 158 | todo = file_path.fix_native_path_case(done, todo) |
| 159 | done = os.path.join(done, todo) |
| 160 | break |
| 161 | symlink_path = os.path.join(done, pre_symlink, symlink) |
| 162 | post_symlink = post_symlink.lstrip(os.path.sep) |
| 163 | # readlink doesn't exist on Windows. |
| 164 | # pylint: disable=E1101 |
| 165 | target = os.path.normpath(os.path.join(done, pre_symlink)) |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 166 | symlink_target = fs.readlink(symlink_path) |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 167 | if os.path.isabs(symlink_target): |
| 168 | # Absolute path are considered a normal directories. The use case is |
| 169 | # generally someone who puts the output directory on a separate drive. |
| 170 | target = symlink_target |
| 171 | else: |
| 172 | # The symlink itself could be using the wrong path case. |
| 173 | target = file_path.fix_native_path_case(target, symlink_target) |
| 174 | |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 175 | if not fs.exists(target): |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 176 | raise MappingError( |
| 177 | 'Symlink target doesn\'t exist: %s -> %s' % (symlink_path, target)) |
| 178 | target = file_path.get_native_path_case(target) |
| 179 | if not file_path.path_starts_with(indir, target): |
| 180 | done = symlink_path |
| 181 | todo = post_symlink |
| 182 | continue |
| 183 | if file_path.path_starts_with(target, symlink_path): |
| 184 | raise MappingError( |
| 185 | 'Can\'t map recursive symlink reference %s -> %s' % |
| 186 | (symlink_path, target)) |
| 187 | logging.info('Found symlink: %s -> %s', symlink_path, target) |
| 188 | symlinks.append(os.path.relpath(symlink_path, indir)) |
| 189 | # Treat the common prefix of the old and new paths as done, and start |
| 190 | # scanning again. |
| 191 | target = target.split(os.path.sep) |
| 192 | symlink_path = symlink_path.split(os.path.sep) |
| 193 | prefix_length = 0 |
| 194 | for target_piece, symlink_path_piece in zip(target, symlink_path): |
Marc-Antoine Ruel | dcff646 | 2018-12-04 16:35:18 +0000 | [diff] [blame] | 195 | if target_piece != symlink_path_piece: |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 196 | break |
Marc-Antoine Ruel | dcff646 | 2018-12-04 16:35:18 +0000 | [diff] [blame] | 197 | prefix_length += 1 |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 198 | done = os.path.sep.join(target[:prefix_length]) |
| 199 | todo = os.path.join( |
| 200 | os.path.sep.join(target[prefix_length:]), post_symlink) |
| 201 | |
| 202 | relfile = os.path.relpath(done, indir) |
| 203 | relfile = relfile.rstrip(os.path.sep) + is_directory * os.path.sep |
| 204 | return relfile, symlinks |
| 205 | |
| 206 | |
Vadim Shtayura | c28b74f | 2014-10-06 20:00:08 -0700 | [diff] [blame] | 207 | @tools.profile |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 208 | def expand_directory_and_symlink(indir, relfile, blacklist, follow_symlinks): |
| 209 | """Expands a single input. It can result in multiple outputs. |
| 210 | |
| 211 | This function is recursive when relfile is a directory. |
| 212 | |
| 213 | Note: this code doesn't properly handle recursive symlink like one created |
| 214 | with: |
| 215 | ln -s .. foo |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 216 | |
| 217 | Yields: |
Marc-Antoine Ruel | 1b2885d | 2018-12-04 18:30:33 +0000 | [diff] [blame^] | 218 | tuple(Relative path, bool is_symlink) to files and symlinks inside |indir|. |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 219 | """ |
| 220 | if os.path.isabs(relfile): |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 221 | raise MappingError(u'Can\'t map absolute path %s' % relfile) |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 222 | |
| 223 | infile = file_path.normpath(os.path.join(indir, relfile)) |
| 224 | if not infile.startswith(indir): |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 225 | raise MappingError(u'Can\'t map file %s outside %s' % (infile, indir)) |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 226 | |
| 227 | filepath = os.path.join(indir, relfile) |
| 228 | native_filepath = file_path.get_native_path_case(filepath) |
| 229 | if filepath != native_filepath: |
| 230 | # Special case './'. |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 231 | if filepath != native_filepath + u'.' + os.path.sep: |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 232 | # While it'd be nice to enforce path casing on Windows, it's impractical. |
| 233 | # Also give up enforcing strict path case on OSX. Really, it's that sad. |
| 234 | # The case where it happens is very specific and hard to reproduce: |
| 235 | # get_native_path_case( |
| 236 | # u'Foo.framework/Versions/A/Resources/Something.nib') will return |
| 237 | # u'Foo.framework/Versions/A/resources/Something.nib', e.g. lowercase 'r'. |
| 238 | # |
| 239 | # Note that this is really something deep in OSX because running |
| 240 | # ls Foo.framework/Versions/A |
| 241 | # will print out 'Resources', while file_path.get_native_path_case() |
| 242 | # returns a lower case 'r'. |
| 243 | # |
| 244 | # So *something* is happening under the hood resulting in the command 'ls' |
| 245 | # and Carbon.File.FSPathMakeRef('path').FSRefMakePath() to disagree. We |
| 246 | # have no idea why. |
| 247 | if sys.platform not in ('darwin', 'win32'): |
| 248 | raise MappingError( |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 249 | u'File path doesn\'t equal native file path\n%s != %s' % |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 250 | (filepath, native_filepath)) |
| 251 | |
| 252 | symlinks = [] |
| 253 | if follow_symlinks: |
Marc-Antoine Ruel | a275b29 | 2014-11-25 15:17:21 -0500 | [diff] [blame] | 254 | try: |
Marc-Antoine Ruel | dcff646 | 2018-12-04 16:35:18 +0000 | [diff] [blame] | 255 | relfile, symlinks = _expand_symlinks(indir, relfile) |
Marc-Antoine Ruel | a275b29 | 2014-11-25 15:17:21 -0500 | [diff] [blame] | 256 | except OSError: |
| 257 | # The file doesn't exist, it will throw below. |
| 258 | pass |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 259 | |
Marc-Antoine Ruel | 1b2885d | 2018-12-04 18:30:33 +0000 | [diff] [blame^] | 260 | # The symlinks need to be mapped in. |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 261 | for s in symlinks: |
Marc-Antoine Ruel | 1b2885d | 2018-12-04 18:30:33 +0000 | [diff] [blame^] | 262 | yield s, True |
| 263 | |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 264 | if relfile.endswith(os.path.sep): |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 265 | if not fs.isdir(infile): |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 266 | raise MappingError( |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 267 | u'%s is not a directory but ends with "%s"' % (infile, os.path.sep)) |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 268 | |
| 269 | # Special case './'. |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 270 | if relfile.startswith(u'.' + os.path.sep): |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 271 | relfile = relfile[2:] |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 272 | try: |
maruel | 12e3001 | 2015-10-09 11:55:35 -0700 | [diff] [blame] | 273 | for filename in fs.listdir(infile): |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 274 | inner_relfile = os.path.join(relfile, filename) |
| 275 | if blacklist and blacklist(inner_relfile): |
| 276 | continue |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 277 | if fs.isdir(os.path.join(indir, inner_relfile)): |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 278 | inner_relfile += os.path.sep |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 279 | # Apply recursively. |
Marc-Antoine Ruel | 1b2885d | 2018-12-04 18:30:33 +0000 | [diff] [blame^] | 280 | for i, is_symlink in expand_directory_and_symlink( |
Marc-Antoine Ruel | cc802b0 | 2018-11-28 21:05:01 +0000 | [diff] [blame] | 281 | indir, inner_relfile, blacklist, follow_symlinks): |
Marc-Antoine Ruel | 1b2885d | 2018-12-04 18:30:33 +0000 | [diff] [blame^] | 282 | yield i, is_symlink |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 283 | except OSError as e: |
| 284 | raise MappingError( |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 285 | u'Unable to iterate over directory %s.\n%s' % (infile, e)) |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 286 | else: |
| 287 | # Always add individual files even if they were blacklisted. |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 288 | if fs.isdir(infile): |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 289 | raise MappingError( |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 290 | u'Input directory %s must have a trailing slash' % infile) |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 291 | |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 292 | if not fs.isfile(infile): |
| 293 | raise MappingError(u'Input file %s doesn\'t exist' % infile) |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 294 | |
Marc-Antoine Ruel | 1b2885d | 2018-12-04 18:30:33 +0000 | [diff] [blame^] | 295 | yield relfile, False |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 296 | |
| 297 | |
Vadim Shtayura | c28b74f | 2014-10-06 20:00:08 -0700 | [diff] [blame] | 298 | @tools.profile |
Marc-Antoine Ruel | 1b2885d | 2018-12-04 18:30:33 +0000 | [diff] [blame^] | 299 | def file_to_metadata(filepath, read_only, collapse_symlinks): |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 300 | """Processes an input file, a dependency, and return meta data about it. |
| 301 | |
| 302 | Behaviors: |
| 303 | - Retrieves the file mode, file size, file timestamp, file link |
| 304 | destination if it is a file link and calcultate the SHA-1 of the file's |
| 305 | content if the path points to a file and not a symlink. |
| 306 | |
| 307 | Arguments: |
| 308 | filepath: File to act on. |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 309 | read_only: If 1 or 2, the file mode is manipulated. In practice, only save |
| 310 | one of 4 modes: 0755 (rwx), 0644 (rw), 0555 (rx), 0444 (r). On |
| 311 | windows, mode is not set since all files are 'executable' by |
| 312 | default. |
kjlubick | 80596f0 | 2017-04-28 08:13:19 -0700 | [diff] [blame] | 313 | collapse_symlinks: True if symlinked files should be treated like they were |
| 314 | the normal underlying file. |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 315 | |
| 316 | Returns: |
| 317 | The necessary dict to create a entry in the 'files' section of an .isolated |
Marc-Antoine Ruel | 1b2885d | 2018-12-04 18:30:33 +0000 | [diff] [blame^] | 318 | file *except* 'h' for files. |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 319 | """ |
Marc-Antoine Ruel | f1d827c | 2014-11-24 15:22:25 -0500 | [diff] [blame] | 320 | # TODO(maruel): None is not a valid value. |
| 321 | assert read_only in (None, 0, 1, 2), read_only |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 322 | out = {} |
Marc-Antoine Ruel | 13554fd | 2018-12-04 18:01:05 +0000 | [diff] [blame] | 323 | # Always check the file stat and check if it is a link. |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 324 | try: |
kjlubick | 80596f0 | 2017-04-28 08:13:19 -0700 | [diff] [blame] | 325 | if collapse_symlinks: |
| 326 | # os.stat follows symbolic links |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 327 | filestats = fs.stat(filepath) |
kjlubick | 80596f0 | 2017-04-28 08:13:19 -0700 | [diff] [blame] | 328 | else: |
| 329 | # os.lstat does not follow symbolic links, and thus preserves them. |
Marc-Antoine Ruel | 7a68f71 | 2017-12-01 18:45:18 -0500 | [diff] [blame] | 330 | filestats = fs.lstat(filepath) |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 331 | except OSError: |
| 332 | # The file is not present. |
| 333 | raise MappingError('%s is missing' % filepath) |
| 334 | is_link = stat.S_ISLNK(filestats.st_mode) |
| 335 | |
| 336 | if sys.platform != 'win32': |
| 337 | # Ignore file mode on Windows since it's not really useful there. |
| 338 | filemode = stat.S_IMODE(filestats.st_mode) |
| 339 | # Remove write access for group and all access to 'others'. |
| 340 | filemode &= ~(stat.S_IWGRP | stat.S_IRWXO) |
| 341 | if read_only: |
| 342 | filemode &= ~stat.S_IWUSR |
Marc-Antoine Ruel | a275b29 | 2014-11-25 15:17:21 -0500 | [diff] [blame] | 343 | if filemode & (stat.S_IXUSR|stat.S_IRGRP) == (stat.S_IXUSR|stat.S_IRGRP): |
| 344 | # Only keep x group bit if both x user bit and group read bit are set. |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 345 | filemode |= stat.S_IXGRP |
| 346 | else: |
| 347 | filemode &= ~stat.S_IXGRP |
| 348 | if not is_link: |
| 349 | out['m'] = filemode |
| 350 | |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 351 | if not is_link: |
| 352 | out['s'] = filestats.st_size |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 353 | else: |
Marc-Antoine Ruel | 13554fd | 2018-12-04 18:01:05 +0000 | [diff] [blame] | 354 | # The link could be in an incorrect path case. In practice, this only |
| 355 | # happens on macOS on case insensitive HFS. |
| 356 | # TODO(maruel): It'd be better if it was only done once, in |
| 357 | # expand_directory_and_symlink(), so it would not be necessary to do again |
| 358 | # here. |
| 359 | symlink_value = fs.readlink(filepath) # pylint: disable=no-member |
| 360 | filedir = file_path.get_native_path_case(os.path.dirname(filepath)) |
| 361 | native_dest = file_path.fix_native_path_case(filedir, symlink_value) |
| 362 | out['l'] = os.path.relpath(native_dest, filedir) |
Marc-Antoine Ruel | 9225779 | 2014-08-28 20:51:08 -0400 | [diff] [blame] | 363 | return out |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 364 | |
| 365 | |
| 366 | def save_isolated(isolated, data): |
| 367 | """Writes one or multiple .isolated files. |
| 368 | |
| 369 | Note: this reference implementation does not create child .isolated file so it |
| 370 | always returns an empty list. |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 371 | """ |
| 372 | # Make sure the data is valid .isolated data by 'reloading' it. |
| 373 | algo = SUPPORTED_ALGOS[data['algo']] |
| 374 | load_isolated(json.dumps(data), algo) |
| 375 | tools.write_json(isolated, data, True) |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 376 | |
| 377 | |
maruel | df6e95e | 2016-02-26 19:05:38 -0800 | [diff] [blame] | 378 | def split_path(path): |
| 379 | """Splits a path and return a list with each element.""" |
| 380 | out = [] |
| 381 | while path: |
| 382 | path, rest = os.path.split(path) |
| 383 | if rest: |
| 384 | out.append(rest) |
| 385 | return out |
| 386 | |
| 387 | |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 388 | def load_isolated(content, algo): |
| 389 | """Verifies the .isolated file is valid and loads this object with the json |
| 390 | data. |
| 391 | |
| 392 | Arguments: |
| 393 | - content: raw serialized content to load. |
| 394 | - algo: hashlib algorithm class. Used to confirm the algorithm matches the |
| 395 | algorithm used on the Isolate Server. |
| 396 | """ |
Marc-Antoine Ruel | 5da404c | 2017-10-31 10:46:37 -0400 | [diff] [blame] | 397 | if not algo: |
| 398 | raise IsolatedError('\'algo\' is required') |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 399 | try: |
| 400 | data = json.loads(content) |
aludwin | 6b54a6b | 2017-08-03 18:20:06 -0700 | [diff] [blame] | 401 | except ValueError as v: |
Adrian Ludwin | 7dc29dd | 2017-08-17 23:01:47 -0400 | [diff] [blame] | 402 | logging.error('Failed to parse .isolated file:\n%s', content) |
aludwin | 6b54a6b | 2017-08-03 18:20:06 -0700 | [diff] [blame] | 403 | raise IsolatedError('Failed to parse (%s): %s...' % (v, content[:100])) |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 404 | |
| 405 | if not isinstance(data, dict): |
| 406 | raise IsolatedError('Expected dict, got %r' % data) |
| 407 | |
| 408 | # Check 'version' first, since it could modify the parsing after. |
| 409 | value = data.get('version', '1.0') |
| 410 | if not isinstance(value, basestring): |
| 411 | raise IsolatedError('Expected string, got %r' % value) |
| 412 | try: |
| 413 | version = tuple(map(int, value.split('.'))) |
| 414 | except ValueError: |
| 415 | raise IsolatedError('Expected valid version, got %r' % value) |
| 416 | |
| 417 | expected_version = tuple(map(int, ISOLATED_FILE_VERSION.split('.'))) |
| 418 | # Major version must match. |
| 419 | if version[0] != expected_version[0]: |
| 420 | raise IsolatedError( |
| 421 | 'Expected compatible \'%s\' version, got %r' % |
| 422 | (ISOLATED_FILE_VERSION, value)) |
| 423 | |
Adrian Ludwin | b4ebc09 | 2017-09-13 07:46:24 -0400 | [diff] [blame] | 424 | algo_name = SUPPORTED_ALGOS_REVERSE[algo] |
| 425 | |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 426 | for key, value in data.iteritems(): |
| 427 | if key == 'algo': |
| 428 | if not isinstance(value, basestring): |
| 429 | raise IsolatedError('Expected string, got %r' % value) |
| 430 | if value not in SUPPORTED_ALGOS: |
| 431 | raise IsolatedError( |
| 432 | 'Expected one of \'%s\', got %r' % |
| 433 | (', '.join(sorted(SUPPORTED_ALGOS)), value)) |
| 434 | if value != SUPPORTED_ALGOS_REVERSE[algo]: |
| 435 | raise IsolatedError( |
| 436 | 'Expected \'%s\', got %r' % (SUPPORTED_ALGOS_REVERSE[algo], value)) |
| 437 | |
| 438 | elif key == 'command': |
| 439 | if not isinstance(value, list): |
| 440 | raise IsolatedError('Expected list, got %r' % value) |
| 441 | if not value: |
| 442 | raise IsolatedError('Expected non-empty command') |
| 443 | for subvalue in value: |
| 444 | if not isinstance(subvalue, basestring): |
| 445 | raise IsolatedError('Expected string, got %r' % subvalue) |
| 446 | |
| 447 | elif key == 'files': |
| 448 | if not isinstance(value, dict): |
| 449 | raise IsolatedError('Expected dict, got %r' % value) |
| 450 | for subkey, subvalue in value.iteritems(): |
| 451 | if not isinstance(subkey, basestring): |
| 452 | raise IsolatedError('Expected string, got %r' % subkey) |
maruel | df6e95e | 2016-02-26 19:05:38 -0800 | [diff] [blame] | 453 | if os.path.isabs(subkey) or subkey.startswith('\\\\'): |
| 454 | # Disallow '\\\\', it could UNC on Windows but disallow this |
| 455 | # everywhere. |
| 456 | raise IsolatedError('File path can\'t be absolute: %r' % subkey) |
| 457 | if subkey.endswith(('/', '\\')): |
| 458 | raise IsolatedError( |
| 459 | 'File path can\'t end with \'%s\': %r' % (subkey[-1], subkey)) |
| 460 | if '..' in split_path(subkey): |
| 461 | raise IsolatedError('File path can\'t reference parent: %r' % subkey) |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 462 | if not isinstance(subvalue, dict): |
| 463 | raise IsolatedError('Expected dict, got %r' % subvalue) |
| 464 | for subsubkey, subsubvalue in subvalue.iteritems(): |
| 465 | if subsubkey == 'l': |
| 466 | if not isinstance(subsubvalue, basestring): |
| 467 | raise IsolatedError('Expected string, got %r' % subsubvalue) |
| 468 | elif subsubkey == 'm': |
| 469 | if not isinstance(subsubvalue, int): |
| 470 | raise IsolatedError('Expected int, got %r' % subsubvalue) |
| 471 | elif subsubkey == 'h': |
| 472 | if not is_valid_hash(subsubvalue, algo): |
Adrian Ludwin | b4ebc09 | 2017-09-13 07:46:24 -0400 | [diff] [blame] | 473 | raise IsolatedError('Expected %s, got %r' % |
| 474 | (algo_name, subsubvalue)) |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 475 | elif subsubkey == 's': |
| 476 | if not isinstance(subsubvalue, (int, long)): |
| 477 | raise IsolatedError('Expected int or long, got %r' % subsubvalue) |
tansell | e4288c3 | 2016-07-28 09:45:40 -0700 | [diff] [blame] | 478 | elif subsubkey == 't': |
| 479 | if subsubvalue not in SUPPORTED_FILE_TYPES: |
| 480 | raise IsolatedError('Expected one of \'%s\', got %r' % ( |
| 481 | ', '.join(sorted(SUPPORTED_FILE_TYPES)), subsubvalue)) |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 482 | else: |
| 483 | raise IsolatedError('Unknown subsubkey %s' % subsubkey) |
| 484 | if bool('h' in subvalue) == bool('l' in subvalue): |
| 485 | raise IsolatedError( |
Adrian Ludwin | b4ebc09 | 2017-09-13 07:46:24 -0400 | [diff] [blame] | 486 | 'Need only one of \'h\' (%s) or \'l\' (link), got: %r' % |
| 487 | (algo_name, subvalue)) |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 488 | if bool('h' in subvalue) != bool('s' in subvalue): |
| 489 | raise IsolatedError( |
Adrian Ludwin | b4ebc09 | 2017-09-13 07:46:24 -0400 | [diff] [blame] | 490 | 'Both \'h\' (%s) and \'s\' (size) should be set, got: %r' % |
| 491 | (algo_name, subvalue)) |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 492 | if bool('s' in subvalue) == bool('l' in subvalue): |
| 493 | raise IsolatedError( |
| 494 | 'Need only one of \'s\' (size) or \'l\' (link), got: %r' % |
| 495 | subvalue) |
| 496 | if bool('l' in subvalue) and bool('m' in subvalue): |
| 497 | raise IsolatedError( |
| 498 | 'Cannot use \'m\' (mode) and \'l\' (link), got: %r' % |
| 499 | subvalue) |
| 500 | |
| 501 | elif key == 'includes': |
| 502 | if not isinstance(value, list): |
| 503 | raise IsolatedError('Expected list, got %r' % value) |
| 504 | if not value: |
| 505 | raise IsolatedError('Expected non-empty includes list') |
| 506 | for subvalue in value: |
| 507 | if not is_valid_hash(subvalue, algo): |
Adrian Ludwin | b4ebc09 | 2017-09-13 07:46:24 -0400 | [diff] [blame] | 508 | raise IsolatedError('Expected %s, got %r' % (algo_name, subvalue)) |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 509 | |
| 510 | elif key == 'os': |
| 511 | if version >= (1, 4): |
| 512 | raise IsolatedError('Key \'os\' is not allowed starting version 1.4') |
| 513 | |
| 514 | elif key == 'read_only': |
| 515 | if not value in (0, 1, 2): |
| 516 | raise IsolatedError('Expected 0, 1 or 2, got %r' % value) |
| 517 | |
| 518 | elif key == 'relative_cwd': |
| 519 | if not isinstance(value, basestring): |
| 520 | raise IsolatedError('Expected string, got %r' % value) |
| 521 | |
| 522 | elif key == 'version': |
| 523 | # Already checked above. |
| 524 | pass |
| 525 | |
| 526 | else: |
| 527 | raise IsolatedError('Unknown key %r' % key) |
| 528 | |
| 529 | # Automatically fix os.path.sep if necessary. While .isolated files are always |
Marc-Antoine Ruel | f674a58 | 2018-01-12 10:56:01 -0500 | [diff] [blame] | 530 | # in the native path format, someone could want to download an .isolated tree |
| 531 | # from another OS. |
Marc-Antoine Ruel | 52436aa | 2014-08-28 21:57:57 -0400 | [diff] [blame] | 532 | wrong_path_sep = '/' if os.path.sep == '\\' else '\\' |
| 533 | if 'files' in data: |
| 534 | data['files'] = dict( |
| 535 | (k.replace(wrong_path_sep, os.path.sep), v) |
| 536 | for k, v in data['files'].iteritems()) |
| 537 | for v in data['files'].itervalues(): |
| 538 | if 'l' in v: |
| 539 | v['l'] = v['l'].replace(wrong_path_sep, os.path.sep) |
| 540 | if 'relative_cwd' in data: |
| 541 | data['relative_cwd'] = data['relative_cwd'].replace( |
| 542 | wrong_path_sep, os.path.sep) |
| 543 | return data |