[Notes] [Git][BuildStream/buildstream][jmac/cas_to_cas_v2] 11 commits: _sandboxremote.py: Use the standard SandboxError.



Title: GitLab

Jim MacArthur pushed to branch jmac/cas_to_cas_v2 at BuildStream / buildstream

Commits:

7 changed files:

Changes:

  • buildstream/element.py
    ... ... @@ -1410,16 +1410,9 @@ class Element(Plugin):
    1410 1410
     
    
    1411 1411
                 finally:
    
    1412 1412
                     # Staging may produce directories with less than 'rwx' permissions
    
    1413
    -                # for the owner, which will break tempfile, so we need to use chmod
    
    1414
    -                # occasionally.
    
    1415
    -                def make_dir_writable(fn, path, excinfo):
    
    1416
    -                    os.chmod(os.path.dirname(path), 0o777)
    
    1417
    -                    if os.path.isdir(path):
    
    1418
    -                        os.rmdir(path)
    
    1419
    -                    else:
    
    1420
    -                        os.remove(path)
    
    1421
    -                shutil.rmtree(temp_staging_directory, onerror=make_dir_writable)
    
    1422
    -
    
    1413
    +                # for the owner, which breaks tempfile. _force_rmtree will deal
    
    1414
    +                # with these.
    
    1415
    +                utils._force_rmtree(temp_staging_directory)
    
    1423 1416
             # Ensure deterministic mtime of sources at build time
    
    1424 1417
             vdirectory.set_deterministic_mtime()
    
    1425 1418
             # Ensure deterministic owners of sources at build time
    

  • buildstream/sandbox/_sandboxremote.py
    ... ... @@ -28,10 +28,7 @@ from ..storage._filebaseddirectory import FileBasedDirectory
    28 28
     from ..storage._casbaseddirectory import CasBasedDirectory
    
    29 29
     from .._protos.build.bazel.remote.execution.v2 import remote_execution_pb2, remote_execution_pb2_grpc
    
    30 30
     from .._protos.google.rpc import code_pb2
    
    31
    -
    
    32
    -
    
    33
    -class SandboxError(Exception):
    
    34
    -    pass
    
    31
    +from .._exceptions import SandboxError
    
    35 32
     
    
    36 33
     
    
    37 34
     # SandboxRemote()
    

  • buildstream/storage/_casbaseddirectory.py
    ... ... @@ -30,7 +30,6 @@ See also: :ref:`sandboxing`.
    30 30
     from collections import OrderedDict
    
    31 31
     
    
    32 32
     import os
    
    33
    -import tempfile
    
    34 33
     import stat
    
    35 34
     
    
    36 35
     from .._protos.build.bazel.remote.execution.v2 import remote_execution_pb2
    
    ... ... @@ -51,6 +50,162 @@ class IndexEntry():
    51 50
             self.modified = modified
    
    52 51
     
    
    53 52
     
    
    53
    +class ResolutionException(VirtualDirectoryError):
    
    54
    +    """ Superclass of all exceptions that can be raised by
    
    55
    +    CasBasedDirectory._resolve. Should not be used outside this module. """
    
    56
    +    pass
    
    57
    +
    
    58
    +
    
    59
    +class InfiniteSymlinkException(ResolutionException):
    
    60
    +    """ Raised when an infinite symlink loop is found. """
    
    61
    +    pass
    
    62
    +
    
    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
    +
    
    70
    +
    
    71
    +class _Resolver():
    
    72
    +    """A class for resolving symlinks inside CAS-based directories. As
    
    73
    +    well as providing a namespace for some functions, this also
    
    74
    +    contains two flags which are constant throughout one resolution
    
    75
    +    operation and the 'seen_objects' list used to detect infinite
    
    76
    +    symlink loops.
    
    77
    +
    
    78
    +    """
    
    79
    +
    
    80
    +    def __init__(self, absolute_symlinks_resolve=True, force_create=False):
    
    81
    +        self.absolute_symlinks_resolve = absolute_symlinks_resolve
    
    82
    +        self.force_create = force_create
    
    83
    +        self.seen_objects = []
    
    84
    +
    
    85
    +    def resolve(self, name, directory):
    
    86
    +        """Resolves any name to an object. If the name points to a symlink in
    
    87
    +        the directory, it returns the thing it points to,
    
    88
    +        recursively.
    
    89
    +
    
    90
    +        Returns a CasBasedDirectory, FileNode or None. None indicates
    
    91
    +        either that 'target' does not exist in this directory, or is a
    
    92
    +        symlink chain which points to a nonexistent name (broken
    
    93
    +        symlink).
    
    94
    +
    
    95
    +        Raises:
    
    96
    +        - InfiniteSymlinkException if 'name' points to an infinite symlink loop.
    
    97
    +        - AbsoluteSymlinkException if 'name' points to an absolute symlink and absolute_symlinks_resolve is False.
    
    98
    +
    
    99
    +        If force_create is set, this will attempt to create directories to make symlinks and directories resolve.
    
    100
    +        Files present in symlink target paths will also be removed and replaced with directories.
    
    101
    +        If force_create is off, this will never alter 'directory'.
    
    102
    +
    
    103
    +        """
    
    104
    +
    
    105
    +        # First check for nonexistent things or 'normal' objects and return them
    
    106
    +        if name not in directory.index:
    
    107
    +            return None
    
    108
    +        index_entry = directory.index[name]
    
    109
    +        if isinstance(index_entry.buildstream_object, Directory):
    
    110
    +            return index_entry.buildstream_object
    
    111
    +        elif isinstance(index_entry.pb_object, remote_execution_pb2.FileNode):
    
    112
    +            return index_entry.pb_object
    
    113
    +
    
    114
    +        # Now we must be dealing with a symlink.
    
    115
    +        assert isinstance(index_entry.pb_object, remote_execution_pb2.SymlinkNode)
    
    116
    +
    
    117
    +        symlink_object = index_entry.pb_object
    
    118
    +        if symlink_object in self.seen_objects:
    
    119
    +            # Infinite symlink loop detected
    
    120
    +            message = ("Infinite symlink loop found during resolution. " +
    
    121
    +                       "First repeated element is {}".format(name))
    
    122
    +            raise InfiniteSymlinkException(message=message)
    
    123
    +
    
    124
    +        self.seen_objects.append(symlink_object)
    
    125
    +
    
    126
    +        components = symlink_object.target.split(CasBasedDirectory._pb2_path_sep)
    
    127
    +        absolute = symlink_object.target.startswith(CasBasedDirectory._pb2_absolute_path_prefix)
    
    128
    +
    
    129
    +        if absolute:
    
    130
    +            if self.absolute_symlinks_resolve:
    
    131
    +                directory = directory.find_root()
    
    132
    +                # Discard the first empty element
    
    133
    +                components.pop(0)
    
    134
    +            else:
    
    135
    +                # Unresolvable absolute symlink
    
    136
    +                message = "{} is an absolute symlink, which was disallowed during resolution".format(name)
    
    137
    +                raise AbsoluteSymlinkException(message=message)
    
    138
    +
    
    139
    +        resolution = directory
    
    140
    +        while components and isinstance(resolution, CasBasedDirectory):
    
    141
    +            c = components.pop(0)
    
    142
    +            directory = resolution
    
    143
    +
    
    144
    +            try:
    
    145
    +                resolution = self._resolve_path_component(c, directory, components)
    
    146
    +            except ResolutionException as original:
    
    147
    +                errormsg = ("Reached a file called {} while trying to resolve a symlink; " +
    
    148
    +                            "cannot proceed. The remaining path components are {}.")
    
    149
    +                raise ResolutionException(errormsg.format(c, components)) from original
    
    150
    +
    
    151
    +        return resolution
    
    152
    +
    
    153
    +    def _resolve_path_component(self, c, directory, components_remaining):
    
    154
    +        if c == ".":
    
    155
    +            resolution = directory
    
    156
    +        elif c == "..":
    
    157
    +            if directory.parent is not None:
    
    158
    +                resolution = directory.parent
    
    159
    +            else:
    
    160
    +                # If directory.parent *is* None, this is an attempt to
    
    161
    +                # access '..' from the root, which is valid under
    
    162
    +                # POSIX; it just returns the root.
    
    163
    +                resolution = directory
    
    164
    +        elif c in directory.index:
    
    165
    +            try:
    
    166
    +                resolution = self._resolve_through_files(c, directory, components_remaining)
    
    167
    +            except ResolutionException as original:
    
    168
    +                errormsg = ("Reached a file called {} while trying to resolve a symlink; " +
    
    169
    +                            "cannot proceed. The remaining path components are {}.")
    
    170
    +                raise ResolutionException(errormsg.format(c, components_remaining)) from original
    
    171
    +        else:
    
    172
    +            # c is not in our index
    
    173
    +            if self.force_create:
    
    174
    +                resolution = directory.descend(c, create=True)
    
    175
    +            else:
    
    176
    +                resolution = None
    
    177
    +        return resolution
    
    178
    +
    
    179
    +    def _resolve_through_files(self, c, directory, require_traversable):
    
    180
    +        """A wrapper to resolve() which deals with files being found
    
    181
    +        in the middle of paths, for example trying to resolve a symlink
    
    182
    +        which points to /usr/lib64/libfoo when 'lib64' is a file.
    
    183
    +
    
    184
    +        require_traversable: If this is True, never return a file
    
    185
    +        node.  Instead, if force_create is set, destroy the file node,
    
    186
    +        then create and return a normal directory in its place. If
    
    187
    +        force_create is off, throws ResolutionException.
    
    188
    +
    
    189
    +        """
    
    190
    +        resolved_thing = self.resolve(c, directory)
    
    191
    +
    
    192
    +        if isinstance(resolved_thing, remote_execution_pb2.FileNode):
    
    193
    +            if require_traversable:
    
    194
    +                # We have components still to resolve, but one of the path components
    
    195
    +                # is a file.
    
    196
    +                if self.force_create:
    
    197
    +                    directory.delete_entry(c)
    
    198
    +                    resolved_thing = directory.descend(c, create=True)
    
    199
    +                else:
    
    200
    +                    # This is a signal that we hit a file, but don't
    
    201
    +                    # have the data to give a proper message, so the
    
    202
    +                    # caller should reraise this with a proper
    
    203
    +                    # description.
    
    204
    +                    raise ResolutionException(message="")
    
    205
    +
    
    206
    +        return resolved_thing
    
    207
    +
    
    208
    +
    
    54 209
     # CasBasedDirectory intentionally doesn't call its superclass constuctor,
    
    55 210
     # which is meant to be unimplemented.
    
    56 211
     # pylint: disable=super-init-not-called
    
    ... ... @@ -168,29 +323,34 @@ class CasBasedDirectory(Directory):
    168 323
             self.index[name] = IndexEntry(dirnode, buildstream_object=newdir)
    
    169 324
             return newdir
    
    170 325
     
    
    171
    -    def _add_new_file(self, basename, filename):
    
    326
    +    def _add_file(self, basename, filename, modified=False):
    
    172 327
             filenode = self.pb2_directory.files.add()
    
    173 328
             filenode.name = filename
    
    174 329
             self.cas_cache.add_object(digest=filenode.digest, path=os.path.join(basename, filename))
    
    175 330
             is_executable = os.access(os.path.join(basename, filename), os.X_OK)
    
    176 331
             filenode.is_executable = is_executable
    
    177
    -        self.index[filename] = IndexEntry(filenode, modified=(filename in self.index))
    
    332
    +        self.index[filename] = IndexEntry(filenode, modified=modified or filename in self.index)
    
    178 333
     
    
    179
    -    def _add_new_link(self, basename, filename):
    
    180
    -        existing_link = self._find_pb2_entry(filename)
    
    334
    +    def _copy_link_from_filesystem(self, basename, filename):
    
    335
    +        self._add_new_link_direct(filename, os.readlink(os.path.join(basename, filename)))
    
    336
    +
    
    337
    +    def _add_new_link_direct(self, name, target):
    
    338
    +        existing_link = self._find_pb2_entry(name)
    
    181 339
             if existing_link:
    
    182 340
                 symlinknode = existing_link
    
    183 341
             else:
    
    184 342
                 symlinknode = self.pb2_directory.symlinks.add()
    
    185
    -        symlinknode.name = filename
    
    343
    +        assert isinstance(symlinknode, remote_execution_pb2.SymlinkNode)
    
    344
    +        symlinknode.name = name
    
    186 345
             # 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))
    
    346
    +        symlinknode.target = target
    
    347
    +        self.index[name] = IndexEntry(symlinknode, modified=(existing_link is not None))
    
    189 348
     
    
    190 349
         def delete_entry(self, name):
    
    191 350
             for collection in [self.pb2_directory.files, self.pb2_directory.symlinks, self.pb2_directory.directories]:
    
    192
    -            if name in collection:
    
    193
    -                collection.remove(name)
    
    351
    +            for thing in collection:
    
    352
    +                if thing.name == name:
    
    353
    +                    collection.remove(thing)
    
    194 354
             if name in self.index:
    
    195 355
                 del self.index[name]
    
    196 356
     
    
    ... ... @@ -231,9 +391,13 @@ class CasBasedDirectory(Directory):
    231 391
                 if isinstance(entry, CasBasedDirectory):
    
    232 392
                     return entry.descend(subdirectory_spec[1:], create)
    
    233 393
                 else:
    
    394
    +                # May be a symlink
    
    395
    +                target = self._resolve(subdirectory_spec[0], force_create=create)
    
    396
    +                if isinstance(target, CasBasedDirectory):
    
    397
    +                    return target
    
    234 398
                     error = "Cannot descend into {}, which is a '{}' in the directory {}"
    
    235 399
                     raise VirtualDirectoryError(error.format(subdirectory_spec[0],
    
    236
    -                                                         type(entry).__name__,
    
    400
    +                                                         type(self.index[subdirectory_spec[0]].pb_object).__name__,
    
    237 401
                                                              self))
    
    238 402
             else:
    
    239 403
                 if create:
    
    ... ... @@ -254,36 +418,9 @@ class CasBasedDirectory(Directory):
    254 418
             else:
    
    255 419
                 return self
    
    256 420
     
    
    257
    -    def _resolve_symlink_or_directory(self, name):
    
    258
    -        """Used only by _import_files_from_directory. Tries to resolve a
    
    259
    -        directory name or symlink name. 'name' must be an entry in this
    
    260
    -        directory. It must be a single symlink or directory name, not a path
    
    261
    -        separated by path separators. If it's an existing directory name, it
    
    262
    -        just returns the Directory object for that. If it's a symlink, it will
    
    263
    -        attempt to find the target of the symlink and return that as a
    
    264
    -        Directory object.
    
    265
    -
    
    266
    -        If a symlink target doesn't exist, it will attempt to create it
    
    267
    -        as a directory as long as it's within this directory tree.
    
    268
    -        """
    
    269
    -
    
    270
    -        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)
    
    274
    -        absolute = symlink.target.startswith(CasBasedDirectory._pb2_absolute_path_prefix)
    
    275
    -        if absolute:
    
    276
    -            root = self.find_root()
    
    277
    -        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
    
    284
    -            else:
    
    285
    -                directory = directory.descend(c, create=True)
    
    286
    -        return directory
    
    421
    +    def _resolve(self, name, absolute_symlinks_resolve=True, force_create=False):
    
    422
    +        resolver = _Resolver(absolute_symlinks_resolve, force_create)
    
    423
    +        return resolver.resolve(name, self)
    
    287 424
     
    
    288 425
         def _check_replacement(self, name, path_prefix, fileListResult):
    
    289 426
             """ Checks whether 'name' exists, and if so, whether we can overwrite it.
    
    ... ... @@ -297,6 +434,7 @@ class CasBasedDirectory(Directory):
    297 434
                 return True
    
    298 435
             if (isinstance(existing_entry,
    
    299 436
                            (remote_execution_pb2.FileNode, remote_execution_pb2.SymlinkNode))):
    
    437
    +            self.delete_entry(name)
    
    300 438
                 fileListResult.overwritten.append(relative_pathname)
    
    301 439
                 return True
    
    302 440
             elif isinstance(existing_entry, remote_execution_pb2.DirectoryNode):
    
    ... ... @@ -314,23 +452,44 @@ class CasBasedDirectory(Directory):
    314 452
                            .format(name, type(existing_entry)))
    
    315 453
             return False  # In case asserts are disabled
    
    316 454
     
    
    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
    
    455
    +    def _replace_anything_with_dir(self, name, path_prefix, overwritten_files_list):
    
    456
    +        self.delete_entry(name)
    
    457
    +        subdir = self._add_directory(name)
    
    458
    +        overwritten_files_list.append(os.path.join(path_prefix, name))
    
    459
    +        return subdir
    
    329 460
     
    
    330 461
         def _import_files_from_directory(self, source_directory, files, path_prefix=""):
    
    331
    -        """ Imports files from a traditional directory """
    
    462
    +        """ Imports files from a traditional directory. """
    
    463
    +
    
    464
    +        def _ensure_followable(name, path_prefix):
    
    465
    +            """ Makes sure 'name' is a directory or symlink to a directory which can be descended into. """
    
    466
    +            if isinstance(self.index[name].buildstream_object, Directory):
    
    467
    +                return self.descend(name)
    
    468
    +            try:
    
    469
    +                target = self._resolve(name, force_create=True)
    
    470
    +            except InfiniteSymlinkException:
    
    471
    +                return self._replace_anything_with_dir(name, path_prefix, result.overwritten)
    
    472
    +            if isinstance(target, CasBasedDirectory):
    
    473
    +                return target
    
    474
    +            elif isinstance(target, remote_execution_pb2.FileNode):
    
    475
    +                return self._replace_anything_with_dir(name, path_prefix, result.overwritten)
    
    476
    +            return target
    
    477
    +
    
    478
    +        def _import_directory_recursively(directory_name, source_directory, remaining_path, path_prefix):
    
    479
    +            """ _import_directory_recursively and _import_files_from_directory will be called alternately
    
    480
    +            as a directory tree is descended. """
    
    481
    +            if directory_name in self.index:
    
    482
    +                subdir = _ensure_followable(directory_name, path_prefix)
    
    483
    +            else:
    
    484
    +                subdir = self._add_directory(directory_name)
    
    485
    +            new_path_prefix = os.path.join(path_prefix, directory_name)
    
    486
    +            subdir_result = subdir._import_files_from_directory(os.path.join(source_directory, directory_name),
    
    487
    +                                                                [os.path.sep.join(remaining_path)],
    
    488
    +                                                                path_prefix=new_path_prefix)
    
    489
    +            return subdir_result
    
    490
    +
    
    332 491
             result = FileListResult()
    
    333
    -        for entry in sorted(files):
    
    492
    +        for entry in files:
    
    334 493
                 split_path = entry.split(os.path.sep)
    
    335 494
                 # The actual file on the FS we're importing
    
    336 495
                 import_file = os.path.join(source_directory, entry)
    
    ... ... @@ -338,14 +497,18 @@ class CasBasedDirectory(Directory):
    338 497
                 relative_pathname = os.path.join(path_prefix, entry)
    
    339 498
                 if len(split_path) > 1:
    
    340 499
                     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)
    
    500
    +                # Hand this off to the importer for that subdir.
    
    501
    +
    
    502
    +                # It would be advantageous to batch these together by
    
    503
    +                # directory_name. However, we can't do it out of
    
    504
    +                # order, since importing symlinks affects the results
    
    505
    +                # of other imports.
    
    506
    +                subdir_result = _import_directory_recursively(directory_name, source_directory,
    
    507
    +                                                              split_path[1:], path_prefix)
    
    345 508
                     result.combine(subdir_result)
    
    346 509
                 elif os.path.islink(import_file):
    
    347 510
                     if self._check_replacement(entry, path_prefix, result):
    
    348
    -                    self._add_new_link(source_directory, entry)
    
    511
    +                    self._copy_link_from_filesystem(source_directory, entry)
    
    349 512
                         result.files_written.append(relative_pathname)
    
    350 513
                 elif os.path.isdir(import_file):
    
    351 514
                     # A plain directory which already exists isn't a problem; just ignore it.
    
    ... ... @@ -353,10 +516,78 @@ class CasBasedDirectory(Directory):
    353 516
                         self._add_directory(entry)
    
    354 517
                 elif os.path.isfile(import_file):
    
    355 518
                     if self._check_replacement(entry, path_prefix, result):
    
    356
    -                    self._add_new_file(source_directory, entry)
    
    519
    +                    self._add_file(source_directory, entry, modified=relative_pathname in result.overwritten)
    
    357 520
                         result.files_written.append(relative_pathname)
    
    358 521
             return result
    
    359 522
     
    
    523
    +    @staticmethod
    
    524
    +    def _files_in_subdir(sorted_files, dirname):
    
    525
    +        """Filters sorted_files and returns only the ones which have
    
    526
    +           'dirname' as a prefix, with that prefix removed.
    
    527
    +
    
    528
    +        """
    
    529
    +        if not dirname.endswith(os.path.sep):
    
    530
    +            dirname += os.path.sep
    
    531
    +        return [f[len(dirname):] for f in sorted_files if f.startswith(dirname)]
    
    532
    +
    
    533
    +    def _partial_import_cas_into_cas(self, source_directory, files, path_prefix="", file_list_required=True):
    
    534
    +        """ Import only the files and symlinks listed in 'files' from source_directory to this one.
    
    535
    +        Args:
    
    536
    +           source_directory (:class:`.CasBasedDirectory`): The directory to import from
    
    537
    +           files ([str]): List of pathnames to import. Must be a list, not a generator.
    
    538
    +           path_prefix (str): Prefix used to add entries to the file list result.
    
    539
    +           file_list_required: Whether to update the file list while processing.
    
    540
    +        """
    
    541
    +        result = FileListResult()
    
    542
    +        processed_directories = set()
    
    543
    +        for f in files:
    
    544
    +            fullname = os.path.join(path_prefix, f)
    
    545
    +            components = f.split(os.path.sep)
    
    546
    +            if len(components) > 1:
    
    547
    +                # We are importing a thing which is in a subdirectory. We may have already seen this dirname
    
    548
    +                # for a previous file.
    
    549
    +                dirname = components[0]
    
    550
    +                if dirname not in processed_directories:
    
    551
    +                    # Now strip off the first directory name and import files recursively.
    
    552
    +                    subcomponents = CasBasedDirectory._files_in_subdir(files, dirname)
    
    553
    +                    # We will fail at this point if there is a file or symlink to file called 'dirname'.
    
    554
    +                    if dirname in self.index:
    
    555
    +                        resolved_component = self._resolve(dirname, force_create=True)
    
    556
    +                        if isinstance(resolved_component, remote_execution_pb2.FileNode):
    
    557
    +                            dest_subdir = self._replace_anything_with_dir(dirname, path_prefix, result.overwritten)
    
    558
    +                        else:
    
    559
    +                            dest_subdir = resolved_component
    
    560
    +                    else:
    
    561
    +                        dest_subdir = self.descend(dirname, create=True)
    
    562
    +                    src_subdir = source_directory.descend(dirname)
    
    563
    +                    import_result = dest_subdir._partial_import_cas_into_cas(src_subdir, subcomponents,
    
    564
    +                                                                             path_prefix=fullname,
    
    565
    +                                                                             file_list_required=file_list_required)
    
    566
    +                    result.combine(import_result)
    
    567
    +                processed_directories.add(dirname)
    
    568
    +            elif isinstance(source_directory.index[f].buildstream_object, CasBasedDirectory):
    
    569
    +                # The thing in the input file list is a directory on
    
    570
    +                # its own. We don't need to do anything other than create it if it doesn't exist.
    
    571
    +                # If we already have an entry with the same name that isn't a directory, that
    
    572
    +                # will be dealt with when importing files in this directory.
    
    573
    +                if f not in self.index:
    
    574
    +                    self.descend(f, create=True)
    
    575
    +            else:
    
    576
    +                # We're importing a file or symlink - replace anything with the same name.
    
    577
    +                importable = self._check_replacement(f, path_prefix, result)
    
    578
    +                if importable:
    
    579
    +                    item = source_directory.index[f].pb_object
    
    580
    +                    if isinstance(item, remote_execution_pb2.FileNode):
    
    581
    +                        filenode = self.pb2_directory.files.add(digest=item.digest, name=f,
    
    582
    +                                                                is_executable=item.is_executable)
    
    583
    +                        self.index[f] = IndexEntry(filenode, modified=True)
    
    584
    +                    else:
    
    585
    +                        assert isinstance(item, remote_execution_pb2.SymlinkNode)
    
    586
    +                        self._add_new_link_direct(name=f, target=item.target)
    
    587
    +                else:
    
    588
    +                    result.ignored.append(os.path.join(path_prefix, f))
    
    589
    +        return result
    
    590
    +
    
    360 591
         def import_files(self, external_pathspec, *, files=None,
    
    361 592
                          report_written=True, update_utimes=False,
    
    362 593
                          can_link=False):
    
    ... ... @@ -378,28 +609,27 @@ class CasBasedDirectory(Directory):
    378 609
     
    
    379 610
             can_link (bool): Ignored, since hard links do not have any meaning within CAS.
    
    380 611
             """
    
    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 612
     
    
    396 613
             if files is None:
    
    397
    -            files = list_relative_paths(source_directory)
    
    614
    +            if isinstance(external_pathspec, str):
    
    615
    +                files = list_relative_paths(external_pathspec)
    
    616
    +            else:
    
    617
    +                assert isinstance(external_pathspec, Directory)
    
    618
    +                files = external_pathspec.list_relative_paths()
    
    619
    +
    
    620
    +        if isinstance(external_pathspec, FileBasedDirectory):
    
    621
    +            source_directory = external_pathspec.get_underlying_directory()
    
    622
    +            result = self._import_files_from_directory(source_directory, files=files)
    
    623
    +        elif isinstance(external_pathspec, str):
    
    624
    +            source_directory = external_pathspec
    
    625
    +            result = self._import_files_from_directory(source_directory, files=files)
    
    626
    +        else:
    
    627
    +            assert isinstance(external_pathspec, CasBasedDirectory)
    
    628
    +            result = self._partial_import_cas_into_cas(external_pathspec, files=list(files))
    
    398 629
     
    
    399 630
             # TODO: No notice is taken of report_written, update_utimes or can_link.
    
    400 631
             # Current behaviour is to fully populate the report, which is inefficient,
    
    401 632
             # but still correct.
    
    402
    -        result = self._import_files_from_directory(source_directory, files=files)
    
    403 633
     
    
    404 634
             # We need to recalculate and store the hashes of all directories both
    
    405 635
             # up and down the tree; we have changed our directory by importing files
    
    ... ... @@ -511,6 +741,28 @@ class CasBasedDirectory(Directory):
    511 741
             else:
    
    512 742
                 self._mark_directory_unmodified()
    
    513 743
     
    
    744
    +    def _lightweight_resolve_to_index(self, path):
    
    745
    +        """A lightweight function for transforming paths into IndexEntry
    
    746
    +        objects. This does not follow symlinks.
    
    747
    +
    
    748
    +        path: The string to resolve. This should be a series of path
    
    749
    +        components separated by the protocol buffer path separator
    
    750
    +        _pb2_path_sep.
    
    751
    +
    
    752
    +        Returns: the IndexEntry found, or None if any of the path components were not present.
    
    753
    +
    
    754
    +        """
    
    755
    +        directory = self
    
    756
    +        path_components = path.split(CasBasedDirectory._pb2_path_sep)
    
    757
    +        for component in path_components[:-1]:
    
    758
    +            if component not in directory.index:
    
    759
    +                return None
    
    760
    +            if isinstance(directory.index[component].buildstream_object, CasBasedDirectory):
    
    761
    +                directory = directory.index[component].buildstream_object
    
    762
    +            else:
    
    763
    +                return None
    
    764
    +        return directory.index.get(path_components[-1], None)
    
    765
    +
    
    514 766
         def list_modified_paths(self):
    
    515 767
             """Provide a list of relative paths which have been modified since the
    
    516 768
             last call to mark_unmodified.
    
    ... ... @@ -518,29 +770,43 @@ class CasBasedDirectory(Directory):
    518 770
             Return value: List(str) - list of modified paths
    
    519 771
             """
    
    520 772
     
    
    521
    -        filelist = []
    
    522
    -        for (k, v) in self.index.items():
    
    523
    -            if isinstance(v.buildstream_object, CasBasedDirectory):
    
    524
    -                filelist.extend([k + os.path.sep + x for x in v.buildstream_object.list_modified_paths()])
    
    525
    -            elif isinstance(v.pb_object, remote_execution_pb2.FileNode) and v.modified:
    
    526
    -                filelist.append(k)
    
    527
    -        return filelist
    
    773
    +        for p in self.list_relative_paths():
    
    774
    +            i = self._lightweight_resolve_to_index(p)
    
    775
    +            if i and i.modified:
    
    776
    +                yield p
    
    528 777
     
    
    529
    -    def list_relative_paths(self):
    
    778
    +    def list_relative_paths(self, relpath=""):
    
    530 779
             """Provide a list of all relative paths.
    
    531 780
     
    
    532
    -        NOTE: This list is not in the same order as utils.list_relative_paths.
    
    533
    -
    
    534 781
             Return value: List(str) - list of all paths
    
    535 782
             """
    
    536 783
     
    
    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
    
    784
    +        symlink_list = filter(lambda i: isinstance(i[1].pb_object, remote_execution_pb2.SymlinkNode),
    
    785
    +                              self.index.items())
    
    786
    +        file_list = list(filter(lambda i: isinstance(i[1].pb_object, remote_execution_pb2.FileNode),
    
    787
    +                                self.index.items()))
    
    788
    +        directory_list = filter(lambda i: isinstance(i[1].buildstream_object, CasBasedDirectory),
    
    789
    +                                self.index.items())
    
    790
    +
    
    791
    +        # We need to mimic the behaviour of os.walk, in which symlinks
    
    792
    +        # to directories count as directories and symlinks to file or
    
    793
    +        # broken symlinks count as files. os.walk doesn't follow
    
    794
    +        # symlinks, so we don't recurse.
    
    795
    +        for (k, v) in sorted(symlink_list):
    
    796
    +            target = self._resolve(k, absolute_symlinks_resolve=True)
    
    797
    +            if isinstance(target, CasBasedDirectory):
    
    798
    +                yield os.path.join(relpath, k)
    
    799
    +            else:
    
    800
    +                file_list.append((k, v))
    
    801
    +
    
    802
    +        if file_list == [] and relpath != "":
    
    803
    +            yield relpath
    
    804
    +        else:
    
    805
    +            for (k, v) in sorted(file_list):
    
    806
    +                yield os.path.join(relpath, k)
    
    807
    +
    
    808
    +        for (k, v) in sorted(directory_list):
    
    809
    +            yield from v.buildstream_object.list_relative_paths(relpath=os.path.join(relpath, k))
    
    544 810
     
    
    545 811
         def recalculate_hash(self):
    
    546 812
             """ Recalcuates the hash for this directory and store the results in
    

  • doc/source/format_project.rst
    ... ... @@ -190,19 +190,34 @@ for more detail.
    190 190
     Artifact server
    
    191 191
     ~~~~~~~~~~~~~~~
    
    192 192
     If you have setup an :ref:`artifact server <artifacts>` for your
    
    193
    -project then it is convenient to configure this in your ``project.conf``
    
    193
    +project then it is convenient to configure the following in your ``project.conf``
    
    194 194
     so that users need not have any additional configuration to communicate
    
    195 195
     with an artifact share.
    
    196 196
     
    
    197 197
     .. code:: yaml
    
    198 198
     
    
    199
    +  #
    
    200
    +  # Artifacts
    
    201
    +  #
    
    199 202
       artifacts:
    
    203
    +    # A remote cache from which to download prebuilt artifacts
    
    204
    +    - url: https://foo.com/artifacts:11001
    
    205
    +      server.cert: server.crt
    
    206
    +    # A remote cache from which to upload/download built/prebuilt artifacts
    
    207
    +    - url: https://foo.com/artifacts:11002
    
    208
    +      server-cert: server.crt
    
    209
    +      client-cert: client.crt
    
    210
    +      client-key: client.key
    
    200 211
     
    
    201
    -    # A url from which to download prebuilt artifacts
    
    202
    -    url: https://foo.com/artifacts
    
    212
    +.. note::
    
    213
    +
    
    214
    +    You can also specify a list of different caches here; earlier entries in the
    
    215
    +    list will have higher priority than later ones.
    
    216
    +
    
    217
    +The use of ports are required to distinguish between pull only access and
    
    218
    +push/pull access. For information regarding the server/client certificates
    
    219
    +and keys, please see: :ref:`Key pair for the server <server_authentication>`.
    
    203 220
     
    
    204
    -You can also specify a list of caches here; earlier entries in the list
    
    205
    -will have higher priority than later ones.
    
    206 221
     
    
    207 222
     Remote execution
    
    208 223
     ~~~~~~~~~~~~~~~~
    

  • doc/source/using_config.rst
    ... ... @@ -32,38 +32,75 @@ the supported configurations on a project wide basis are listed here.
    32 32
     
    
    33 33
     Artifact server
    
    34 34
     ~~~~~~~~~~~~~~~
    
    35
    -The project you build will often specify a :ref:`remote artifact cache
    
    36
    -<artifacts>` already, but you may want to specify extra caches. There are two
    
    37
    -ways to do this.  You can add one or more global caches:
    
    35
    +Although project's often specify a :ref:`remote artifact cache <artifacts>` in
    
    36
    +their ``project.conf``, you may also want to specify extra caches.
    
    38 37
     
    
    39
    -**Example**
    
    38
    +Assuming that your host/server is reachable on the internet as ``artifacts.com``
    
    39
    +(for example), there are two ways to declare remote caches in your user
    
    40
    +configuration:
    
    41
    +
    
    42
    +1. Adding global caches:
    
    40 43
     
    
    41 44
     .. code:: yaml
    
    42 45
     
    
    46
    +   #
    
    47
    +   # Artifacts
    
    48
    +   #
    
    43 49
        artifacts:
    
    44
    -     url: https://artifacts.com/artifacts
    
    50
    +     # Add a cache to pull from
    
    51
    +     - url: https://artifacts.com/artifacts:11001
    
    52
    +       server-cert: server.crt
    
    53
    +     # Add a cache to push/pull to/from
    
    54
    +     - url: https://artifacts.com/artifacts:11002
    
    55
    +       server-cert: server.crt
    
    56
    +       client-cert: client.crt
    
    57
    +       client-key: client.key
    
    58
    +       push: true
    
    59
    +     # Add another cache to pull from
    
    60
    +     - url: https://anothercache.com/artifacts:8080
    
    61
    +       server-cert: another_server.crt
    
    62
    +
    
    63
    +.. note::
    
    45 64
     
    
    46
    -Caches listed there will be considered lower priority than those specified
    
    47
    -by the project configuration.
    
    65
    +    Caches declared here will be used by **all** BuildStream project's on the user's
    
    66
    +    machine and are considered a lower priority than those specified in the project
    
    67
    +    configuration.
    
    48 68
     
    
    49
    -You can also add project-specific caches:
    
    50 69
     
    
    51
    -**Example**
    
    70
    +2. Specifying caches for a specific project within the user configuration:
    
    52 71
     
    
    53 72
     .. code:: yaml
    
    54 73
     
    
    55 74
        projects:
    
    56 75
          project-name:
    
    57 76
            artifacts:
    
    58
    -         - url: https://artifacts.com/artifacts1
    
    59
    -         - url: ssh://user artifacts com/artifacts2
    
    77
    +         # Add a cache to pull from
    
    78
    +         - url: https://artifacts.com/artifacts:11001
    
    79
    +           server-cert: server.crt
    
    80
    +         # Add a cache to push/pull to/from
    
    81
    +         - url: https://artifacts.com/artifacts:11002
    
    82
    +           server-cert: server.crt
    
    83
    +           client-cert: client.crt
    
    84
    +           client-key: client.key
    
    60 85
                push: true
    
    86
    +         # Add another cache to pull from
    
    87
    +         - url: https://ourprojectcache.com/artifacts:8080
    
    88
    +           server-cert: project_server.crt
    
    89
    +
    
    90
    +
    
    91
    +.. note::
    
    92
    +
    
    93
    +    Caches listed here will be considered a higher priority than those specified
    
    94
    +    by the project. Furthermore, for a given list of URLs, earlier entries will
    
    95
    +    have higher priority.
    
    96
    +
    
    97
    +
    
    98
    +Notice that the use of different ports for the same server distinguishes between
    
    99
    +pull only access and push/pull access. For information regarding this and the
    
    100
    +server/client certificates and keys, please see:
    
    101
    +:ref:`Key pair for the server <server_authentication>`.
    
    61 102
     
    
    62
    -Caches listed here will be considered higher priority than those specified
    
    63
    -by the project.
    
    64 103
     
    
    65
    -If you give a list of URLs, earlier entries in the list will have higher
    
    66
    -priority than later ones.
    
    67 104
     
    
    68 105
     Strict build plan
    
    69 106
     ~~~~~~~~~~~~~~~~~
    

  • doc/source/using_configuring_artifact_server.rst
    ... ... @@ -98,6 +98,8 @@ Command reference
    98 98
        :prog: bst-artifact-server
    
    99 99
     
    
    100 100
     
    
    101
    +.. _server_authentication:
    
    102
    +
    
    101 103
     Key pair for the server
    
    102 104
     ~~~~~~~~~~~~~~~~~~~~~~~
    
    103 105
     
    
    ... ... @@ -237,52 +239,12 @@ We can then check if the services are successfully running with:
    237 239
     For more information on systemd services see: 
    
    238 240
     `Creating Systemd Service Files <https://www.devdungeon.com/content/creating-systemd-service-files>`_.
    
    239 241
     
    
    240
    -User configuration
    
    241
    -~~~~~~~~~~~~~~~~~~
    
    242
    -The user configuration for artifacts is documented with the rest
    
    243
    -of the :ref:`user configuration documentation <user_config>`.
    
    244
    -
    
    245
    -Note that for self-signed certificates, the public key fields are mandatory.
    
    246
    -
    
    247
    -Assuming you have the same setup used in this document, and that your
    
    248
    -host is reachable on the internet as ``artifacts.com`` (for example),
    
    249
    -then a user can use the following user configuration:
    
    250
    -
    
    251
    -Pull-only:
    
    252
    -
    
    253
    -.. code:: yaml
    
    254
    -
    
    255
    -   #
    
    256
    -   #    Artifacts
    
    257
    -   #
    
    258
    -   artifacts:
    
    259
    -
    
    260
    -     url: https://artifacts.com:11001
    
    261
    -
    
    262
    -     # Optional server certificate if not trusted by system root certificates
    
    263
    -     server-cert: server.crt
    
    242
    +Declaring remote artifact caches
    
    243
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    244
    +Remote artifact caches can be declared within either:
    
    264 245
     
    
    265
    -Pull and push:
    
    266
    -
    
    267
    -.. code:: yaml
    
    268
    -
    
    269
    -   #
    
    270
    -   #    Artifacts
    
    271
    -   #
    
    272
    -   artifacts:
    
    273
    -
    
    274
    -     url: https://artifacts.com:11002
    
    275
    -
    
    276
    -     # Optional server certificate if not trusted by system root certificates
    
    277
    -     server-cert: server.crt
    
    278
    -
    
    279
    -     # Optional client key pair for authentication
    
    280
    -     client-key: client.key
    
    281
    -     client-cert: client.crt
    
    282
    -
    
    283
    -     push: true
    
    284
    -
    
    285
    -.. note::
    
    246
    +1. The :ref:`project configuration <project_essentials_artifacts>`, or
    
    247
    +2. The :ref:`user configuration <config_artifacts>`.
    
    286 248
     
    
    287
    -    Equivalent statements can be delcared in a project's configuration file
    
    288
    -    (the ``project.conf``).
    249
    +Please follow the above links to see examples showing how we declare remote
    
    250
    +caches in both the project configuration and the user configuration, respectively.

  • tests/storage/virtual_directory_import.py
    1
    +from hashlib import sha256
    
    2
    +import os
    
    3
    +import pytest
    
    4
    +import random
    
    5
    +import tempfile
    
    6
    +from tests.testutils import cli
    
    7
    +
    
    8
    +from buildstream.storage._casbaseddirectory import CasBasedDirectory
    
    9
    +from buildstream.storage._filebaseddirectory import FileBasedDirectory
    
    10
    +from buildstream._artifactcache import ArtifactCache
    
    11
    +from buildstream._artifactcache.cascache import CASCache
    
    12
    +from buildstream import utils
    
    13
    +
    
    14
    +
    
    15
    +# These are comparitive tests that check that FileBasedDirectory and
    
    16
    +# CasBasedDirectory act identically.
    
    17
    +
    
    18
    +
    
    19
    +class FakeArtifactCache():
    
    20
    +    def __init__(self):
    
    21
    +        self.cas = None
    
    22
    +
    
    23
    +
    
    24
    +class FakeContext():
    
    25
    +    def __init__(self):
    
    26
    +        self.artifactdir = ''
    
    27
    +        self.artifactcache = FakeArtifactCache()
    
    28
    +
    
    29
    +
    
    30
    +# This is a set of example file system contents. It's a set of trees
    
    31
    +# which are either expected to be problematic or were found to be
    
    32
    +# problematic during random testing.
    
    33
    +
    
    34
    +# The test attempts to import each on top of each other to test
    
    35
    +# importing works consistently.  Each tuple is defined as (<filename>,
    
    36
    +# <type>, <content>). Type can be 'F' (file), 'S' (symlink) or 'D'
    
    37
    +# (directory) with content being the contents for a file or the
    
    38
    +# destination for a symlink.
    
    39
    +root_filesets = [
    
    40
    +    [('a/b/c/textfile1', 'F', 'This is textfile 1\n')],
    
    41
    +    [('a/b/c/textfile1', 'F', 'This is the replacement textfile 1\n')],
    
    42
    +    [('a/b/d', 'D', '')],
    
    43
    +    [('a/b/c', 'S', '/a/b/d')],
    
    44
    +    [('a/b/d', 'S', '/a/b/c')],
    
    45
    +    [('a/b/d', 'D', ''), ('a/b/c', 'S', '/a/b/d')],
    
    46
    +    [('a/b/c', 'D', ''), ('a/b/d', 'S', '/a/b/c')],
    
    47
    +    [('a/b', 'F', 'This is textfile 1\n')],
    
    48
    +    [('a/b/c', 'F', 'This is textfile 1\n')],
    
    49
    +    [('a/b/c', 'D', '')]
    
    50
    +]
    
    51
    +
    
    52
    +empty_hash_ref = sha256().hexdigest()
    
    53
    +RANDOM_SEED = 69105
    
    54
    +NUM_RANDOM_TESTS = 10
    
    55
    +
    
    56
    +
    
    57
    +def generate_import_roots(rootno, directory):
    
    58
    +    rootname = "root{}".format(rootno)
    
    59
    +    rootdir = os.path.join(directory, "content", rootname)
    
    60
    +    if os.path.exists(rootdir):
    
    61
    +        return
    
    62
    +    for (path, typesymbol, content) in root_filesets[rootno - 1]:
    
    63
    +        if typesymbol == 'F':
    
    64
    +            (dirnames, filename) = os.path.split(path)
    
    65
    +            os.makedirs(os.path.join(rootdir, dirnames), exist_ok=True)
    
    66
    +            with open(os.path.join(rootdir, dirnames, filename), "wt") as f:
    
    67
    +                f.write(content)
    
    68
    +        elif typesymbol == 'D':
    
    69
    +            os.makedirs(os.path.join(rootdir, path), exist_ok=True)
    
    70
    +        elif typesymbol == 'S':
    
    71
    +            (dirnames, filename) = os.path.split(path)
    
    72
    +            os.makedirs(os.path.join(rootdir, dirnames), exist_ok=True)
    
    73
    +            os.symlink(content, os.path.join(rootdir, path))
    
    74
    +
    
    75
    +
    
    76
    +def generate_random_root(rootno, directory):
    
    77
    +    random.seed(RANDOM_SEED + rootno)
    
    78
    +    rootname = "root{}".format(rootno)
    
    79
    +    rootdir = os.path.join(directory, "content", rootname)
    
    80
    +    if os.path.exists(rootdir):
    
    81
    +        return
    
    82
    +    things = []
    
    83
    +    locations = ['.']
    
    84
    +    os.makedirs(rootdir)
    
    85
    +    for i in range(0, 100):
    
    86
    +        location = random.choice(locations)
    
    87
    +        thingname = "node{}".format(i)
    
    88
    +        thing = random.choice(['dir', 'link', 'file'])
    
    89
    +        target = os.path.join(rootdir, location, thingname)
    
    90
    +        if thing == 'dir':
    
    91
    +            os.makedirs(target)
    
    92
    +            locations.append(os.path.join(location, thingname))
    
    93
    +        elif thing == 'file':
    
    94
    +            with open(target, "wt") as f:
    
    95
    +                f.write("This is node {}\n".format(i))
    
    96
    +        elif thing == 'link':
    
    97
    +            # TODO: Make some relative symlinks
    
    98
    +            if random.randint(1, 3) == 1 or not things:
    
    99
    +                os.symlink("/broken", target)
    
    100
    +            else:
    
    101
    +                symlink_destination = random.choice(things)
    
    102
    +                os.symlink(symlink_destination, target)
    
    103
    +        things.append(os.path.join(location, thingname))
    
    104
    +
    
    105
    +
    
    106
    +def file_contents(path):
    
    107
    +    with open(path, "r") as f:
    
    108
    +        result = f.read()
    
    109
    +    return result
    
    110
    +
    
    111
    +
    
    112
    +def file_contents_are(path, contents):
    
    113
    +    return file_contents(path) == contents
    
    114
    +
    
    115
    +
    
    116
    +def create_new_casdir(root_number, fake_context, tmpdir):
    
    117
    +    d = CasBasedDirectory(fake_context)
    
    118
    +    d.import_files(os.path.join(tmpdir, "content", "root{}".format(root_number)))
    
    119
    +    assert d.ref.hash != empty_hash_ref
    
    120
    +    return d
    
    121
    +
    
    122
    +
    
    123
    +def create_new_filedir(root_number, tmpdir):
    
    124
    +    root = os.path.join(tmpdir, "vdir")
    
    125
    +    os.makedirs(root)
    
    126
    +    d = FileBasedDirectory(root)
    
    127
    +    d.import_files(os.path.join(tmpdir, "content", "root{}".format(root_number)))
    
    128
    +    return d
    
    129
    +
    
    130
    +
    
    131
    +def combinations(integer_range):
    
    132
    +    for x in integer_range:
    
    133
    +        for y in integer_range:
    
    134
    +            yield (x, y)
    
    135
    +
    
    136
    +
    
    137
    +def resolve_symlinks(path, root):
    
    138
    +    """ A function to resolve symlinks inside 'path' components apart from the last one.
    
    139
    +        For example, resolve_symlinks('/a/b/c/d', '/a/b')
    
    140
    +        will return '/a/b/f/d' if /a/b/c is a symlink to /a/b/f. The final component of
    
    141
    +        'path' is not resolved, because we typically want to inspect the symlink found
    
    142
    +        at that path, not its target.
    
    143
    +
    
    144
    +    """
    
    145
    +    components = path.split(os.path.sep)
    
    146
    +    location = root
    
    147
    +    for i in range(0, len(components) - 1):
    
    148
    +        location = os.path.join(location, components[i])
    
    149
    +        if os.path.islink(location):
    
    150
    +            # Resolve the link, add on all the remaining components
    
    151
    +            target = os.path.join(os.readlink(location))
    
    152
    +            tail = os.path.sep.join(components[i + 1:])
    
    153
    +
    
    154
    +            if target.startswith(os.path.sep):
    
    155
    +                # Absolute link - relative to root
    
    156
    +                location = os.path.join(root, target, tail)
    
    157
    +            else:
    
    158
    +                # Relative link - relative to symlink location
    
    159
    +                location = os.path.join(location, target)
    
    160
    +            return resolve_symlinks(location, root)
    
    161
    +    # If we got here, no symlinks were found. Add on the final component and return.
    
    162
    +    location = os.path.join(location, components[-1])
    
    163
    +    return location
    
    164
    +
    
    165
    +
    
    166
    +def directory_not_empty(path):
    
    167
    +    return os.listdir(path)
    
    168
    +
    
    169
    +
    
    170
    +def _import_test(tmpdir, original, overlay, generator_function, verify_contents=False):
    
    171
    +    fake_context = FakeContext()
    
    172
    +    fake_context.artifactcache.cas = CASCache(tmpdir)
    
    173
    +    # Create some fake content
    
    174
    +    generator_function(original, tmpdir)
    
    175
    +    if original != overlay:
    
    176
    +        generator_function(overlay, tmpdir)
    
    177
    +
    
    178
    +    d = create_new_casdir(original, fake_context, tmpdir)
    
    179
    +
    
    180
    +    duplicate_cas = create_new_casdir(original, fake_context, tmpdir)
    
    181
    +
    
    182
    +    assert duplicate_cas.ref.hash == d.ref.hash
    
    183
    +
    
    184
    +    d2 = create_new_casdir(overlay, fake_context, tmpdir)
    
    185
    +    d.import_files(d2)
    
    186
    +    export_dir = os.path.join(tmpdir, "output-{}-{}".format(original, overlay))
    
    187
    +    roundtrip_dir = os.path.join(tmpdir, "roundtrip-{}-{}".format(original, overlay))
    
    188
    +    d2.export_files(roundtrip_dir)
    
    189
    +    d.export_files(export_dir)
    
    190
    +
    
    191
    +    if verify_contents:
    
    192
    +        for item in root_filesets[overlay - 1]:
    
    193
    +            (path, typename, content) = item
    
    194
    +            realpath = resolve_symlinks(path, export_dir)
    
    195
    +            if typename == 'F':
    
    196
    +                if os.path.isdir(realpath) and directory_not_empty(realpath):
    
    197
    +                    # The file should not have overwritten the directory in this case.
    
    198
    +                    pass
    
    199
    +                else:
    
    200
    +                    assert os.path.isfile(realpath), "{} did not exist in the combined virtual directory".format(path)
    
    201
    +                    assert file_contents_are(realpath, content)
    
    202
    +            elif typename == 'S':
    
    203
    +                if os.path.isdir(realpath) and directory_not_empty(realpath):
    
    204
    +                    # The symlink should not have overwritten the directory in this case.
    
    205
    +                    pass
    
    206
    +                else:
    
    207
    +                    assert os.path.islink(realpath)
    
    208
    +                    assert os.readlink(realpath) == content
    
    209
    +            elif typename == 'D':
    
    210
    +                # We can't do any more tests than this because it
    
    211
    +                # depends on things present in the original. Blank
    
    212
    +                # directories here will be ignored and the original
    
    213
    +                # left in place.
    
    214
    +                assert os.path.lexists(realpath)
    
    215
    +
    
    216
    +    # Now do the same thing with filebaseddirectories and check the contents match
    
    217
    +
    
    218
    +    files = list(utils.list_relative_paths(roundtrip_dir))
    
    219
    +    duplicate_cas._import_files_from_directory(roundtrip_dir, files=files)
    
    220
    +    duplicate_cas._recalculate_recursing_down()
    
    221
    +    if duplicate_cas.parent:
    
    222
    +        duplicate_cas.parent._recalculate_recursing_up(duplicate_cas)
    
    223
    +
    
    224
    +    assert duplicate_cas.ref.hash == d.ref.hash
    
    225
    +
    
    226
    +
    
    227
    +# It's possible to parameterize on both original and overlay values,
    
    228
    +# but this leads to more tests being listed in the output than are
    
    229
    +# comfortable.
    
    230
    +@pytest.mark.parametrize("original", range(1, len(root_filesets) + 1))
    
    231
    +def test_fixed_cas_import(cli, tmpdir, original):
    
    232
    +    for overlay in range(1, len(root_filesets) + 1):
    
    233
    +        _import_test(str(tmpdir), original, overlay, generate_import_roots, verify_contents=True)
    
    234
    +
    
    235
    +
    
    236
    +@pytest.mark.parametrize("original", range(1, NUM_RANDOM_TESTS + 1))
    
    237
    +def test_random_cas_import(cli, tmpdir, original):
    
    238
    +    for overlay in range(1, NUM_RANDOM_TESTS + 1):
    
    239
    +        _import_test(str(tmpdir), original, overlay, generate_random_root, verify_contents=False)
    
    240
    +
    
    241
    +
    
    242
    +def _listing_test(tmpdir, root, generator_function):
    
    243
    +    fake_context = FakeContext()
    
    244
    +    fake_context.artifactcache.cas = CASCache(tmpdir)
    
    245
    +    # Create some fake content
    
    246
    +    generator_function(root, tmpdir)
    
    247
    +
    
    248
    +    d = create_new_filedir(root, tmpdir)
    
    249
    +    filelist = list(d.list_relative_paths())
    
    250
    +
    
    251
    +    d2 = create_new_casdir(root, fake_context, tmpdir)
    
    252
    +    filelist2 = list(d2.list_relative_paths())
    
    253
    +
    
    254
    +    assert filelist == filelist2
    
    255
    +
    
    256
    +
    
    257
    +@pytest.mark.parametrize("root", range(1, 11))
    
    258
    +def test_random_directory_listing(cli, tmpdir, root):
    
    259
    +    _listing_test(str(tmpdir), root, generate_random_root)
    
    260
    +
    
    261
    +
    
    262
    +@pytest.mark.parametrize("root", [1, 2, 3, 4, 5])
    
    263
    +def test_fixed_directory_listing(cli, tmpdir, root):
    
    264
    +    _listing_test(str(tmpdir), root, generate_import_roots)



  • [Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]