PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Functions | Variables
picurv_cli.storage.transport Namespace Reference

Functions

str _remote_join (str remote, *str parts)
 Join path components without corrupting rclone remote syntax.
 
str _object_remote (dict profile, str archive_id, *str parts)
 Return the remote path for one immutable archive object.
 
str _blob_remote (dict profile, str digest)
 Return the remote path of one content-addressed payload blob.
 
None _ensure_blob_directory (dict profile, str digest)
 Create the directory a blob is stored in, once, before any upload into it.
 
str _chunk_remote_path (dict profile, str archive_id, dict chunk)
 Resolve where one manifest chunk's payload lives on the remote.
 
bool _remote_blob_present (dict profile, str digest)
 Whether a blob with this digest is already stored and intact.
 
str _rclone_error_detail (str text)
 The lines of rclone output that report the failure.
 
subprocess.CompletedProcess _run_rclone (list arguments, bool check=True)
 Invoke rclone through the same argv-based subprocess boundary as other PICurv tools.
 
str _remote_sha256 (str remote_path)
 Ask rclone to calculate or retrieve the SHA-256 of one remote object.
 
dict _upload_verified (str local_path, str remote_path)
 Upload one file, then verify its remote SHA-256.
 
bytes _read_remote_bytes (str remote_path)
 Read a small remote catalog object through rclone.
 
dict _load_remote_manifest (dict profile, str archive_id, bool require_complete=True)
 Fetch and validate one versioned remote storage manifest.
 

Variables

 _CREATED_BLOB_DIRECTORIES = set()
 
 _BLOB_DIRECTORY_LOCK = threading.Lock()
 
tuple _RCLONE_NOT_FOUND_CODES = (3, 4)
 

Function Documentation

◆ _remote_join()

str picurv_cli.storage.transport._remote_join ( str  remote,
*str  parts 
)
protected

Join path components without corrupting rclone remote syntax.

Parameters
[in]remoteValue supplied through the remote argument.
[in]partsValue supplied through the parts argument.
Returns
Result produced by this operation.

Definition at line 38 of file transport.py.

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

◆ _object_remote()

str picurv_cli.storage.transport._object_remote ( dict  profile,
str  archive_id,
*str  parts 
)
protected

Return the remote path for one immutable archive object.

Parameters
[in]profileValue supplied through the profile argument.
[in]archive_idValue supplied through the archive_id argument.
[in]partsValue supplied through the parts argument.
Returns
Result produced by this operation.

Definition at line 54 of file transport.py.

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

◆ _blob_remote()

str picurv_cli.storage.transport._blob_remote ( dict  profile,
str  digest 
)
protected

Return the remote path of one content-addressed payload blob.

Parameters
[in]profileActive storage profile.
[in]digestPayload SHA-256.
Returns
Remote path, fanned out by digest prefix to keep directories small.

Definition at line 65 of file transport.py.

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.

◆ _ensure_blob_directory()

None picurv_cli.storage.transport._ensure_blob_directory ( dict  profile,
str  digest 
)
protected

Create the directory a blob is stored in, once, before any upload into it.

Google Drive allows several folders with one name. Parallel uploads that each create a missing directory leave duplicates, and a later lookup by path sees only one of them, so a stored blob reads as missing. Creating each directory once, serially, gives every upload the same folder.

Parameters
[in]profileActive storage profile.
[in]digestPayload SHA-256 whose blob directory is needed.

Definition at line 80 of file transport.py.

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

◆ _chunk_remote_path()

str picurv_cli.storage.transport._chunk_remote_path ( dict  profile,
str  archive_id,
dict  chunk 
)
protected

Resolve where one manifest chunk's payload lives on the remote.

Every chunk this schema writes is blob-addressed, resolved out of the shared content-addressed store. _load_remote_manifest already refuses any manifest whose schema version does not match the current one, so a non-blob chunk cannot reach this function from a manifest this build actually loads.

