3@brief The rclone process boundary and remote object addressing.
8import concurrent.futures
24from pathlib
import Path
28 REMOTE_BLOBS_DIRECTORY,
29 REMOTE_COMPLETE_FILENAME,
30 REMOTE_MANIFEST_FILENAME,
31 REMOTE_OBJECTS_DIRECTORY,
32 STORAGE_SCHEMA_VERSION,
38def _remote_join(remote: str, *parts: str) -> str:
40 @brief Join path components without corrupting rclone remote syntax.
41 @param[in] remote Value supplied through the `remote` argument.
42 @param[in] parts Value supplied through the `parts` argument.
43 @return Result produced by this operation.
45 clean_parts = [str(part).strip(
"/")
for part
in parts
if str(part).strip(
"/")]
46 suffix =
"/".join(clean_parts)
49 if remote.endswith(
":"):
50 return remote + suffix
51 return remote.rstrip(
"/") +
"/" + suffix
54def _object_remote(profile: dict, archive_id: str, *parts: str) -> str:
56 @brief Return the remote path for one immutable archive object.
57 @param[in] profile Value supplied through the `profile` argument.
58 @param[in] archive_id Value supplied through the `archive_id` argument.
59 @param[in] parts Value supplied through the `parts` argument.
60 @return Result produced by this operation.
62 return _remote_join(profile[
"remote"], REMOTE_OBJECTS_DIRECTORY, archive_id, *parts)
65def _blob_remote(profile: dict, digest: str) -> str:
67 @brief Return the remote path of one content-addressed payload blob.
68 @param[in] profile Active storage profile.
69 @param[in] digest Payload SHA-256.
70 @return Remote path, fanned out by digest prefix to keep directories small.
72 return _remote_join(profile[
"remote"], REMOTE_BLOBS_DIRECTORY, digest[:2], digest)
76_CREATED_BLOB_DIRECTORIES = set()
77_BLOB_DIRECTORY_LOCK = threading.Lock()
82 @brief Create the directory a blob is stored in, once, before any upload into it.
83 @details Google Drive allows several folders with one name. Parallel uploads that each
84 create a missing directory leave duplicates, and a later lookup by path sees
85 only one of them, so a stored blob reads as missing. Creating each directory
86 once, serially, gives every upload the same folder.
87 @param[in] profile Active storage profile.
88 @param[in] digest Payload SHA-256 whose blob directory is needed.
90 directory = _remote_join(profile[
"remote"], REMOTE_BLOBS_DIRECTORY, digest[:2])
91 with _BLOB_DIRECTORY_LOCK:
92 if directory
not in _CREATED_BLOB_DIRECTORIES:
93 _run_rclone([
"mkdir", directory])
94 _CREATED_BLOB_DIRECTORIES.add(directory)
97def _chunk_remote_path(profile: dict, archive_id: str, chunk: dict) -> str:
99 @brief Resolve where one manifest chunk's payload lives on the remote.
101 @details Every chunk this schema writes is blob-addressed, resolved out of the
102 shared content-addressed store. `_load_remote_manifest` already refuses
103 any manifest whose schema version does not match the current one, so a
104 non-blob chunk cannot reach this function from a manifest this build
106 @param[in] profile Active storage profile.
107 @param[in] archive_id Owning archive id.
108 @param[in] chunk Manifest chunk entry.
109 @return Remote path of the chunk payload.
111 if chunk.get(
"blob"):
112 return _blob_remote(profile, chunk[
"sha256"])
113 return _object_remote(profile, archive_id,
"chunks", chunk[
"name"])
116def _remote_blob_present(profile: dict, digest: str) -> bool:
118 @brief Whether a blob with this digest is already stored and intact.
119 @param[in] profile Active storage profile.
120 @param[in] digest Payload SHA-256.
121 @return True when the remote already holds exactly this content.
124 return _remote_sha256(_blob_remote(profile, digest)) == digest
125 except (StorageError, OSError):
133 @brief The lines of rclone output that report the failure.
134 @details rclone prints advisories, such as a shared client ID's deprecation, as NOTICE
135 lines ahead of the error, and reports some failures as NOTICE lines too
136 ("Failed to cat"), so the lines kept are those naming a failure or error.
137 @param[in] text rclone stderr or stdout.
138 @return The failure lines, else the non-NOTICE lines, else the whole text.
140 lines = [line
for line
in text.strip().splitlines()
if line.strip()]
141 failures = [line
for line
in lines
if re.search(
r"\bERROR\b|\bFailed\b|\berror\b", line)]
142 other = [line
for line
in lines
if " NOTICE: " not in line]
143 return "\n".join(failures
or other
or lines)
146def _run_rclone(arguments: list, check: bool =
True) -> subprocess.CompletedProcess:
148 @brief Invoke rclone through the same argv-based subprocess boundary as other PICurv tools.
149 @param[in] arguments Value supplied through the `arguments` argument.
150 @param[in] check Value supplied through the `check` argument.
151 @return Result produced by this operation.
153 executable = shutil.which(
"rclone")
155 raise StorageError(
"rclone was not found on PATH. Install/configure rclone before using PICurv storage.")
156 result = subprocess.run(
157 [executable] + [str(item)
for item
in arguments],
162 if check
and result.returncode != 0:
164 raise StorageError(f
"rclone {' '.join(str(item) for item in arguments[:2])} failed: {detail}")
168def _remote_sha256(remote_path: str) -> str:
170 @brief Ask rclone to calculate or retrieve the SHA-256 of one remote object.
171 @param[in] remote_path Value supplied through the `remote_path` argument.
172 @return Result produced by this operation.
174 result = _run_rclone([
"hashsum",
"SHA-256", remote_path])
175 for line
in result.stdout.splitlines():
176 token = line.strip().split(
None, 1)[0]
if line.strip()
else ""
177 if re.fullmatch(
r"[0-9a-fA-F]{64}", token):
179 raise StorageError(f
"rclone did not return a SHA-256 for {remote_path}.")
182def _upload_verified(local_path: str, remote_path: str) -> dict:
184 @brief Upload one file, then verify its remote SHA-256.
185 @param[in] local_path Value supplied through the `local_path` argument.
186 @param[in] remote_path Value supplied through the `remote_path` argument.
187 @return Result produced by this operation.
189 local_digest = _sha256_file(local_path)
190 _run_rclone([
"copyto", local_path, remote_path])
191 remote_digest = _remote_sha256(remote_path)
192 if remote_digest != local_digest:
194 f
"Remote checksum mismatch after upload: {remote_path} "
195 f
"(local {local_digest}, remote {remote_digest})."
197 return {
"sha256": local_digest,
"stored_bytes": os.path.getsize(local_path)}
201_RCLONE_NOT_FOUND_CODES = (3, 4)
204def _read_remote_bytes(remote_path: str) -> bytes:
206 @brief Read a small remote catalog object through rclone.
207 @param[in] remote_path Value supplied through the `remote_path` argument.
208 @return Result produced by this operation.
209 @throws FileNotFoundError when the object does not exist, so callers can name what is missing.
211 executable = shutil.which(
"rclone")
214 result = subprocess.run(
215 [executable,
"cat", remote_path], capture_output=
True, check=
False
217 if result.returncode
in _RCLONE_NOT_FOUND_CODES:
218 raise FileNotFoundError(remote_path)
219 if result.returncode != 0:
221 (result.stderr
or result.stdout
or b
"unknown rclone error").decode(
"utf-8",
"replace"))
222 raise StorageError(f
"Unable to read remote object {remote_path}: {detail}")
226def _load_remote_manifest(profile: dict, archive_id: str, require_complete: bool =
True) -> dict:
228 @brief Fetch and validate one versioned remote storage manifest.
229 @param[in] profile Value supplied through the `profile` argument.
230 @param[in] archive_id Value supplied through the `archive_id` argument.
231 @param[in] require_complete Value supplied through the `require_complete` argument.
232 @return Result produced by this operation.
234 if not ARCHIVE_ID_PATTERN.fullmatch(str(archive_id)):
235 raise StorageError(f
"Invalid archive ID: {archive_id!r}.")
237 manifest_bytes = _read_remote_bytes(_object_remote(profile, archive_id, REMOTE_MANIFEST_FILENAME))
238 except FileNotFoundError:
240 f
"No archive {archive_id} on {profile['remote']}; 'picurv storage list' shows the archives there."
244 complete = _read_remote_bytes(_object_remote(profile, archive_id, REMOTE_COMPLETE_FILENAME))
245 except FileNotFoundError:
246 raise StorageError(f
"Archive {archive_id} has no valid completion marker.")
from None
247 recorded = complete.decode(
"ascii",
"replace").strip().lower()
248 actual = hashlib.sha256(manifest_bytes).hexdigest()
249 if recorded != actual:
250 raise StorageError(f
"Archive {archive_id} has no valid completion marker.")
252 manifest = json.loads(manifest_bytes.decode(
"utf-8"))
253 except (UnicodeDecodeError, ValueError)
as exc:
254 raise StorageError(f
"Archive {archive_id} has an invalid manifest.")
from exc
255 if not isinstance(manifest, dict)
or manifest.get(
"storage_schema_version") != STORAGE_SCHEMA_VERSION:
257 f
"Archive {archive_id} uses unsupported storage schema "
258 f
"{manifest.get('storage_schema_version') if isinstance(manifest, dict) else 'unknown'}."
User-facing storage workflow failure.
None _ensure_blob_directory(dict profile, str digest)
Create the directory a blob is stored in, once, before any upload into it.
str _rclone_error_detail(str text)
The lines of rclone output that report the failure.