PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
transport.py
Go to the documentation of this file.
1"""!
2@file transport.py
3@brief The rclone process boundary and remote object addressing.
4"""
5
6import argparse
7import base64
8import concurrent.futures
9import contextlib
10import datetime
11import errno
12import hashlib
13import json
14import os
15import re
16import shutil
17import socket
18import subprocess
19import sys
20import tarfile
21import tempfile
22import threading
23import uuid
24from pathlib import Path
25import yaml
26from .models import (
27 ARCHIVE_ID_PATTERN,
28 REMOTE_BLOBS_DIRECTORY,
29 REMOTE_COMPLETE_FILENAME,
30 REMOTE_MANIFEST_FILENAME,
31 REMOTE_OBJECTS_DIRECTORY,
32 STORAGE_SCHEMA_VERSION,
33 StorageError,
34 _sha256_file,
35)
36
37
38def _remote_join(remote: str, *parts: str) -> str:
39 """!
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.
44 """
45 clean_parts = [str(part).strip("/") for part in parts if str(part).strip("/")]
46 suffix = "/".join(clean_parts)
47 if not suffix:
48 return remote
49 if remote.endswith(":"):
50 return remote + suffix
51 return remote.rstrip("/") + "/" + suffix
52
53
54def _object_remote(profile: dict, archive_id: str, *parts: str) -> str:
55 """!
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.
61 """
62 return _remote_join(profile["remote"], REMOTE_OBJECTS_DIRECTORY, archive_id, *parts)
63
64
65def _blob_remote(profile: dict, digest: str) -> str:
66 """!
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.
71 """
72 return _remote_join(profile["remote"], REMOTE_BLOBS_DIRECTORY, digest[:2], digest)
73
74
75#: Remote blob directories this process has created, and the lock that serializes creating them.
76_CREATED_BLOB_DIRECTORIES = set()
77_BLOB_DIRECTORY_LOCK = threading.Lock()
78
79
80def _ensure_blob_directory(profile: dict, digest: str) -> None:
81 """!
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.
89 """
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)
95
96
97def _chunk_remote_path(profile: dict, archive_id: str, chunk: dict) -> str:
98 """!
99 @brief Resolve where one manifest chunk's payload lives on the remote.
100
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
105 actually loads.
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.
110 """
111 if chunk.get("blob"):
112 return _blob_remote(profile, chunk["sha256"])
113 return _object_remote(profile, archive_id, "chunks", chunk["name"])
114
115
116def _remote_blob_present(profile: dict, digest: str) -> bool:
117 """!
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.
122 """
123 try:
124 return _remote_sha256(_blob_remote(profile, digest)) == digest
125 except (StorageError, OSError):
126 # An absent blob is the normal case, not an error; anything else that stops us
127 # from confirming it is treated the same way, and the chunk is uploaded.
128 return False
129
130
131def _rclone_error_detail(text: str) -> str:
132 """!
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.
139 """
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)
144
145
146def _run_rclone(arguments: list, check: bool = True) -> subprocess.CompletedProcess:
147 """!
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.
152 """
153 executable = shutil.which("rclone")
154 if not executable:
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],
158 text=True,
159 capture_output=True,
160 check=False,
161 )
162 if check and result.returncode != 0:
163 detail = _rclone_error_detail(result.stderr or result.stdout or "unknown rclone error")
164 raise StorageError(f"rclone {' '.join(str(item) for item in arguments[:2])} failed: {detail}")
165 return result
166
167
168def _remote_sha256(remote_path: str) -> str:
169 """!
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.
173 """
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):
178 return token.lower()
179 raise StorageError(f"rclone did not return a SHA-256 for {remote_path}.")
180
181
182def _upload_verified(local_path: str, remote_path: str) -> dict:
183 """!
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.
188 """
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:
193 raise StorageError(
194 f"Remote checksum mismatch after upload: {remote_path} "
195 f"(local {local_digest}, remote {remote_digest})."
196 )
197 return {"sha256": local_digest, "stored_bytes": os.path.getsize(local_path)}
198
199
200#: rclone exit codes for a missing directory or file.
201_RCLONE_NOT_FOUND_CODES = (3, 4)
202
203
204def _read_remote_bytes(remote_path: str) -> bytes:
205 """!
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.
210 """
211 executable = shutil.which("rclone")
212 if not executable:
213 raise StorageError("rclone was not found on PATH.")
214 result = subprocess.run(
215 [executable, "cat", remote_path], capture_output=True, check=False
216 )
217 if result.returncode in _RCLONE_NOT_FOUND_CODES:
218 raise FileNotFoundError(remote_path)
219 if result.returncode != 0:
220 detail = _rclone_error_detail(
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}")
223 return result.stdout
224
225
226def _load_remote_manifest(profile: dict, archive_id: str, require_complete: bool = True) -> dict:
227 """!
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.
233 """
234 if not ARCHIVE_ID_PATTERN.fullmatch(str(archive_id)):
235 raise StorageError(f"Invalid archive ID: {archive_id!r}.")
236 try:
237 manifest_bytes = _read_remote_bytes(_object_remote(profile, archive_id, REMOTE_MANIFEST_FILENAME))
238 except FileNotFoundError:
239 raise StorageError(
240 f"No archive {archive_id} on {profile['remote']}; 'picurv storage list' shows the archives there."
241 ) from None
242 if require_complete:
243 try:
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.")
251 try:
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:
256 raise StorageError(
257 f"Archive {archive_id} uses unsupported storage schema "
258 f"{manifest.get('storage_schema_version') if isinstance(manifest, dict) else 'unknown'}."
259 )
260 return manifest
User-facing storage workflow failure.
Definition models.py:139
None _ensure_blob_directory(dict profile, str digest)
Create the directory a blob is stored in, once, before any upload into it.
Definition transport.py:80
str _rclone_error_detail(str text)
The lines of rclone output that report the failure.
Definition transport.py:131