Parameters
[in]profileActive storage profile.
[in]archive_idOwning archive id.
[in]chunkManifest chunk entry.
Returns
Remote path of the chunk payload.

Definition at line 97 of file transport.py.

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

◆ _remote_blob_present()

bool picurv_cli.storage.transport._remote_blob_present ( dict  profile,
str  digest 
)
protected

Whether a blob with this digest is already stored and intact.

Parameters
[in]profileActive storage profile.
[in]digestPayload SHA-256.
Returns
True when the remote already holds exactly this content.

Definition at line 116 of file transport.py.

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

◆ _rclone_error_detail()

str picurv_cli.storage.transport._rclone_error_detail ( str  text)
protected

The lines of rclone output that report the failure.

rclone prints advisories, such as a shared client ID's deprecation, as NOTICE lines ahead of the error, and reports some failures as NOTICE lines too ("Failed to cat"), so the lines kept are those naming a failure or error.

Parameters
[in]textrclone stderr or stdout.
Returns
The failure lines, else the non-NOTICE lines, else the whole text.

Definition at line 131 of file transport.py.

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
Here is the caller graph for this function:

◆ _run_rclone()

subprocess.CompletedProcess picurv_cli.storage.transport._run_rclone ( list  arguments,
bool   check = True 
)
protected

Invoke rclone through the same argv-based subprocess boundary as other PICurv tools.

Parameters
[in]argumentsValue supplied through the arguments argument.
[in]checkValue supplied through the check argument.
Returns
Result produced by this operation.

Definition at line 146 of file transport.py.

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
Here is the call graph for this function:

◆ _remote_sha256()

str picurv_cli.storage.transport._remote_sha256 ( str  remote_path)
protected

Ask rclone to calculate or retrieve the SHA-256 of one remote object.

Parameters
[in]remote_pathValue supplied through the remote_path argument.
Returns
Result produced by this operation.

Definition at line 168 of file transport.py.

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

◆ _upload_verified()

dict picurv_cli.storage.transport._upload_verified ( str  local_path,
str  remote_path 
)
protected

Upload one file, then verify its remote SHA-256.

Parameters
[in]local_pathValue supplied through the local_path argument.
[in]remote_pathValue supplied through the remote_path argument.
Returns
Result produced by this operation.

Definition at line 182 of file transport.py.

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.

◆ _read_remote_bytes()

bytes picurv_cli.storage.transport._read_remote_bytes ( str  remote_path)
protected

Read a small remote catalog object through rclone.

Parameters
[in]remote_pathValue supplied through the remote_path argument.
Returns
Result produced by this operation.
Exceptions
FileNotFoundErrorwhen the object does not exist, so callers can name what is missing.

Definition at line 204 of file transport.py.

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
Here is the call graph for this function:

◆ _load_remote_manifest()

dict picurv_cli.storage.transport._load_remote_manifest ( dict  profile,
str  archive_id,
bool   require_complete = True 
)
protected

Fetch and validate one versioned remote storage manifest.

Parameters
[in]profileValue supplied through the profile argument.
[in]archive_idValue supplied through the archive_id argument.
[in]require_completeValue supplied through the require_complete argument.
Returns
Result produced by this operation.

Definition at line 226 of file transport.py.

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

Variable Documentation

◆ _CREATED_BLOB_DIRECTORIES

picurv_cli.storage.transport._CREATED_BLOB_DIRECTORIES = set()
protected

Definition at line 76 of file transport.py.

◆ _BLOB_DIRECTORY_LOCK

picurv_cli.storage.transport._BLOB_DIRECTORY_LOCK = threading.Lock()
protected

Definition at line 77 of file transport.py.

◆ _RCLONE_NOT_FOUND_CODES

tuple picurv_cli.storage.transport._RCLONE_NOT_FOUND_CODES = (3, 4)
protected

Definition at line 201 of file transport.py.