fs: detach state from fs (#5479)

We used to think this way, but state is not really an fs concept
(fsspec's dircache is though), as it is a cache of hashes of objects
that we are staging, and the hash doesn't depend on fs, as it is usually
computed by us by reading from fs.

Pre-requisite for diskcache-based state.
This commit is contained in:
Ruslan Kuprieiev
2021-02-16 17:42:50 +02:00
committed by GitHub
parent d28f5675b4
commit a814a49181
10 changed files with 62 additions and 50 deletions
+2 -2
View File
@@ -58,8 +58,8 @@ class CloudCache:
with fs.open(path_info, mode="rb") as fobj:
self.fs.upload_fobj(fobj, cache_info)
self.protect(cache_info)
with self.fs.state:
self.fs.state.save(cache_info, hash_info)
with self.fs.repo.state:
self.fs.repo.state.save(cache_info, self.fs, hash_info)
callback = kwargs.get("download_callback")
if callback:
+3 -3
View File
@@ -167,7 +167,7 @@ def _checkout_file(
_link(cache, cache_info, path_info)
modified = True
fs.state.save(path_info, obj.hash_info)
fs.repo.state.save(path_info, fs, obj.hash_info)
if progress_callback:
progress_callback(str(path_info))
@@ -217,7 +217,7 @@ def _checkout_dir(
or modified
)
fs.state.save(path_info, obj.hash_info)
fs.repo.state.save(path_info, fs, obj.hash_info)
# relink is not modified, assume it as nochange
return modified and not relink
@@ -241,7 +241,7 @@ def _checkout(
path_info, fs, obj, cache, force, progress_callback, relink,
)
fs.state.save_link(path_info)
fs.repo.state.save_link(path_info, fs)
return ret
-3
View File
@@ -9,7 +9,6 @@ from funcy import cached_property
from dvc.exceptions import DvcException
from dvc.path_info import URLInfo
from dvc.progress import Tqdm
from dvc.state import StateNoop
from dvc.utils import tmp_fname
from dvc.utils.fs import makedirs, move
from dvc.utils.http import open_url
@@ -55,8 +54,6 @@ class BaseFileSystem:
PARAM_CHECKSUM: ClassVar[Optional[str]] = None
DETAIL_FIELDS: FrozenSet[str] = frozenset()
state = StateNoop()
def __init__(self, repo, config):
self.repo = repo
self.config = config
-6
View File
@@ -33,12 +33,6 @@ class LocalFileSystem(BaseFileSystem):
def fs_root(self):
return self.config.get("url")
@property
def state(self):
from dvc.state import StateNoop
return self.repo.state if self.repo else StateNoop()
@cached_property
def dvcignore(self):
from dvc.ignore import DvcIgnoreFilter, DvcIgnoreFilterNoop
+1 -1
View File
@@ -171,7 +171,7 @@ class Tree(HashFile):
):
entry_obj = HashFile(entry_info, self.src_fs, entry_hash)
entry_obj.save(odb, **kwargs)
self.src_fs.state.save(self.src_path_info, hi)
self.src_fs.repo.state.save(self.src_path_info, self.src_fs, hi)
def filter(self, odb, prefix):
hash_info = self.hash_info.dir_info.trie.get(prefix)
+5 -5
View File
@@ -55,8 +55,8 @@ def _iter_hashes(path_info, fs, name, **kwargs):
file_infos = []
for file_info in fs.walk_files(path_info, **kwargs):
hash_info = fs.state.get( # pylint: disable=assignment-from-none
file_info
hash_info = fs.repo.state.get( # pylint: disable=assignment-from-none
file_info, fs,
)
if not hash_info:
file_infos.append(file_info)
@@ -108,9 +108,9 @@ def get_hash(path_info, fs, name, **kwargs):
errno.ENOENT, os.strerror(errno.ENOENT), path_info
)
with fs.state:
with fs.repo.state:
# pylint: disable=assignment-from-none
hash_info = fs.state.get(path_info)
hash_info = fs.repo.state.get(path_info, fs)
# If we have dir hash in state db, but dir cache file is lost,
# then we need to recollect the dir via .get_dir_hash() call below,
@@ -139,7 +139,7 @@ def get_hash(path_info, fs, name, **kwargs):
hash_info = get_file_hash(path_info, fs, name)
if hash_info and fs.exists(path_info):
fs.state.save(path_info, hash_info)
fs.repo.state.save(path_info, fs, hash_info)
return hash_info
+6 -4
View File
@@ -472,12 +472,12 @@ class Remote:
)
if self.fs.scheme == "local":
with self.fs.state:
with self.fs.repo.state:
for checksum in named_cache.scheme_keys("local"):
cache_file = self.cache.hash_to_path_info(checksum)
if self.fs.exists(cache_file):
hash_info = HashInfo(self.fs.PARAM_CHECKSUM, checksum)
self.fs.state.save(cache_file, hash_info)
self.fs.repo.state.save(cache_file, self.fs, hash_info)
self.cache.protect(cache_file)
return ret
@@ -493,7 +493,7 @@ class Remote:
)
if not self.cache.verify:
with cache.fs.state:
with cache.fs.repo.state:
for checksum in named_cache.scheme_keys("local"):
cache_file = cache.hash_to_path_info(checksum)
if cache.fs.exists(cache_file):
@@ -502,7 +502,9 @@ class Remote:
# during download will not be moved from tmp_file
# (see `BaseFileSystem.download()`)
hash_info = HashInfo(cache.fs.PARAM_CHECKSUM, checksum)
cache.fs.state.save(cache_file, hash_info)
cache.fs.repo.state.save(
cache_file, cache.fs, hash_info
)
cache.protect(cache_file)
return ret
+2 -2
View File
@@ -26,7 +26,7 @@ def _get_unused_links(repo):
for out in stage.outs
if out.scheme == "local"
]
return repo.state.get_unused_links(used)
return repo.state.get_unused_links(used, repo.fs)
def _fspath_dir(path):
@@ -95,7 +95,7 @@ def checkout(
unused = _get_unused_links(self)
stats["deleted"] = [_fspath_dir(u) for u in unused]
self.state.remove_links(unused)
self.state.remove_links(unused, self.fs)
if isinstance(targets, str):
targets = [targets]
+28 -12
View File
@@ -7,6 +7,7 @@ from abc import ABC, abstractmethod
from urllib.parse import urlencode, urlunparse
from dvc.exceptions import DvcException
from dvc.fs.local import LocalFileSystem
from dvc.hash_info import HashInfo
from dvc.utils import current_timestamp, relpath, to_chunks
from dvc.utils.fs import get_inode, get_mtime_and_size, remove
@@ -35,15 +36,15 @@ class StateBase(ABC):
self.count = 0
@abstractmethod
def save(self, path_info, hash_info):
def save(self, path_info, fs, hash_info):
pass
@abstractmethod
def get(self, path_info):
def get(self, path_info, fs):
pass
@abstractmethod
def save_link(self, path_info):
def save_link(self, path_info, fs):
pass
@abstractmethod
@@ -67,13 +68,13 @@ class StateBase(ABC):
class StateNoop(StateBase):
def save(self, path_info, hash_info):
def save(self, path_info, fs, hash_info):
pass
def get(self, path_info): # pylint: disable=unused-argument
def get(self, path_info, fs): # pylint: disable=unused-argument
return None
def save_link(self, path_info):
def save_link(self, path_info, fs):
pass
def load(self):
@@ -124,7 +125,6 @@ class State(StateBase): # pylint: disable=too-many-instance-attributes
MAX_UINT = 2 ** 64 - 2
def __init__(self, repo):
from dvc.fs.local import LocalFileSystem
super().__init__()
@@ -379,13 +379,17 @@ class State(StateBase): # pylint: disable=too-many-instance-attributes
return results[0]
return None
def save(self, path_info, hash_info):
def save(self, path_info, fs, hash_info):
"""Save hash for the specified path info.
Args:
path_info (dict): path_info to save hash for.
hash_info (HashInfo): hash to save.
"""
if not isinstance(fs, LocalFileSystem):
return
assert isinstance(path_info, str) or path_info.scheme == "local"
assert hash_info
assert isinstance(hash_info, HashInfo)
@@ -405,7 +409,7 @@ class State(StateBase): # pylint: disable=too-many-instance-attributes
actual_inode, actual_mtime, actual_size, hash_info.value
)
def get(self, path_info):
def get(self, path_info, fs):
"""Gets the hash for the specified path info. Hash will be
retrieved from the state database if available.
@@ -416,6 +420,9 @@ class State(StateBase): # pylint: disable=too-many-instance-attributes
HashInfo or None: hash for the specified path info or None if it
doesn't exist in the state database.
"""
if not isinstance(fs, LocalFileSystem):
return None
assert isinstance(path_info, str) or path_info.scheme == "local"
path = os.fspath(path_info)
@@ -439,13 +446,16 @@ class State(StateBase): # pylint: disable=too-many-instance-attributes
self._update_state_record_timestamp_for_inode(actual_inode)
return HashInfo("md5", value, size=int(actual_size))
def save_link(self, path_info):
def save_link(self, path_info, fs):
"""Adds the specified path to the list of links created by dvc. This
list is later used on `dvc checkout` to cleanup old links.
Args:
path_info (dict): path info to add to the list of links.
"""
if not isinstance(fs, LocalFileSystem):
return
assert isinstance(path_info, str) or path_info.scheme == "local"
if not self.fs.exists(path_info):
@@ -460,12 +470,15 @@ class State(StateBase): # pylint: disable=too-many-instance-attributes
)
self._execute(cmd, (relative_path, self._to_sqlite(inode), mtime))
def get_unused_links(self, used):
def get_unused_links(self, used, fs):
"""Removes all saved links except the ones that are used.
Args:
used (list): list of used links that should not be removed.
"""
if not isinstance(fs, LocalFileSystem):
return
unused = []
self._execute(f"SELECT * FROM {self.LINK_STATE_TABLE}")
@@ -486,7 +499,10 @@ class State(StateBase): # pylint: disable=too-many-instance-attributes
return unused
def remove_links(self, unused):
def remove_links(self, unused, fs):
if not isinstance(fs, LocalFileSystem):
return
for path in unused:
remove(path)
+15 -12
View File
@@ -17,18 +17,18 @@ def test_state(tmp_dir, dvc):
state = State(dvc)
with state:
state.save(path_info, hash_info)
assert state.get(path_info) == hash_info
state.save(path_info, dvc.fs, hash_info)
assert state.get(path_info, dvc.fs) == hash_info
path.unlink()
path.write_text("1")
assert state.get(path_info) is None
assert state.get(path_info, dvc.fs) is None
hash_info = HashInfo("md5", file_md5(path, dvc.fs))
state.save(path_info, hash_info)
state.save(path_info, dvc.fs, hash_info)
assert state.get(path_info) == hash_info
assert state.get(path_info, dvc.fs) == hash_info
def test_state_overflow(tmp_dir, dvc):
@@ -64,7 +64,7 @@ def test_get_state_record_for_inode(get_inode_mock, tmp_dir, dvc):
get_inode_mock.side_effect = mock_get_inode(inode)
with state:
state.save(PathInfo(foo), HashInfo("md5", md5))
state.save(PathInfo(foo), dvc.fs, HashInfo("md5", md5))
ret = state.get_state_record_for_inode(inode)
assert ret is not None
@@ -79,7 +79,7 @@ def test_remove_links(tmp_dir, dvc):
result = dvc.state._execute(cmd_count_links).fetchone()[0]
assert result == 2
dvc.state.remove_links(["foo", "bar"])
dvc.state.remove_links(["foo", "bar"], dvc.fs)
result = dvc.state._execute(cmd_count_links).fetchone()[0]
assert result == 0
@@ -90,12 +90,15 @@ def test_get_unused_links(tmp_dir, dvc):
with dvc.state:
links = [os.path.join(dvc.root_dir, link) for link in ["foo", "bar"]]
assert set(dvc.state.get_unused_links([])) == {"foo", "bar"}
assert set(dvc.state.get_unused_links(links[:1])) == {"bar"}
assert set(dvc.state.get_unused_links(links)) == set()
assert set(dvc.state.get_unused_links([], dvc.fs)) == {"foo", "bar"}
assert set(dvc.state.get_unused_links(links[:1], dvc.fs)) == {"bar"}
assert set(dvc.state.get_unused_links(links, dvc.fs)) == set()
assert set(
dvc.state.get_unused_links(
used=links[:1]
+ [os.path.join(dvc.root_dir, "not-existing-file")]
(
links[:1]
+ [os.path.join(dvc.root_dir, "not-existing-file")]
),
dvc.fs,
)
) == {"bar"}