# # directory_impl.py # # This source file is part of the FoundationDB open source project # # Copyright 2013-2018 Apple Inc. and the FoundationDB project authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # FoundationDB Python API import random import struct import threading from fdb import impl as _impl from fdb import six import fdb.tuple from .subspace_impl import Subspace class AllocatorTransactionState: def __init__(self): self.lock = threading.Lock() class HighContentionAllocator (object): def __init__(self, subspace): self.counters = subspace[0] self.recent = subspace[1] self.lock = threading.Lock() @_impl.transactional def allocate(self, tr): """Returns a byte string that 1) has never and will never be returned by another call to this method on the same subspace 2) is nearly as short as possible given the above """ # Get transaction-local state if not hasattr(tr, "__fdb_directory_layer_hca_state__"): with self.lock: if not hasattr(tr, "__fdb_directory_layer_hca_state__"): tr.__fdb_directory_layer_hca_state__ = AllocatorTransactionState() tr_state = tr.__fdb_directory_layer_hca_state__ while True: [start] = [self.counters.unpack(k)[0] for k, _ in tr.snapshot.get_range( self.counters.range().start, self.counters.range().stop, limit=1, reverse=True)] or [0] window_advanced = False while True: with tr_state.lock: if window_advanced: del tr[self.counters: self.counters[start]] tr.options.set_next_write_no_write_conflict_range() del tr[self.recent: self.recent[start]] # Increment the allocation count for the current window tr.add(self.counters[start], struct.pack(" 0 and latest_counter[0] > start: break if candidate_value == None: tr.add_write_conflict_key(self.recent[candidate]) return fdb.tuple.pack((candidate,)) def _window_size(self, start): # Larger window sizes are better for high contention, smaller sizes for # keeping the keys small. But if there are many allocations, the keys # can't be too small. So start small and scale up. We don't want this # to ever get *too* big because we have to store about window_size/2 # recent items. if start < 255: return 64 if start < 65535: return 1024 return 8192 class Directory(object): def __init__(self, directory_layer, path=(), layer=b''): self._directory_layer = directory_layer self._path = path self._layer = layer @_impl.transactional def create_or_open(self, tr, path, layer=None): path = self._tuplify_path(path) return self._directory_layer.create_or_open(tr, self._partition_subpath(path), layer) @_impl.transactional def open(self, tr, path, layer=None): path = self._tuplify_path(path) return self._directory_layer.open(tr, self._partition_subpath(path), layer) @_impl.transactional def create(self, tr, path, layer=None, prefix=None): path = self._tuplify_path(path) return self._directory_layer.create(tr, self._partition_subpath(path), layer, prefix) @_impl.transactional def list(self, tr, path=()): path = self._tuplify_path(path) return self._directory_layer.list(tr, self._partition_subpath(path)) @_impl.transactional def move(self, tr, old_path, new_path): old_path = self._tuplify_path(old_path) new_path = self._tuplify_path(new_path) return self._directory_layer.move(tr, self._partition_subpath(old_path), self._partition_subpath(new_path)) @_impl.transactional def move_to(self, tr, new_absolute_path): directory_layer = self._get_layer_for_path(()) new_absolute_path = _to_unicode_path(new_absolute_path) partition_len = len(directory_layer._path) partition_path = new_absolute_path[:partition_len] if partition_path != directory_layer._path: raise ValueError("Cannot move between partitions.") return directory_layer.move(tr, self._path[partition_len:], new_absolute_path[partition_len:]) @_impl.transactional def remove(self, tr, path=()): path = self._tuplify_path(path) directory_layer = self._get_layer_for_path(path) return directory_layer.remove(tr, self._partition_subpath(path, directory_layer)) @_impl.transactional def remove_if_exists(self, tr, path=()): path = self._tuplify_path(path) directory_layer = self._get_layer_for_path(path) return directory_layer.remove_if_exists(tr, self._partition_subpath(path, directory_layer)) @_impl.transactional def exists(self, tr, path=()): path = self._tuplify_path(path) directory_layer = self._get_layer_for_path(path) return directory_layer.exists(tr, self._partition_subpath(path, directory_layer)) def get_layer(self): return self._layer def get_path(self): return self._path def _tuplify_path(self, path): if not isinstance(path, tuple): path = (path,) return path def _partition_subpath(self, path, directory_layer=None): directory_layer = directory_layer or self._directory_layer return self._path[len(directory_layer._path):] + path # Called by all functions that could operate on this subspace directly (move_to, remove, remove_if_exists, exists) # Subclasses can choose to return a different directory layer to use for the operation if path is in fact () def _get_layer_for_path(self, path): return self._directory_layer class DirectoryLayer(Directory): def __init__(self, node_subspace=Subspace(rawPrefix=b'\xfe'), content_subspace=Subspace(), allow_manual_prefixes=False): Directory.__init__(self, self) # If specified, new automatically allocated prefixes will all fall within content_subspace self._content_subspace = content_subspace self._node_subspace = node_subspace self._allow_manual_prefixes = allow_manual_prefixes # The root node is the one whose contents are the node subspace self._root_node = self._node_subspace[self._node_subspace.key()] self._allocator = HighContentionAllocator(self._root_node[b'hca']) @_impl.transactional def create_or_open(self, tr, path, layer=None): """ Opens the directory with the given path. If the directory does not exist, it is created (creating parent directories if necessary). If layer is specified, it is checked against the layer of an existing directory or set as the layer of a new directory. """ return self._create_or_open_internal(tr, path, layer) def _create_or_open_internal(self, tr, path, layer=None, prefix=None, allow_create=True, allow_open=True): self._check_version(tr, write_access=False) if prefix is not None and not self._allow_manual_prefixes: if len(self._path) == 0: raise ValueError("Cannot specify a prefix unless manual prefixes are enabled.") else: raise ValueError("Cannot specify a prefix in a partition.") path = _to_unicode_path(path) if not path: # Root directory contains node metadata and so cannot be opened. raise ValueError("The root directory cannot be opened.") existing_node = self._find(tr, path).prefetch_metadata(tr) if existing_node.exists(): if existing_node.is_in_partition(): subpath = existing_node.get_partition_subpath() return existing_node.get_contents(self)._directory_layer._create_or_open_internal( tr, subpath, layer, prefix, allow_create, allow_open ) if not allow_open: raise ValueError("The directory already exists.") if layer and existing_node.layer() != layer: raise ValueError("The directory was created with an incompatible layer.") return existing_node.get_contents(self) if not allow_create: raise ValueError("The directory does not exist.") self._check_version(tr) if prefix == None: prefix = self._content_subspace.key() + self._allocator.allocate(tr) if len(list(tr.get_range_startswith(prefix, limit=1))) > 0: raise Exception("The database has keys stored at the prefix chosen by the automatic prefix allocator: %r." % prefix) if not self._is_prefix_free(tr.snapshot, prefix): raise Exception("The directory layer has manually allocated prefixes that conflict with the automatic prefix allocator.") elif not self._is_prefix_free(tr, prefix): raise ValueError("The given prefix is already in use.") if len(path) > 1: parent_node = self._node_with_prefix(self.create_or_open(tr, path[:-1]).key()) else: parent_node = self._root_node if not parent_node: # print repr(path[:-1]) raise ValueError("The parent directory doesn't exist.") node = self._node_with_prefix(prefix) tr[parent_node[self.SUBDIRS][path[-1]]] = prefix if not layer: layer = b'' tr[node[b'layer']] = layer return self._contents_of_node(node, path, layer) @_impl.transactional def open(self, tr, path, layer=None): """ Opens the directory with the given path. An error is raised if the directory does not exist, or if a layer is specified and a different layer was specified when the directory was created. """ return self._create_or_open_internal(tr, path, layer, allow_create=False) @_impl.transactional def create(self, tr, path, layer=None, prefix=None): """Creates a directory with the given path (creating parent directories if necessary). An error is raised if the given directory already exists. If prefix is specified, the directory is created with the given physical prefix; otherwise a prefix is allocated automatically. If layer is specified, it is recorded with the directory and will be checked by future calls to open. """ return self._create_or_open_internal(tr, path, layer, prefix, allow_open=False) @_impl.transactional def move_to(self, tr, new_absolute_path): raise Exception('The root directory cannot be moved.') @_impl.transactional def move(self, tr, old_path, new_path): """Moves the directory found at `old_path` to `new_path`. There is no effect on the physical prefix of the given directory, or on clients that already have the directory open. An error is raised if the old directory does not exist, a directory already exists at `new_path`, or the parent directory of `new_path` does not exist. """ self._check_version(tr) old_path = _to_unicode_path(old_path) new_path = _to_unicode_path(new_path) if old_path == new_path[:len(old_path)]: raise ValueError("The destination directory cannot be a subdirectory of the source directory.") old_node = self._find(tr, old_path).prefetch_metadata(tr) new_node = self._find(tr, new_path).prefetch_metadata(tr) if not old_node.exists(): raise ValueError("The source directory does not exist.") if old_node.is_in_partition() or new_node.is_in_partition(): if not old_node.is_in_partition() or not new_node.is_in_partition() or old_node.path != new_node.path: raise ValueError("Cannot move between partitions.") return new_node.get_contents(self).move(tr, old_node.get_partition_subpath(), new_node.get_partition_subpath()) if new_node.exists(): raise ValueError("The destination directory already exists. Remove it first.") parent_node = self._find(tr, new_path[:-1]) if not parent_node.exists(): raise ValueError("The parent of the destination directory does not exist. Create it first.") tr[parent_node.subspace[self.SUBDIRS][new_path[-1]]] = self._node_subspace.unpack(old_node.subspace.key())[0] self._remove_from_parent(tr, old_path) return self._contents_of_node(old_node.subspace, new_path, old_node.layer()) @_impl.transactional def remove(self, tr, path=()): """Removes the directory, its contents, and all subdirectories. Throws an exception if the directory does not exist. Warning: Clients that have already opened the directory might still insert data into its contents after it is removed. """ return self._remove_internal(tr, path, fail_on_nonexistent=True) @_impl.transactional def remove_if_exists(self, tr, path=()): """Removes the directory, its contents, and all subdirectories, if it exists. Returns true if the directory existed and false otherwise. Warning: Clients that have already opened the directory might still insert data into its contents after it is removed. """ return self._remove_internal(tr, path, fail_on_nonexistent=False) def _remove_internal(self, tr, path, fail_on_nonexistent): self._check_version(tr) if not path: raise ValueError("The root directory cannot be removed.") path = _to_unicode_path(path) node = self._find(tr, path).prefetch_metadata(tr) if not node.exists(): if fail_on_nonexistent: raise ValueError("The directory does not exist.") else: return False if node.is_in_partition(): return node.get_contents(self)._directory_layer._remove_internal(tr, node.get_partition_subpath(), fail_on_nonexistent) self._remove_recursive(tr, node.subspace) self._remove_from_parent(tr, path) return True @_impl.transactional def list(self, tr, path=()): """Returns the names of the specified directory's subdirectories as a list of strings. """ self._check_version(tr, write_access=False) path = _to_unicode_path(path) node = self._find(tr, path).prefetch_metadata(tr) if not node.exists(): raise ValueError("The directory does not exist.") if node.is_in_partition(include_empty_subpath=True): return node.get_contents(self).list(tr, node.get_partition_subpath()) return [name for name, cnode in self._subdir_names_and_nodes(tr, node.subspace)] @_impl.transactional def exists(self, tr, path=()): """Returns whether or not the specified directory exists.""" self._check_version(tr, write_access=False) path = _to_unicode_path(path) node = self._find(tr, path).prefetch_metadata(tr) if not node.exists(): return False if node.is_in_partition(): return node.get_contents(self).exists(tr, node.get_partition_subpath()) return True ######################################## # Private methods for implementation # ######################################## SUBDIRS = 0 VERSION = (1, 0, 0) def _check_version(self, tr, write_access=True): version = tr[self._root_node[b'version']] if not version.present(): if write_access: self._initialize_directory(tr) return version = struct.unpack(' self.VERSION[0]: raise Exception("Cannot load directory with version %d.%d.%d using directory layer %d.%d.%d" % (version + self.VERSION)) if version[1] > self.VERSION[1] and write_access: raise Exception("Directory with version %d.%d.%d is read-only when opened using directory layer %d.%d.%d" % (version + self.VERSION)) def _initialize_directory(self, tr): tr[self._root_node[b'version']] = struct.pack(' len(self.path)) def get_partition_subpath(self): return self.target_path[len(self.path):] def get_contents(self, directory_layer, tr=None): return directory_layer._contents_of_node(self.subspace, self.path, self.layer(tr))