Jim MacArthur pushed to branch jmac/cas_to_cas_v2 at BuildStream / buildstream
Commits:
2 changed files:
Changes:
| ... | ... | @@ -38,6 +38,8 @@ from .._exceptions import BstError |
| 38 | 38 |
from .directory import Directory, VirtualDirectoryError
|
| 39 | 39 |
from ._filebaseddirectory import FileBasedDirectory
|
| 40 | 40 |
from ..utils import FileListResult, safe_copy, list_relative_paths
|
| 41 |
+from ..utils import FileListResult, safe_copy, list_relative_paths, _relative_symlink_target
|
|
| 42 |
+from .._artifactcache.cascache import CASCache
|
|
| 41 | 43 |
|
| 42 | 44 |
|
| 43 | 45 |
class IndexEntry():
|
| ... | ... | @@ -51,6 +53,20 @@ class IndexEntry(): |
| 51 | 53 |
self.modified = modified
|
| 52 | 54 |
|
| 53 | 55 |
|
| 56 |
+class ResolutionException(Exception):
|
|
| 57 |
+ """ Superclass of all exceptions that can be raised by CasBasedDirectory._resolve. Should not be exposed externally."""
|
|
| 58 |
+ pass
|
|
| 59 |
+ |
|
| 60 |
+class InfiniteSymlinkException(ResolutionException):
|
|
| 61 |
+ """ Raised when an infinite symlink loop is found. """
|
|
| 62 |
+ pass
|
|
| 63 |
+ |
|
| 64 |
+class AbsoluteSymlinkException(ResolutionException):
|
|
| 65 |
+ """Raised if we try to follow an absolute symlink (i.e. one whose
|
|
| 66 |
+ target starts with the path separator) and we have disallowed
|
|
| 67 |
+ following such symlinks. """
|
|
| 68 |
+ pass
|
|
| 69 |
+ |
|
| 54 | 70 |
# CasBasedDirectory intentionally doesn't call its superclass constuctor,
|
| 55 | 71 |
# which is meant to be unimplemented.
|
| 56 | 72 |
# pylint: disable=super-init-not-called
|
| ... | ... | @@ -176,21 +192,26 @@ class CasBasedDirectory(Directory): |
| 176 | 192 |
filenode.is_executable = is_executable
|
| 177 | 193 |
self.index[filename] = IndexEntry(filenode, modified=(filename in self.index))
|
| 178 | 194 |
|
| 179 |
- def _add_new_link(self, basename, filename):
|
|
| 180 |
- existing_link = self._find_pb2_entry(filename)
|
|
| 195 |
+ def _copy_link_from_filesystem(self, basename, filename):
|
|
| 196 |
+ self._add_new_link_direct(filename, os.readlink(os.path.join(basename, filename)))
|
|
| 197 |
+ |
|
| 198 |
+ def _add_new_link_direct(self, name, target):
|
|
| 199 |
+ existing_link = self._find_pb2_entry(name)
|
|
| 181 | 200 |
if existing_link:
|
| 182 | 201 |
symlinknode = existing_link
|
| 183 | 202 |
else:
|
| 184 | 203 |
symlinknode = self.pb2_directory.symlinks.add()
|
| 185 |
- symlinknode.name = filename
|
|
| 204 |
+ assert(isinstance(symlinknode, remote_execution_pb2.SymlinkNode))
|
|
| 205 |
+ symlinknode.name = name
|
|
| 186 | 206 |
# A symlink node has no digest.
|
| 187 |
- symlinknode.target = os.readlink(os.path.join(basename, filename))
|
|
| 188 |
- self.index[filename] = IndexEntry(symlinknode, modified=(existing_link is not None))
|
|
| 207 |
+ symlinknode.target = target
|
|
| 208 |
+ self.index[name] = IndexEntry(symlinknode, modified=(existing_link is not None))
|
|
| 189 | 209 |
|
| 190 | 210 |
def delete_entry(self, name):
|
| 191 | 211 |
for collection in [self.pb2_directory.files, self.pb2_directory.symlinks, self.pb2_directory.directories]:
|
| 192 |
- if name in collection:
|
|
| 193 |
- collection.remove(name)
|
|
| 212 |
+ for thing in collection:
|
|
| 213 |
+ if thing.name == name:
|
|
| 214 |
+ collection.remove(thing)
|
|
| 194 | 215 |
if name in self.index:
|
| 195 | 216 |
del self.index[name]
|
| 196 | 217 |
|
| ... | ... | @@ -231,9 +252,13 @@ class CasBasedDirectory(Directory): |
| 231 | 252 |
if isinstance(entry, CasBasedDirectory):
|
| 232 | 253 |
return entry.descend(subdirectory_spec[1:], create)
|
| 233 | 254 |
else:
|
| 255 |
+ # May be a symlink
|
|
| 256 |
+ target = self._resolve(subdirectory_spec[0], force_create=create)
|
|
| 257 |
+ if isinstance(target, CasBasedDirectory):
|
|
| 258 |
+ return target
|
|
| 234 | 259 |
error = "Cannot descend into {}, which is a '{}' in the directory {}"
|
| 235 | 260 |
raise VirtualDirectoryError(error.format(subdirectory_spec[0],
|
| 236 |
- type(entry).__name__,
|
|
| 261 |
+ type(self.index[subdirectory_spec[0]].pb_object).__name__,
|
|
| 237 | 262 |
self))
|
| 238 | 263 |
else:
|
| 239 | 264 |
if create:
|
| ... | ... | @@ -254,7 +279,7 @@ class CasBasedDirectory(Directory): |
| 254 | 279 |
else:
|
| 255 | 280 |
return self
|
| 256 | 281 |
|
| 257 |
- def _resolve_symlink_or_directory(self, name):
|
|
| 282 |
+ def _force_resolve(self, name):
|
|
| 258 | 283 |
"""Used only by _import_files_from_directory. Tries to resolve a
|
| 259 | 284 |
directory name or symlink name. 'name' must be an entry in this
|
| 260 | 285 |
directory. It must be a single symlink or directory name, not a path
|
| ... | ... | @@ -267,23 +292,128 @@ class CasBasedDirectory(Directory): |
| 267 | 292 |
as a directory as long as it's within this directory tree.
|
| 268 | 293 |
"""
|
| 269 | 294 |
|
| 295 |
+ return self._resolve(name, force_create=True)
|
|
| 296 |
+ |
|
| 297 |
+ def _is_followable(self, name):
|
|
| 298 |
+ """ Returns true if this is a directory or symlink to a valid directory. """
|
|
| 299 |
+ if name not in self.index:
|
|
| 300 |
+ return False
|
|
| 270 | 301 |
if isinstance(self.index[name].buildstream_object, Directory):
|
| 271 |
- return self.index[name].buildstream_object
|
|
| 272 |
- # OK then, it's a symlink
|
|
| 273 |
- symlink = self._find_pb2_entry(name)
|
|
| 302 |
+ return True
|
|
| 303 |
+ try:
|
|
| 304 |
+ target = self._resolve(name)
|
|
| 305 |
+ except InfiniteSymlinkException:
|
|
| 306 |
+ return False
|
|
| 307 |
+ return isinstance(target, CasBasedDirectory) or target is None
|
|
| 308 |
+ # TODO: But why return True if it's None (broken link/circular loop)? Surely that is against the docstring.
|
|
| 309 |
+ |
|
| 310 |
+ def _resolve(self, name, absolute_symlinks_resolve=True, force_create=False, seen_objects=None):
|
|
| 311 |
+ """Resolves any name to an object. If the name points to a symlink in
|
|
| 312 |
+ this directory, it returns the thing it points to,
|
|
| 313 |
+ recursively.
|
|
| 314 |
+ |
|
| 315 |
+ Returns a CasBasedDirectory, FileNode or None. None indicates
|
|
| 316 |
+ either that 'none' does not exist in this directory, or is a
|
|
| 317 |
+ symlink chain which points to a nonexistent name (broken
|
|
| 318 |
+ symlink).
|
|
| 319 |
+ |
|
| 320 |
+ |
|
| 321 |
+ Raises:
|
|
| 322 |
+ - InfiniteSymlinkException if 'name' points to an infinite symlink loop.
|
|
| 323 |
+ - AbsoluteSymlinkException if 'name' points to an absolute symlink and absolute_symlinks_resolve is False.
|
|
| 324 |
+ |
|
| 325 |
+ If force_create is on, this will attempt to create directories to make symlinks and directories resolve.
|
|
| 326 |
+ If force_create is off, this will never alter this directory.
|
|
| 327 |
+ |
|
| 328 |
+ """
|
|
| 329 |
+ |
|
| 330 |
+ if name not in self.index:
|
|
| 331 |
+ return None
|
|
| 332 |
+ |
|
| 333 |
+ # First check if it's a normal object and return that
|
|
| 334 |
+ index_entry = self.index[name]
|
|
| 335 |
+ if isinstance(index_entry.buildstream_object, Directory):
|
|
| 336 |
+ return index_entry.buildstream_object
|
|
| 337 |
+ elif isinstance(index_entry.pb_object, remote_execution_pb2.FileNode):
|
|
| 338 |
+ return index_entry.pb_object
|
|
| 339 |
+ |
|
| 340 |
+ assert isinstance(index_entry.pb_object, remote_execution_pb2.SymlinkNode)
|
|
| 341 |
+ |
|
| 342 |
+ if seen_objects is None:
|
|
| 343 |
+ seen_objects = [index_entry.pb_object]
|
|
| 344 |
+ else:
|
|
| 345 |
+ if index_entry.pb_object in seen_objects:
|
|
| 346 |
+ # Infinite symlink loop detected
|
|
| 347 |
+ raise InfiniteSymlinkException()
|
|
| 348 |
+ |
|
| 349 |
+ symlink = index_entry.pb_object
|
|
| 350 |
+ components = symlink.target.split(CasBasedDirectory._pb2_path_sep)
|
|
| 351 |
+ |
|
| 274 | 352 |
absolute = symlink.target.startswith(CasBasedDirectory._pb2_absolute_path_prefix)
|
| 275 | 353 |
if absolute:
|
| 276 |
- root = self.find_root()
|
|
| 354 |
+ if absolute_symlinks_resolve:
|
|
| 355 |
+ start_directory = self.find_root()
|
|
| 356 |
+ # Discard the first empty element
|
|
| 357 |
+ components.pop(0)
|
|
| 358 |
+ else:
|
|
| 359 |
+ # Unresolvable absolute symlink
|
|
| 360 |
+ raise AbsoluteSymlinkException()
|
|
| 277 | 361 |
else:
|
| 278 |
- root = self
|
|
| 279 |
- directory = root
|
|
| 280 |
- components = symlink.target.split(CasBasedDirectory._pb2_path_sep)
|
|
| 281 |
- for c in components:
|
|
| 282 |
- if c == "..":
|
|
| 283 |
- directory = directory.parent
|
|
| 362 |
+ start_directory = self
|
|
| 363 |
+ |
|
| 364 |
+ directory = start_directory
|
|
| 365 |
+ while True:
|
|
| 366 |
+ if not components:
|
|
| 367 |
+ # We ran out of path elements and ended up in a directory
|
|
| 368 |
+ return directory
|
|
| 369 |
+ c = components.pop(0)
|
|
| 370 |
+ if c == ".":
|
|
| 371 |
+ pass
|
|
| 372 |
+ elif c == "..":
|
|
| 373 |
+ if directory.parent is not None:
|
|
| 374 |
+ directory = directory.parent
|
|
| 375 |
+ # If directory.parent *is* None, this is an attempt to access
|
|
| 376 |
+ # '..' from the root, which is valid under POSIX; it just
|
|
| 377 |
+ # returns the root.
|
|
| 378 |
+ elif c in directory.index:
|
|
| 379 |
+ # Recursive resolve and continue
|
|
| 380 |
+ try:
|
|
| 381 |
+ f = directory._resolve(c, absolute_symlinks_resolve, seen_objects=seen_objects)
|
|
| 382 |
+ except ResolutionException:
|
|
| 383 |
+ f = None
|
|
| 384 |
+ if isinstance(f, CasBasedDirectory):
|
|
| 385 |
+ directory = f
|
|
| 386 |
+ elif isinstance(f, remote_execution_pb2.FileNode):
|
|
| 387 |
+ if components:
|
|
| 388 |
+ # We have components still to resolve, but one of the path components
|
|
| 389 |
+ # is a file.
|
|
| 390 |
+ if force_create:
|
|
| 391 |
+ self.delete_entry(c)
|
|
| 392 |
+ directory = directory.descend(c, create=True)
|
|
| 393 |
+ else:
|
|
| 394 |
+ return f
|
|
| 395 |
+ # TODO: Why return f? We've got
|
|
| 396 |
+ # components left and hit a file; this
|
|
| 397 |
+ # should be an error.
|
|
| 398 |
+ |
|
| 399 |
+ # errormsg = "Reached a file called {} while trying to resolve a symlink; cannot proceed"
|
|
| 400 |
+ # raise VirtualDirectoryError(errormsg.format(c))
|
|
| 401 |
+ else:
|
|
| 402 |
+ # It's a file, and there's no path components left, so just return that.
|
|
| 403 |
+ return f
|
|
| 404 |
+ else:
|
|
| 405 |
+ # f was not found
|
|
| 406 |
+ if force_create:
|
|
| 407 |
+ directory = directory.descend(c, create=True)
|
|
| 408 |
+ else:
|
|
| 409 |
+ return None
|
|
| 284 | 410 |
else:
|
| 285 |
- directory = directory.descend(c, create=True)
|
|
| 286 |
- return directory
|
|
| 411 |
+ # c is not in our index
|
|
| 412 |
+ if force_create:
|
|
| 413 |
+ directory = directory.descend(c, create=True)
|
|
| 414 |
+ else:
|
|
| 415 |
+ return None
|
|
| 416 |
+ # You can only exit the while loop with a return, or exception, so you shouldn't be here.
|
|
| 287 | 417 |
|
| 288 | 418 |
def _check_replacement(self, name, path_prefix, fileListResult):
|
| 289 | 419 |
""" Checks whether 'name' exists, and if so, whether we can overwrite it.
|
| ... | ... | @@ -297,6 +427,7 @@ class CasBasedDirectory(Directory): |
| 297 | 427 |
return True
|
| 298 | 428 |
if (isinstance(existing_entry,
|
| 299 | 429 |
(remote_execution_pb2.FileNode, remote_execution_pb2.SymlinkNode))):
|
| 430 |
+ self.delete_entry(name)
|
|
| 300 | 431 |
fileListResult.overwritten.append(relative_pathname)
|
| 301 | 432 |
return True
|
| 302 | 433 |
elif isinstance(existing_entry, remote_execution_pb2.DirectoryNode):
|
| ... | ... | @@ -314,23 +445,29 @@ class CasBasedDirectory(Directory): |
| 314 | 445 |
.format(name, type(existing_entry)))
|
| 315 | 446 |
return False # In case asserts are disabled
|
| 316 | 447 |
|
| 317 |
- def _import_directory_recursively(self, directory_name, source_directory, remaining_path, path_prefix):
|
|
| 318 |
- """ _import_directory_recursively and _import_files_from_directory will be called alternately
|
|
| 319 |
- as a directory tree is descended. """
|
|
| 320 |
- if directory_name in self.index:
|
|
| 321 |
- subdir = self._resolve_symlink_or_directory(directory_name)
|
|
| 322 |
- else:
|
|
| 323 |
- subdir = self._add_directory(directory_name)
|
|
| 324 |
- new_path_prefix = os.path.join(path_prefix, directory_name)
|
|
| 325 |
- subdir_result = subdir._import_files_from_directory(os.path.join(source_directory, directory_name),
|
|
| 326 |
- [os.path.sep.join(remaining_path)],
|
|
| 327 |
- path_prefix=new_path_prefix)
|
|
| 328 |
- return subdir_result
|
|
| 329 |
- |
|
| 330 | 448 |
def _import_files_from_directory(self, source_directory, files, path_prefix=""):
|
| 331 |
- """ Imports files from a traditional directory """
|
|
| 449 |
+ """ Imports files from a traditional directory. """
|
|
| 450 |
+ |
|
| 451 |
+ def _import_directory_recursively(directory_name, source_directory, remaining_path, path_prefix):
|
|
| 452 |
+ """ _import_directory_recursively and _import_files_from_directory will be called alternately
|
|
| 453 |
+ as a directory tree is descended. """
|
|
| 454 |
+ if directory_name in self.index:
|
|
| 455 |
+ if self._is_followable(directory_name):
|
|
| 456 |
+ subdir = self._force_resolve(directory_name)
|
|
| 457 |
+ else:
|
|
| 458 |
+ self.delete_entry(directory_name)
|
|
| 459 |
+ subdir = self._add_directory(directory_name)
|
|
| 460 |
+ result.overwritten.append(relative_pathname)
|
|
| 461 |
+ else:
|
|
| 462 |
+ subdir = self._add_directory(directory_name)
|
|
| 463 |
+ new_path_prefix = os.path.join(path_prefix, directory_name)
|
|
| 464 |
+ subdir_result = subdir._import_files_from_directory(os.path.join(source_directory, directory_name),
|
|
| 465 |
+ [os.path.sep.join(remaining_path)],
|
|
| 466 |
+ path_prefix=new_path_prefix)
|
|
| 467 |
+ return subdir_result
|
|
| 468 |
+ |
|
| 332 | 469 |
result = FileListResult()
|
| 333 |
- for entry in sorted(files):
|
|
| 470 |
+ for entry in files:
|
|
| 334 | 471 |
split_path = entry.split(os.path.sep)
|
| 335 | 472 |
# The actual file on the FS we're importing
|
| 336 | 473 |
import_file = os.path.join(source_directory, entry)
|
| ... | ... | @@ -338,14 +475,18 @@ class CasBasedDirectory(Directory): |
| 338 | 475 |
relative_pathname = os.path.join(path_prefix, entry)
|
| 339 | 476 |
if len(split_path) > 1:
|
| 340 | 477 |
directory_name = split_path[0]
|
| 341 |
- # Hand this off to the importer for that subdir. This will only do one file -
|
|
| 342 |
- # a better way would be to hand off all the files in this subdir at once.
|
|
| 343 |
- subdir_result = self._import_directory_recursively(directory_name, source_directory,
|
|
| 344 |
- split_path[1:], path_prefix)
|
|
| 478 |
+ # Hand this off to the importer for that subdir.
|
|
| 479 |
+ |
|
| 480 |
+ # It would be advantageous to batch these together by
|
|
| 481 |
+ # directory_name. However, we can't do it out of
|
|
| 482 |
+ # order, since importing symlinks affects the results
|
|
| 483 |
+ # of other imports.
|
|
| 484 |
+ subdir_result = _import_directory_recursively(directory_name, source_directory,
|
|
| 485 |
+ split_path[1:], path_prefix)
|
|
| 345 | 486 |
result.combine(subdir_result)
|
| 346 | 487 |
elif os.path.islink(import_file):
|
| 347 | 488 |
if self._check_replacement(entry, path_prefix, result):
|
| 348 |
- self._add_new_link(source_directory, entry)
|
|
| 489 |
+ self._copy_link_from_filesystem(source_directory, entry)
|
|
| 349 | 490 |
result.files_written.append(relative_pathname)
|
| 350 | 491 |
elif os.path.isdir(import_file):
|
| 351 | 492 |
# A plain directory which already exists isn't a problem; just ignore it.
|
| ... | ... | @@ -357,6 +498,93 @@ class CasBasedDirectory(Directory): |
| 357 | 498 |
result.files_written.append(relative_pathname)
|
| 358 | 499 |
return result
|
| 359 | 500 |
|
| 501 |
+ def _files_in_subdir(sorted_files, dirname):
|
|
| 502 |
+ """Filters sorted_files and returns only the ones which have
|
|
| 503 |
+ 'dirname' as a prefix, with that prefix removed.
|
|
| 504 |
+ |
|
| 505 |
+ """
|
|
| 506 |
+ if not dirname.endswith(os.path.sep):
|
|
| 507 |
+ dirname += os.path.sep
|
|
| 508 |
+ return [f[len(dirname):] for f in sorted_files if f.startswith(dirname)]
|
|
| 509 |
+ |
|
| 510 |
+ def _partial_import_cas_into_cas(self, source_directory, files, path_prefix="", file_list_required=True):
|
|
| 511 |
+ """ Import only the files and symlinks listed in 'files' from source_directory to this one.
|
|
| 512 |
+ Args:
|
|
| 513 |
+ source_directory (:class:`.CasBasedDirectory`): The directory to import from
|
|
| 514 |
+ files ([str]): List of pathnames to import.
|
|
| 515 |
+ path_prefix (str): Prefix used to add entries to the file list result.
|
|
| 516 |
+ file_list_required: Whether to update the file list while processing.
|
|
| 517 |
+ """
|
|
| 518 |
+ result = FileListResult()
|
|
| 519 |
+ processed_directories = set()
|
|
| 520 |
+ for f in files:
|
|
| 521 |
+ fullname = os.path.join(path_prefix, f)
|
|
| 522 |
+ components = f.split(os.path.sep)
|
|
| 523 |
+ if len(components) > 1:
|
|
| 524 |
+ # We are importing a thing which is in a subdirectory. We may have already seen this dirname
|
|
| 525 |
+ # for a previous file.
|
|
| 526 |
+ dirname = components[0]
|
|
| 527 |
+ if dirname not in processed_directories:
|
|
| 528 |
+ # Now strip off the first directory name and import files recursively.
|
|
| 529 |
+ subcomponents = CasBasedDirectory._files_in_subdir(files, dirname)
|
|
| 530 |
+ # We will fail at this point if there is a file or symlink to file called 'dirname'.
|
|
| 531 |
+ if dirname in self.index:
|
|
| 532 |
+ resolved_component = self._resolve(dirname, force_create=True)
|
|
| 533 |
+ if isinstance(resolved_component, remote_execution_pb2.FileNode):
|
|
| 534 |
+ self.delete_entry(dirname)
|
|
| 535 |
+ result.overwritten.append(f)
|
|
| 536 |
+ dest_subdir = self.descend(dirname, create=True)
|
|
| 537 |
+ else:
|
|
| 538 |
+ dest_subdir = resolved_component
|
|
| 539 |
+ else:
|
|
| 540 |
+ dest_subdir = self.descend(dirname, create=True)
|
|
| 541 |
+ src_subdir = source_directory.descend(dirname)
|
|
| 542 |
+ import_result = dest_subdir._partial_import_cas_into_cas(src_subdir, subcomponents,
|
|
| 543 |
+ path_prefix=fullname,
|
|
| 544 |
+ file_list_required=file_list_required)
|
|
| 545 |
+ result.combine(import_result)
|
|
| 546 |
+ processed_directories.add(dirname)
|
|
| 547 |
+ elif isinstance(source_directory.index[f].buildstream_object, CasBasedDirectory):
|
|
| 548 |
+ # The thing in the input file list is a directory on
|
|
| 549 |
+ # its own. In which case, replace any existing file,
|
|
| 550 |
+ # or symlink to file with the new, blank directory -
|
|
| 551 |
+ # if it's neither of those things, or doesn't exist,
|
|
| 552 |
+ # then just create the dir.
|
|
| 553 |
+ if f in self.index:
|
|
| 554 |
+ x = self._resolve(f)
|
|
| 555 |
+ if x is None:
|
|
| 556 |
+ # If we're importing a blank directory, and the target has a broken symlink, then do nothing.
|
|
| 557 |
+ pass
|
|
| 558 |
+ elif isinstance(x, remote_execution_pb2.FileNode):
|
|
| 559 |
+ # Files with the same name, or symlinks to files, get removed.
|
|
| 560 |
+ pass
|
|
| 561 |
+ else:
|
|
| 562 |
+ # There's either a symlink (valid or not) or existing directory with this name, so do nothing.
|
|
| 563 |
+ pass
|
|
| 564 |
+ else:
|
|
| 565 |
+ self.descend(f, create=True)
|
|
| 566 |
+ else:
|
|
| 567 |
+ # We're importing a file or symlink - replace anything with the same name.
|
|
| 568 |
+ importable = self._check_replacement(f, path_prefix, result)
|
|
| 569 |
+ if importable:
|
|
| 570 |
+ item = source_directory.index[f].pb_object
|
|
| 571 |
+ if isinstance(item, remote_execution_pb2.FileNode):
|
|
| 572 |
+ filenode = self.pb2_directory.files.add(digest=item.digest, name=f,
|
|
| 573 |
+ is_executable=item.is_executable)
|
|
| 574 |
+ self.index[f] = IndexEntry(filenode, modified=(fullname in result.overwritten))
|
|
| 575 |
+ else:
|
|
| 576 |
+ assert(isinstance(item, remote_execution_pb2.SymlinkNode))
|
|
| 577 |
+ self._add_new_link_direct(name=f, target=item.target)
|
|
| 578 |
+ return result
|
|
| 579 |
+ |
|
| 580 |
+ def _import_cas_into_cas(self, source_directory, files=None):
|
|
| 581 |
+ """ A full import is significantly quicker than a partial import, because we can just
|
|
| 582 |
+ replace one directory with another's hash, without doing any recursion.
|
|
| 583 |
+ """
|
|
| 584 |
+ |
|
| 585 |
+ # You must pass a list into _partial_import (not a generator)
|
|
| 586 |
+ return self._partial_import_cas_into_cas(source_directory, list(files))
|
|
| 587 |
+ |
|
| 360 | 588 |
def import_files(self, external_pathspec, *, files=None,
|
| 361 | 589 |
report_written=True, update_utimes=False,
|
| 362 | 590 |
can_link=False):
|
| ... | ... | @@ -378,28 +606,27 @@ class CasBasedDirectory(Directory): |
| 378 | 606 |
|
| 379 | 607 |
can_link (bool): Ignored, since hard links do not have any meaning within CAS.
|
| 380 | 608 |
"""
|
| 381 |
- if isinstance(external_pathspec, FileBasedDirectory):
|
|
| 382 |
- source_directory = external_pathspec._get_underlying_directory()
|
|
| 383 |
- elif isinstance(external_pathspec, CasBasedDirectory):
|
|
| 384 |
- # TODO: This transfers from one CAS to another via the
|
|
| 385 |
- # filesystem, which is very inefficient. Alter this so it
|
|
| 386 |
- # transfers refs across directly.
|
|
| 387 |
- with tempfile.TemporaryDirectory(prefix="roundtrip") as tmpdir:
|
|
| 388 |
- external_pathspec.export_files(tmpdir)
|
|
| 389 |
- if files is None:
|
|
| 390 |
- files = list_relative_paths(tmpdir)
|
|
| 391 |
- result = self._import_files_from_directory(tmpdir, files=files)
|
|
| 392 |
- return result
|
|
| 393 |
- else:
|
|
| 394 |
- source_directory = external_pathspec
|
|
| 395 | 609 |
|
| 396 | 610 |
if files is None:
|
| 397 |
- files = list_relative_paths(source_directory)
|
|
| 611 |
+ if isinstance(external_pathspec, str):
|
|
| 612 |
+ files = list_relative_paths(external_pathspec)
|
|
| 613 |
+ else:
|
|
| 614 |
+ assert isinstance(external_pathspec, Directory)
|
|
| 615 |
+ files = external_pathspec.list_relative_paths()
|
|
| 616 |
+ |
|
| 617 |
+ if isinstance(external_pathspec, FileBasedDirectory):
|
|
| 618 |
+ source_directory = external_pathspec.get_underlying_directory()
|
|
| 619 |
+ result = self._import_files_from_directory(source_directory, files=files)
|
|
| 620 |
+ elif isinstance(external_pathspec, str):
|
|
| 621 |
+ source_directory = external_pathspec
|
|
| 622 |
+ result = self._import_files_from_directory(source_directory, files=files)
|
|
| 623 |
+ else:
|
|
| 624 |
+ assert isinstance(external_pathspec, CasBasedDirectory)
|
|
| 625 |
+ result = self._import_cas_into_cas(external_pathspec, files=files)
|
|
| 398 | 626 |
|
| 399 | 627 |
# TODO: No notice is taken of report_written, update_utimes or can_link.
|
| 400 | 628 |
# Current behaviour is to fully populate the report, which is inefficient,
|
| 401 | 629 |
# but still correct.
|
| 402 |
- result = self._import_files_from_directory(source_directory, files=files)
|
|
| 403 | 630 |
|
| 404 | 631 |
# We need to recalculate and store the hashes of all directories both
|
| 405 | 632 |
# up and down the tree; we have changed our directory by importing files
|
| ... | ... | @@ -526,7 +753,7 @@ class CasBasedDirectory(Directory): |
| 526 | 753 |
filelist.append(k)
|
| 527 | 754 |
return filelist
|
| 528 | 755 |
|
| 529 |
- def list_relative_paths(self):
|
|
| 756 |
+ def list_relative_paths(self, relpath=""):
|
|
| 530 | 757 |
"""Provide a list of all relative paths.
|
| 531 | 758 |
|
| 532 | 759 |
NOTE: This list is not in the same order as utils.list_relative_paths.
|
| ... | ... | @@ -534,13 +761,32 @@ class CasBasedDirectory(Directory): |
| 534 | 761 |
Return value: List(str) - list of all paths
|
| 535 | 762 |
"""
|
| 536 | 763 |
|
| 537 |
- filelist = []
|
|
| 538 |
- for (k, v) in self.index.items():
|
|
| 539 |
- if isinstance(v.buildstream_object, CasBasedDirectory):
|
|
| 540 |
- filelist.extend([k + os.path.sep + x for x in v.buildstream_object.list_relative_paths()])
|
|
| 541 |
- elif isinstance(v.pb_object, remote_execution_pb2.FileNode):
|
|
| 542 |
- filelist.append(k)
|
|
| 543 |
- return filelist
|
|
| 764 |
+ symlink_list = filter(lambda i: isinstance(i[1].pb_object, remote_execution_pb2.SymlinkNode),
|
|
| 765 |
+ self.index.items())
|
|
| 766 |
+ file_list = list(filter(lambda i: isinstance(i[1].pb_object, remote_execution_pb2.FileNode),
|
|
| 767 |
+ self.index.items()))
|
|
| 768 |
+ directory_list = filter(lambda i: isinstance(i[1].buildstream_object, CasBasedDirectory),
|
|
| 769 |
+ self.index.items())
|
|
| 770 |
+ |
|
| 771 |
+ # We need to mimic the behaviour of os.walk, in which symlinks
|
|
| 772 |
+ # to directories count as directories and symlinks to file or
|
|
| 773 |
+ # broken symlinks count as files. os.walk doesn't follow
|
|
| 774 |
+ # symlinks, so we don't recurse.
|
|
| 775 |
+ for (k, v) in sorted(symlink_list):
|
|
| 776 |
+ target = self._resolve(k, absolute_symlinks_resolve=True)
|
|
| 777 |
+ if isinstance(target, CasBasedDirectory):
|
|
| 778 |
+ yield os.path.join(relpath, k)
|
|
| 779 |
+ else:
|
|
| 780 |
+ file_list.append((k, v))
|
|
| 781 |
+ |
|
| 782 |
+ if file_list == [] and relpath != "":
|
|
| 783 |
+ yield relpath
|
|
| 784 |
+ else:
|
|
| 785 |
+ for (k, v) in sorted(file_list):
|
|
| 786 |
+ yield os.path.join(relpath, k)
|
|
| 787 |
+ |
|
| 788 |
+ for (k, v) in sorted(directory_list):
|
|
| 789 |
+ yield from v.buildstream_object.list_relative_paths(relpath=os.path.join(relpath, k))
|
|
| 544 | 790 |
|
| 545 | 791 |
def recalculate_hash(self):
|
| 546 | 792 |
""" Recalcuates the hash for this directory and store the results in
|
| 1 |
+import os
|
|
| 2 |
+import pytest
|
|
| 3 |
+import random
|
|
| 4 |
+import copy
|
|
| 5 |
+import tempfile
|
|
| 6 |
+from tests.testutils import cli
|
|
| 7 |
+ |
|
| 8 |
+ |
|
| 9 |
+from buildstream.storage._casbaseddirectory import CasBasedDirectory
|
|
| 10 |
+from buildstream.storage._filebaseddirectory import FileBasedDirectory
|
|
| 11 |
+from buildstream._artifactcache import ArtifactCache
|
|
| 12 |
+from buildstream._artifactcache.cascache import CASCache
|
|
| 13 |
+from buildstream import utils
|
|
| 14 |
+ |
|
| 15 |
+ |
|
| 16 |
+class FakeContext():
|
|
| 17 |
+ def __init__(self):
|
|
| 18 |
+ self.config_cache_quota = "65536"
|
|
| 19 |
+ |
|
| 20 |
+ def get_projects(self):
|
|
| 21 |
+ return []
|
|
| 22 |
+ |
|
| 23 |
+# This is a set of example file system contents. The test attempts to import
|
|
| 24 |
+# each on top of each other to test importing works consistently.
|
|
| 25 |
+# Each tuple is defined as (<filename>, <type>, <content>). Type can be
|
|
| 26 |
+# 'F' (file), 'S' (symlink) or 'D' (directory) with content being the contents
|
|
| 27 |
+# for a file or the destination for a symlink.
|
|
| 28 |
+root_filesets = [
|
|
| 29 |
+ # Arbitrary test sets
|
|
| 30 |
+ [('a/b/c/textfile1', 'F', 'This is textfile 1\n')],
|
|
| 31 |
+ [('a/b/c/textfile1', 'F', 'This is the replacement textfile 1\n')],
|
|
| 32 |
+ [('a/b/d', 'D', '')],
|
|
| 33 |
+ [('a/b/c', 'S', '/a/b/d')],
|
|
| 34 |
+ [('a/b/d', 'S', '/a/b/c')],
|
|
| 35 |
+ [('a/b/d', 'D', ''), ('a/b/c', 'S', '/a/b/d')],
|
|
| 36 |
+ [('a/b/c', 'D', ''), ('a/b/d', 'S', '/a/b/c')],
|
|
| 37 |
+ [('a/b', 'F', 'This is textfile 1\n')],
|
|
| 38 |
+ [('a/b/c', 'F', 'This is textfile 1\n')],
|
|
| 39 |
+ [('a/b/c', 'D', '')]
|
|
| 40 |
+]
|
|
| 41 |
+ |
|
| 42 |
+empty_hash_ref = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
|
| 43 |
+RANDOM_SEED = 69105
|
|
| 44 |
+ |
|
| 45 |
+ |
|
| 46 |
+def generate_import_roots(rootno, directory):
|
|
| 47 |
+ rootname = "root{}".format(rootno)
|
|
| 48 |
+ rootdir = os.path.join(directory, "content", rootname)
|
|
| 49 |
+ |
|
| 50 |
+ for (path, typesymbol, content) in root_filesets[rootno - 1]:
|
|
| 51 |
+ if typesymbol == 'F':
|
|
| 52 |
+ (dirnames, filename) = os.path.split(path)
|
|
| 53 |
+ os.makedirs(os.path.join(rootdir, dirnames), exist_ok=True)
|
|
| 54 |
+ with open(os.path.join(rootdir, dirnames, filename), "wt") as f:
|
|
| 55 |
+ f.write(content)
|
|
| 56 |
+ elif typesymbol == 'D':
|
|
| 57 |
+ os.makedirs(os.path.join(rootdir, path), exist_ok=True)
|
|
| 58 |
+ elif typesymbol == 'S':
|
|
| 59 |
+ (dirnames, filename) = os.path.split(path)
|
|
| 60 |
+ os.makedirs(os.path.join(rootdir, dirnames), exist_ok=True)
|
|
| 61 |
+ os.symlink(content, os.path.join(rootdir, path))
|
|
| 62 |
+ |
|
| 63 |
+ |
|
| 64 |
+def generate_random_root(rootno, directory):
|
|
| 65 |
+ random.seed(RANDOM_SEED + rootno)
|
|
| 66 |
+ rootname = "root{}".format(rootno)
|
|
| 67 |
+ rootdir = os.path.join(directory, "content", rootname)
|
|
| 68 |
+ things = []
|
|
| 69 |
+ locations = ['.']
|
|
| 70 |
+ os.makedirs(rootdir)
|
|
| 71 |
+ for i in range(0, 100):
|
|
| 72 |
+ location = random.choice(locations)
|
|
| 73 |
+ thingname = "node{}".format(i)
|
|
| 74 |
+ thing = random.choice(['dir', 'link', 'file'])
|
|
| 75 |
+ target = os.path.join(rootdir, location, thingname)
|
|
| 76 |
+ description = thing
|
|
| 77 |
+ if thing == 'dir':
|
|
| 78 |
+ os.makedirs(target)
|
|
| 79 |
+ locations.append(os.path.join(location, thingname))
|
|
| 80 |
+ elif thing == 'file':
|
|
| 81 |
+ with open(target, "wt") as f:
|
|
| 82 |
+ f.write("This is node {}\n".format(i))
|
|
| 83 |
+ elif thing == 'link':
|
|
| 84 |
+ # TODO: Make some relative symlinks
|
|
| 85 |
+ if random.randint(1, 3) == 1 or len(things) == 0:
|
|
| 86 |
+ os.symlink("/broken", target)
|
|
| 87 |
+ description = "symlink pointing to /broken"
|
|
| 88 |
+ else:
|
|
| 89 |
+ symlink_destination = random.choice(things)
|
|
| 90 |
+ os.symlink(symlink_destination, target)
|
|
| 91 |
+ description = "symlink pointing to {}".format(symlink_destination)
|
|
| 92 |
+ things.append(os.path.join(location, thingname))
|
|
| 93 |
+ |
|
| 94 |
+ |
|
| 95 |
+def file_contents(path):
|
|
| 96 |
+ with open(path, "r") as f:
|
|
| 97 |
+ result = f.read()
|
|
| 98 |
+ return result
|
|
| 99 |
+ |
|
| 100 |
+ |
|
| 101 |
+def file_contents_are(path, contents):
|
|
| 102 |
+ return file_contents(path) == contents
|
|
| 103 |
+ |
|
| 104 |
+ |
|
| 105 |
+def create_new_casdir(root_number, fake_context, tmpdir):
|
|
| 106 |
+ d = CasBasedDirectory(fake_context)
|
|
| 107 |
+ d.import_files(os.path.join(tmpdir, "content", "root{}".format(root_number)))
|
|
| 108 |
+ assert d.ref.hash != empty_hash_ref
|
|
| 109 |
+ return d
|
|
| 110 |
+ |
|
| 111 |
+ |
|
| 112 |
+def create_new_filedir(root_number, tmpdir):
|
|
| 113 |
+ root = os.path.join(tmpdir, "vdir")
|
|
| 114 |
+ os.makedirs(root)
|
|
| 115 |
+ d = FileBasedDirectory(root)
|
|
| 116 |
+ d.import_files(os.path.join(tmpdir, "content", "root{}".format(root_number)))
|
|
| 117 |
+ return d
|
|
| 118 |
+ |
|
| 119 |
+ |
|
| 120 |
+def combinations(integer_range):
|
|
| 121 |
+ for x in integer_range:
|
|
| 122 |
+ for y in integer_range:
|
|
| 123 |
+ yield (x, y)
|
|
| 124 |
+ |
|
| 125 |
+ |
|
| 126 |
+def resolve_symlinks(path, root):
|
|
| 127 |
+ """ A function to resolve symlinks inside 'path' components apart from the last one.
|
|
| 128 |
+ For example, resolve_symlinks('/a/b/c/d', '/a/b')
|
|
| 129 |
+ will return '/a/b/f/d' if /a/b/c is a symlink to /a/b/f. The final component of
|
|
| 130 |
+ 'path' is not resolved, because we typically want to inspect the symlink found
|
|
| 131 |
+ at that path, not its target.
|
|
| 132 |
+ |
|
| 133 |
+ """
|
|
| 134 |
+ components = path.split(os.path.sep)
|
|
| 135 |
+ location = root
|
|
| 136 |
+ for i in range(0, len(components) - 1):
|
|
| 137 |
+ location = os.path.join(location, components[i])
|
|
| 138 |
+ if os.path.islink(location):
|
|
| 139 |
+ # Resolve the link, add on all the remaining components
|
|
| 140 |
+ target = os.path.join(os.readlink(location))
|
|
| 141 |
+ tail = os.path.sep.join(components[i + 1:])
|
|
| 142 |
+ |
|
| 143 |
+ if target.startswith(os.path.sep):
|
|
| 144 |
+ # Absolute link - relative to root
|
|
| 145 |
+ location = os.path.join(root, target, tail)
|
|
| 146 |
+ else:
|
|
| 147 |
+ # Relative link - relative to symlink location
|
|
| 148 |
+ location = os.path.join(location, target)
|
|
| 149 |
+ return resolve_symlinks(location, root)
|
|
| 150 |
+ # If we got here, no symlinks were found. Add on the final component and return.
|
|
| 151 |
+ location = os.path.join(location, components[-1])
|
|
| 152 |
+ return location
|
|
| 153 |
+ |
|
| 154 |
+ |
|
| 155 |
+def directory_not_empty(path):
|
|
| 156 |
+ return os.listdir(path)
|
|
| 157 |
+ |
|
| 158 |
+ |
|
| 159 |
+def _import_test(tmpdir, original, overlay, generator_function, verify_contents=False):
|
|
| 160 |
+ fake_context = FakeContext()
|
|
| 161 |
+ fake_context.artifactdir = tmpdir
|
|
| 162 |
+ print("Creating CAS Cache with artifact dir {}".format(tmpdir))
|
|
| 163 |
+ fake_context.artifactcache = CASCache(fake_context)
|
|
| 164 |
+ # Create some fake content
|
|
| 165 |
+ generator_function(original, tmpdir)
|
|
| 166 |
+ if original != overlay:
|
|
| 167 |
+ generator_function(overlay, tmpdir)
|
|
| 168 |
+ |
|
| 169 |
+ d = create_new_casdir(original, fake_context, tmpdir)
|
|
| 170 |
+ |
|
| 171 |
+ duplicate_cas = create_new_casdir(original, fake_context, tmpdir)
|
|
| 172 |
+ |
|
| 173 |
+ assert duplicate_cas.ref.hash == d.ref.hash
|
|
| 174 |
+ |
|
| 175 |
+ d2 = create_new_casdir(overlay, fake_context, tmpdir)
|
|
| 176 |
+ print("Importing dir {} into {}".format(overlay, original))
|
|
| 177 |
+ d.import_files(d2)
|
|
| 178 |
+ export_dir = os.path.join(tmpdir, "output")
|
|
| 179 |
+ roundtrip_dir = os.path.join(tmpdir, "roundtrip")
|
|
| 180 |
+ d2.export_files(roundtrip_dir)
|
|
| 181 |
+ d.export_files(export_dir)
|
|
| 182 |
+ |
|
| 183 |
+ if verify_contents:
|
|
| 184 |
+ for item in root_filesets[overlay - 1]:
|
|
| 185 |
+ (path, typename, content) = item
|
|
| 186 |
+ realpath = resolve_symlinks(path, export_dir)
|
|
| 187 |
+ if typename == 'F':
|
|
| 188 |
+ if os.path.isdir(realpath) and directory_not_empty(realpath):
|
|
| 189 |
+ # The file should not have overwritten the directory in this case.
|
|
| 190 |
+ pass
|
|
| 191 |
+ else:
|
|
| 192 |
+ assert os.path.isfile(realpath), "{} did not exist in the combined virtual directory".format(path)
|
|
| 193 |
+ assert file_contents_are(realpath, content)
|
|
| 194 |
+ elif typename == 'S':
|
|
| 195 |
+ if os.path.isdir(realpath) and directory_not_empty(realpath):
|
|
| 196 |
+ # The symlink should not have overwritten the directory in this case.
|
|
| 197 |
+ pass
|
|
| 198 |
+ else:
|
|
| 199 |
+ assert os.path.islink(realpath)
|
|
| 200 |
+ assert os.readlink(realpath) == content
|
|
| 201 |
+ elif typename == 'D':
|
|
| 202 |
+ # We can't do any more tests than this because it
|
|
| 203 |
+ # depends on things present in the original. Blank
|
|
| 204 |
+ # directories here will be ignored and the original
|
|
| 205 |
+ # left in place.
|
|
| 206 |
+ assert os.path.lexists(realpath)
|
|
| 207 |
+ |
|
| 208 |
+ # Now do the same thing with filebaseddirectories and check the contents match
|
|
| 209 |
+ |
|
| 210 |
+ files = list(utils.list_relative_paths(roundtrip_dir))
|
|
| 211 |
+ print("Importing from filesystem: filelist is: {}".format(files))
|
|
| 212 |
+ duplicate_cas._import_files_from_directory(roundtrip_dir, files=files)
|
|
| 213 |
+ duplicate_cas._recalculate_recursing_down()
|
|
| 214 |
+ if duplicate_cas.parent:
|
|
| 215 |
+ duplicate_cas.parent._recalculate_recursing_up(duplicate_cas)
|
|
| 216 |
+ print("Result of direct import: {}".format(duplicate_cas.show_files_recursive()))
|
|
| 217 |
+ |
|
| 218 |
+ assert duplicate_cas.ref.hash == d.ref.hash
|
|
| 219 |
+ |
|
| 220 |
+ |
|
| 221 |
+@pytest.mark.parametrize("original,overlay", combinations(range(1, len(root_filesets) + 1)))
|
|
| 222 |
+def test_fixed_cas_import(cli, tmpdir, original, overlay):
|
|
| 223 |
+ _import_test(tmpdir, original, overlay, generate_import_roots, verify_contents=True)
|
|
| 224 |
+ |
|
| 225 |
+ |
|
| 226 |
+@pytest.mark.parametrize("original,overlay", combinations(range(1, 11)))
|
|
| 227 |
+def test_random_cas_import_fast(cli, tmpdir, original, overlay):
|
|
| 228 |
+ _import_test(tmpdir, original, overlay, generate_random_root, verify_contents=False)
|
|
| 229 |
+ |
|
| 230 |
+ |
|
| 231 |
+def _listing_test(tmpdir, root, generator_function):
|
|
| 232 |
+ fake_context = FakeContext()
|
|
| 233 |
+ fake_context.artifactdir = tmpdir
|
|
| 234 |
+ print("Creating CAS Cache with artifact dir {}".format(tmpdir))
|
|
| 235 |
+ fake_context.artifactcache = CASCache(fake_context)
|
|
| 236 |
+ # Create some fake content
|
|
| 237 |
+ generator_function(root, tmpdir)
|
|
| 238 |
+ |
|
| 239 |
+ d = create_new_filedir(root, tmpdir)
|
|
| 240 |
+ filelist = list(d.list_relative_paths())
|
|
| 241 |
+ |
|
| 242 |
+ d2 = create_new_casdir(root, fake_context, tmpdir)
|
|
| 243 |
+ filelist2 = list(d2.list_relative_paths())
|
|
| 244 |
+ |
|
| 245 |
+ print("filelist for root {} via FileBasedDirectory:".format(root))
|
|
| 246 |
+ print("{}".format(filelist))
|
|
| 247 |
+ print("filelist for root {} via CasBasedDirectory:".format(root))
|
|
| 248 |
+ print("{}".format(filelist2))
|
|
| 249 |
+ assert filelist == filelist2
|
|
| 250 |
+ |
|
| 251 |
+ |
|
| 252 |
+@pytest.mark.parametrize("root", range(1, 11))
|
|
| 253 |
+def test_random_directory_listing(cli, tmpdir, root):
|
|
| 254 |
+ _listing_test(tmpdir, root, generate_random_root)
|
|
| 255 |
+ |
|
| 256 |
+ |
|
| 257 |
+@pytest.mark.parametrize("root", [1, 2, 3, 4, 5])
|
|
| 258 |
+def test_fixed_directory_listing(cli, tmpdir, root):
|
|
| 259 |
+ _listing_test(tmpdir, root, generate_import_roots)
|
|
| 260 |
+ |
|
| 261 |
+ |
|
| 262 |
+def main():
|
|
| 263 |
+ for i in range(1, 6):
|
|
| 264 |
+ with tempfile.TemporaryDirectory(prefix="/home/jimmacarthur/.cache/buildstream/cas") as tmpdirname:
|
|
| 265 |
+ test_fixed_directory_listing(None, tmpdirname, i)
|
|
| 266 |
+ |
|
| 267 |
+ for i in range(1, 11):
|
|
| 268 |
+ with tempfile.TemporaryDirectory(prefix="/home/jimmacarthur/.cache/buildstream/cas") as tmpdirname:
|
|
| 269 |
+ test_random_directory_listing(None, tmpdirname, i)
|
|
| 270 |
+ |
|
| 271 |
+ for i in range(1, 21):
|
|
| 272 |
+ for j in range(1, 21):
|
|
| 273 |
+ with tempfile.TemporaryDirectory(prefix="/home/jimmacarthur/.cache/buildstream/cas") as tmpdirname:
|
|
| 274 |
+ test_random_cas_import_fast(None, tmpdirname, i, j)
|
|
| 275 |
+ |
|
| 276 |
+ for i in range(1, len(root_filesets) + 1):
|
|
| 277 |
+ for j in range(1, len(root_filesets) + 1):
|
|
| 278 |
+ with tempfile.TemporaryDirectory(prefix="/home/jimmacarthur/.cache/buildstream/cas") as tmpdirname:
|
|
| 279 |
+ test_fixed_cas_import(None, tmpdirname, i, j)
|
|
| 280 |
+ |
|
| 281 |
+ |
|
| 282 |
+if __name__ == "__main__":
|
|
| 283 |
+ main()
|
