objects: migrate remote push/pull to objects.transfer (#6308)

* objects: migrate remote status to objects.status

* data_cloud: use objects.status

* objects: migrate remote._process to objects.transfer

* data_cloud: use objects.transfer

* objects: handle memfs staging objects in transfer

* fetch/import: use unified transfer()

* update get_remote and transfer exception usage

* update tests

* objects.transfer: use src ODB verify rules after xfer

* odb: move index from remote into odb

* objects.transfer: skip src status check when possible

* update tests

* remove dvc.remote

* odb.index: migrate to diskcache

* objects: fix status/transfer optimization

* update index usage

* state: remove dead sqlite related code

* update cloud tests

* drop unnecessary remove in tests

* use abstract base class in odb index

* status: load trees from local cache instead of remote odb when possible

* handle status when dir cache is explicitly removed
This commit is contained in:
Peter Rowlands (변기호)
2021-07-20 13:30:01 +03:00
committed by GitHub
parent 66d0df2d12
commit 3d84df930b
42 changed files with 890 additions and 1285 deletions
+18
View File
@@ -1,5 +1,10 @@
from typing import TYPE_CHECKING
from dvc.scheme import Schemes
if TYPE_CHECKING:
from .index import ObjectDBIndexBase
def get_odb(fs, path_info, **config):
from .base import ObjectDB
@@ -34,6 +39,19 @@ def _get_odb(repo, settings):
return get_odb(cls(**config), path_info, state=repo.state, **config)
def get_index(odb) -> "ObjectDBIndexBase":
import hashlib
from .index import ObjectDBIndex, ObjectDBIndexNoop
cls = ObjectDBIndex if odb.tmp_dir else ObjectDBIndexNoop
return cls(
odb.tmp_dir,
hashlib.sha256(odb.path_info.url.encode("utf-8")).hexdigest(),
odb.fs.CHECKSUM_DIR_SUFFIX,
)
class ODBManager:
CACHE_DIR = "cache"
CLOUD_SCHEMES = [
+12 -3
View File
@@ -81,12 +81,16 @@ class ObjectDB:
fs: "BaseFileSystem",
hash_info: "HashInfo",
move: bool = True,
verify: Optional[bool] = None,
**kwargs,
):
if self.read_only:
raise ObjectDBPermissionError("Cannot add to read-only ODB")
if verify is None:
verify = self.verify
try:
self.check(hash_info, check_hash=self.verify)
self.check(hash_info, check_hash=verify)
return
except (ObjectFormatError, FileNotFoundError):
pass
@@ -120,8 +124,13 @@ class ObjectDB:
else:
raise
self.protect(cache_info)
self.state.save(cache_info, self.fs, hash_info)
try:
if verify:
self.check(hash_info, check_hash=True)
self.protect(cache_info)
self.state.save(cache_info, self.fs, hash_info)
except (ObjectFormatError, FileNotFoundError):
pass
callback = kwargs.get("download_callback")
if callback:
+137
View File
@@ -0,0 +1,137 @@
import logging
import os
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Iterable, Optional, Set
from ..errors import ObjectDBError
if TYPE_CHECKING:
from dvc.types import StrPath
logger = logging.getLogger(__name__)
class ObjectDBIndexBase(ABC):
@abstractmethod
def __init__(
self, tmp_dir: "StrPath", name: str, dir_suffix: Optional[str] = None
):
pass
@abstractmethod
def __iter__(self):
pass
@abstractmethod
def __contains__(self, hash_):
pass
def hashes(self):
return iter(self)
@abstractmethod
def dir_hashes(self):
pass
@abstractmethod
def clear(self):
pass
@abstractmethod
def update(self, dir_hashes: Iterable[str], file_hashes: Iterable[str]):
pass
@abstractmethod
def intersection(self, hashes: Set[str]):
pass
class ObjectDBIndexNoop(ObjectDBIndexBase):
"""No-op class for ODBs which are not indexed."""
def __init__(
self, tmp_dir: "StrPath", name: str, dir_suffix: Optional[str] = None
): # pylint: disable=super-init-not-called
pass
def __iter__(self):
return iter([])
def __contains__(self, hash_):
return False
def dir_hashes(self):
return []
def clear(self):
pass
def update(self, dir_hashes: Iterable[str], file_hashes: Iterable[str]):
pass
def intersection(self, hashes: Set[str]):
return []
class ObjectDBIndex(ObjectDBIndexBase):
"""Class for indexing hashes in an ODB."""
INDEX_SUFFIX = ".idx"
INDEX_DIR = "index"
def __init__(
self, tmp_dir: "StrPath", name: str, dir_suffix: Optional[str] = None
): # pylint: disable=super-init-not-called
from diskcache import Index
from dvc.fs.local import LocalFileSystem
from dvc.utils.fs import makedirs
self.index_dir = os.path.join(tmp_dir, self.INDEX_DIR, name)
makedirs(self.index_dir, exist_ok=True)
self.fs = LocalFileSystem()
self.index = Index(self.index_dir)
if not dir_suffix:
dir_suffix = self.fs.CHECKSUM_DIR_SUFFIX
self.dir_suffix = dir_suffix
def __iter__(self):
return iter(self.index)
def __contains__(self, hash_):
return hash_ in self.index
def dir_hashes(self):
"""Iterate over .dir hashes stored in the index."""
yield from (hash_ for hash_, is_dir in self.index.items() if is_dir)
def is_dir_hash(self, hash_: str):
return hash_.endswith(self.dir_suffix)
def clear(self):
"""Clear this index (to force re-indexing later)."""
from diskcache import Timeout
try:
self.index.clear()
except Timeout as exc:
raise ObjectDBError("Failed to clear ODB index") from exc
def update(self, dir_hashes: Iterable[str], file_hashes: Iterable[str]):
"""Update this index, adding the specified hashes."""
from diskcache import Timeout
try:
with self.index.transact():
for hash_ in dir_hashes:
self.index[hash_] = True
with self.index.transact():
for hash_ in file_hashes:
self.index[hash_] = False
except Timeout as exc:
raise ObjectDBError("Failed to update ODB index") from exc
def intersection(self, hashes: Set[str]):
"""Iterate over values from `hashes` which exist in the index."""
yield from hashes.intersection(self.index.keys())
+45
View File
@@ -0,0 +1,45 @@
# type: ignore
import logging
import sys
import time
from functools import wraps
import colorama
logger = logging.getLogger(__name__)
this = sys.modules[__name__]
this.timeout_seconds = 10.0
this.already_displayed = False
this.message = (
"You can cut execution time considerably by using a different "
"`cache.type` configuration.\n"
"See {blue}https://dvc.org/doc/commands-reference/config#cache{reset} "
"for more information.\n"
"To disable this message, run:\n"
"`dvc config cache.slow_link_warning false`".format(
blue=colorama.Fore.BLUE, reset=colorama.Fore.RESET
)
)
def slow_link_guard(f):
@wraps(f)
def wrapper(odb, *args, **kwargs):
if this.already_displayed:
return f(odb, *args, **kwargs)
if not odb.slow_link_warning or odb.cache_types:
return f(odb, *args, **kwargs)
start = time.time()
result = f(odb, *args, **kwargs)
delta = time.time() - start
if delta >= this.timeout_seconds:
logger.warning(this.message)
this.already_displayed = True
return result
return wrapper
+5
View File
@@ -195,6 +195,11 @@ def get_staging(odb: Optional["ObjectDB"] = None) -> "ObjectDB":
return get_odb(fs, path_info, **config)
def is_memfs_staging(odb: "ObjectDB"):
staging = get_staging()
return odb.fs == staging.fs and odb.path_info == staging.path_info
def _load_from_state(odb, staging, path_info, fs, name):
from . import load
from .errors import ObjectFormatError
+185
View File
@@ -0,0 +1,185 @@
import logging
from typing import TYPE_CHECKING, Dict, Iterable, NamedTuple, Optional, Set
from dvc.hash_info import HashInfo
from .tree import Tree
if TYPE_CHECKING:
from .db.base import ObjectDB
from .db.index import ObjectDBIndexBase
from .file import HashFile
logger = logging.getLogger(__name__)
class StatusResult(NamedTuple):
exists: Set["HashFile"]
missing: Set["HashFile"]
class CompareStatusResult(NamedTuple):
ok: Set["HashFile"]
missing: Set["HashFile"]
new: Set["HashFile"]
deleted: Set["HashFile"]
def _indexed_dir_hashes(odb, index, hash_infos, name, cache_odb):
from . import load
# Validate our index by verifying all indexed .dir hashes
# still exist on the remote
dir_hashes = {hash_info.value for hash_info in hash_infos}
indexed_dirs = set(index.dir_hashes())
indexed_dir_exists = set()
if indexed_dirs:
indexed_dir_exists.update(odb.list_hashes_exists(indexed_dirs))
missing_dirs = indexed_dirs.difference(indexed_dir_exists)
if missing_dirs:
logger.debug(
"Remote cache missing indexed .dir hashes '%s', "
"clearing remote index",
", ".join(missing_dirs),
)
index.clear()
# Check if non-indexed (new) dir hashes exist on remote
dir_exists = dir_hashes.intersection(indexed_dir_exists)
dir_exists.update(odb.list_hashes_exists(dir_hashes - dir_exists))
# If .dir hash exists in the ODB, assume directory contents
# also exists
for dir_hash in dir_exists:
try:
tree = load(cache_odb, HashInfo(name, dir_hash))
except FileNotFoundError:
continue
file_hashes = [entry.hash_info.value for _, entry in tree]
if dir_hash not in index:
logger.debug(
"Indexing new .dir '%s' with '%s' nested files",
dir_hash,
len(file_hashes),
)
index.update([dir_hash], file_hashes)
yield from file_hashes
yield tree.hash_info.value
def _status_staging(objs: Iterable["HashFile"]) -> "StatusResult":
exists: Set["HashFile"] = set()
for obj in objs:
if isinstance(obj, Tree):
exists.update(entry for _, entry in obj)
exists.add(obj)
return StatusResult(exists, set())
def status(
odb: "ObjectDB",
objs: Iterable["HashFile"],
name: Optional[str] = None,
index: Optional["ObjectDBIndexBase"] = None,
cache_odb: Optional["ObjectDB"] = None,
**kwargs,
) -> "StatusResult":
"""Return status of whether or not the specified objects exist odb.
If cache_odb is set, trees will be loaded from cache_odb instead of odb
when needed.
Status is returned as a tuple of:
exists: objs that exist in odb
missing: objs that do not exist in ODB
"""
from .stage import is_memfs_staging
logger.debug("Preparing to collect status from '%s'", odb.path_info)
if not name:
name = odb.fs.PARAM_CHECKSUM
if is_memfs_staging(odb):
# assume memfs staged objects already exist
return _status_staging(objs)
hash_objs: Dict[str, "HashFile"] = {}
hashes: Set[str] = set()
dir_infos: Set["HashInfo"] = set()
exists: Set[str] = set()
for obj in objs:
assert obj.hash_info and obj.hash_info.value
if isinstance(obj, Tree):
for _, entry in obj:
assert entry.hash_info and entry.hash_info.value
hash_objs[entry.hash_info.value] = entry
hashes.add(entry.hash_info.value)
if index:
dir_infos.add(obj.hash_info)
hashes.add(obj.hash_info.value)
hash_objs[obj.hash_info.value] = obj
logger.debug("Collecting status from '%s'", odb.path_info)
if index and hashes:
if dir_infos:
if cache_odb is None:
cache_odb = odb
exists = hashes.intersection(
_indexed_dir_hashes(odb, index, dir_infos, name, cache_odb)
)
hashes.difference_update(exists)
if hashes:
exists.update(index.intersection(hashes))
hashes.difference_update(exists)
if hashes:
exists.update(
odb.hashes_exist(hashes, name=str(odb.path_info), **kwargs)
)
return StatusResult(
{hash_objs[hash_] for hash_ in exists},
{hash_objs[hash_] for hash_ in (hashes - exists)},
)
def compare_status(
src: "ObjectDB",
dest: "ObjectDB",
objs: Iterable["HashFile"],
log_missing: bool = True,
check_deleted: bool = True,
src_index: Optional["ObjectDBIndexBase"] = None,
dest_index: Optional["ObjectDBIndexBase"] = None,
**kwargs,
) -> "CompareStatusResult":
"""Compare status for the specified objects between two ODBs.
Status is returned as a tuple of:
ok: hashes that exist in both src and dest
missing: hashes that do not exist in neither src nor dest
new: hashes that only exist in src
deleted: hashes that only exist in dest
"""
dest_exists, dest_missing = status(dest, objs, index=dest_index, **kwargs)
# for transfer operations we can skip src status check when all objects
# already exist in dest
if dest_missing or check_deleted:
src_exists, src_missing = status(src, objs, index=src_index, **kwargs)
else:
src_exists = dest_exists
src_missing = set()
result = CompareStatusResult(
src_exists & dest_exists,
src_missing & dest_missing,
src_exists - dest_exists,
dest_exists - src_exists,
)
if log_missing and result.missing:
missing_desc = "\n".join(
f"name: {obj.name}, {obj.hash_info}" for obj in result.missing
)
logger.warning(
"Some of the cache files do not exist neither locally "
f"nor on remote. Missing cache files:\n{missing_desc}"
)
return result
+218
View File
@@ -0,0 +1,218 @@
import errno
import itertools
import logging
from concurrent import futures
from concurrent.futures import ThreadPoolExecutor
from functools import partial, wraps
from typing import TYPE_CHECKING, Iterable, Optional, Set
from dvc.progress import Tqdm
from .file import HashFile
from .tree import Tree
if TYPE_CHECKING:
from .db.base import ObjectDB
from .db.index import ObjectDBIndexBase
logger = logging.getLogger(__name__)
def _log_exceptions(func):
@wraps(func)
def wrapper(odb, obj, *args, **kwargs):
try:
func(odb, obj, *args, **kwargs)
return 0
except Exception as exc: # pylint: disable=broad-except
# NOTE: this means we ran out of file descriptors and there is no
# reason to try to proceed, as we will hit this error anyways.
# pylint: disable=no-member
if isinstance(exc, OSError) and exc.errno == errno.EMFILE:
raise
logger.exception(
"failed to transfer '%s' to '%s'",
obj.path_info,
odb.get(obj.hash_info).path_info,
)
return 1
return wrapper
def _transfer(src, dest, dir_objs, file_objs, missing, jobs, **kwargs):
from . import save
from .stage import is_memfs_staging
is_staged = is_memfs_staging(src)
func = _log_exceptions(save)
total = len(dir_objs) + len(file_objs)
if total == 0:
return 0
with Tqdm(total=total, unit="file", desc="Transferring") as pbar:
func = pbar.wrap_fn(func)
with ThreadPoolExecutor(max_workers=jobs) as executor:
processor = partial(
_create_tasks, executor, jobs, func, src, dest, is_staged
)
processor.save_func = func
_do_transfer(
src,
dest,
dir_objs,
file_objs,
{obj.hash_info for obj in missing},
processor,
**kwargs,
)
return total
def _create_tasks(executor, jobs, func, src, dest, is_staged, objs):
fails = 0
obj_iter = iter(objs)
def create_taskset(amount):
return {
executor.submit(
func,
dest,
_raw_obj(src, obj, is_staged),
move=False,
verify=src.verify,
)
for obj in itertools.islice(obj_iter, amount)
}
tasks = create_taskset(jobs * 5)
while tasks:
done, tasks = futures.wait(tasks, return_when=futures.FIRST_COMPLETED)
fails += sum(task.result() for task in done)
tasks.update(create_taskset(len(done)))
return fails
def _raw_obj(odb, obj, is_staged=False):
if is_staged:
return HashFile(obj.path_info, obj.fs, obj.hash_info)
return odb.get(obj.hash_info)
def _do_transfer(
src,
dest,
dir_objs,
file_objs,
missing_hashes,
processor,
src_index: Optional["ObjectDBIndexBase"] = None,
dest_index: Optional["ObjectDBIndexBase"] = None,
**kwargs,
):
from dvc.exceptions import FileTransferError
total_fails = 0
succeeded_dir_objs = []
all_file_objs = set(file_objs)
for dir_obj in dir_objs:
bound_file_objs = set()
directory_hashes = {entry.hash_info for _, entry in dir_obj}
for file_obj in all_file_objs.copy():
if file_obj.hash_info in directory_hashes:
bound_file_objs.add(file_obj)
all_file_objs.remove(file_obj)
dir_fails = processor(bound_file_objs)
if dir_fails:
logger.debug(
"failed to upload full contents of '%s', "
"aborting .dir file upload",
dir_obj.name,
)
logger.error(
"failed to upload '%s' to '%s'",
src.get(dir_obj.hash_info).path_info,
dest.get(dir_obj.hash_info).path_info,
)
total_fails += dir_fails + 1
elif directory_hashes.intersection(missing_hashes):
# if for some reason a file contained in this dir is
# missing both locally and in the remote, we want to
# push whatever file content we have, but should not
# push .dir file
logger.debug(
"directory '%s' contains missing files,"
"skipping .dir file upload",
dir_obj.name,
)
else:
is_dir_failed = processor.save_func(
dest, src.get(dir_obj.hash_info), move=False
)
total_fails += is_dir_failed
if not is_dir_failed:
succeeded_dir_objs.append(dir_obj)
# insert the rest
total_fails += processor(all_file_objs)
if total_fails:
if src_index:
src_index.clear()
raise FileTransferError(total_fails)
# index successfully pushed dirs
if dest_index:
for dir_obj in succeeded_dir_objs:
file_hashes = {entry.hash_info.value for _, entry in dir_obj}
logger.debug(
"Indexing pushed dir '%s' with '%s' nested files",
dir_obj.hash_info,
len(file_hashes),
)
dest_index.update([dir_obj.hash_info.value], file_hashes)
def transfer(
src: "ObjectDB",
dest: "ObjectDB",
objs: Iterable["HashFile"],
jobs: Optional[int] = None,
**kwargs,
) -> int:
"""Transfer (copy) the specified objects from one ODB to another.
Returns the number of successfully transferred objects
"""
from .status import compare_status
logger.debug(
"Preparing to transfer data from '%s' to '%s'",
src.path_info,
dest.path_info,
)
status = compare_status(src, dest, objs, check_deleted=False, **kwargs)
if not status.new:
return 0
files: Set["HashFile"] = set()
dirs: Set["HashFile"] = set()
for obj in status.new:
if isinstance(obj, Tree):
dirs.add(obj)
else:
files.add(obj)
if jobs is None:
jobs = dest.fs.jobs
return _transfer(
src,
dest,
dirs,
files,
status.missing,
jobs,
**kwargs,
)
+2 -2
View File
@@ -1,7 +1,7 @@
import json
import logging
import posixpath
from typing import Optional, Tuple
from typing import Dict, Optional, Tuple
from funcy import cached_property
@@ -17,7 +17,7 @@ class Tree(HashFile):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._dict = {}
self._dict: Dict[Tuple[str], "HashFile"] = {}
@cached_property
def trie(self):