netherframe.backends.gcp 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- netherframe/backends/gcp/__init__.py +32 -0
- netherframe/backends/gcp/gcs.py +417 -0
- netherframe/backends/gcp/gcs_backend_bootstrap.py +104 -0
- netherframe/backends/gcp/py.typed +0 -0
- netherframe_backends_gcp-0.2.0.dist-info/METADATA +53 -0
- netherframe_backends_gcp-0.2.0.dist-info/RECORD +12 -0
- netherframe_backends_gcp-0.2.0.dist-info/WHEEL +4 -0
- netherframe_backends_gcp-0.2.0.dist-info/licenses/LICENSE +21 -0
- nf/backends/gcp/__init__.py +4 -0
- nf/backends/gcp/gcs.py +4 -0
- nf/backends/gcp/gcs_backend_bootstrap.py +4 -0
- nf/backends/gcp/py.typed +0 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Google Cloud Platform backend implementations for Netherframe."""
|
|
2
|
+
|
|
3
|
+
from netherframe.backends.gcp.gcs import GcsBackend, GcsStateBackend
|
|
4
|
+
from netherframe.backends.gcp.gcs_backend_bootstrap import (
|
|
5
|
+
GcsBackendBootstrapper,
|
|
6
|
+
GcsBackendResources,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"GcsBackend",
|
|
11
|
+
"GcsStateBackend",
|
|
12
|
+
"GcsBackendBootstrapper",
|
|
13
|
+
"GcsBackendResources",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
from netherframe.core.backends.backend_bootstrap import BackendBootstrapManager
|
|
17
|
+
from netherframe.core.backends.backend_registry import BackendRegistry
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _register_core_components() -> None:
|
|
21
|
+
"""Register GCS backend constructs and state backends."""
|
|
22
|
+
BackendBootstrapManager.register_bootstrapper("gcs", GcsBackendBootstrapper)
|
|
23
|
+
BackendRegistry.register_backend_construct("gcs", GcsBackend, "netherframe.backends.gcp")
|
|
24
|
+
BackendRegistry.register_state_backend("gcs", GcsStateBackend, "netherframe.backends.gcp")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_register_core_components()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def register_backends() -> None:
|
|
31
|
+
"""Register GCP backends. Called by entry points."""
|
|
32
|
+
_register_core_components()
|
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
"""Google Cloud Storage backend implementation for Terraform and native execution modes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from netherframe.core.serialization import orjson_compat as json
|
|
6
|
+
import subprocess
|
|
7
|
+
import time
|
|
8
|
+
from typing import TYPE_CHECKING, Any
|
|
9
|
+
|
|
10
|
+
from netherframe.core.backends.lock_heartbeat import LockHeartbeat
|
|
11
|
+
from netherframe.core.backends.document_state_backend import ABSENT, DocumentChangedError, DocumentStateBackend
|
|
12
|
+
from netherframe.core.constructs.backend_base import Backend
|
|
13
|
+
from netherframe.core.constructs.app_stack import Stack
|
|
14
|
+
from netherframe.core.exceptions import StateLockError
|
|
15
|
+
from netherframe.core.logging import get_logger
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from netherframe.core.backends.backend_bootstrap import BackendBootstrapper
|
|
19
|
+
from netherframe.core.constructs.framework_settings import BackendSettings
|
|
20
|
+
|
|
21
|
+
logger = get_logger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class GcsBackend(Backend):
|
|
25
|
+
"""Google Cloud Storage backend for Terraform state."""
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def backend_type(self) -> str:
|
|
29
|
+
"""Get the backend type name."""
|
|
30
|
+
return "gcs"
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
nf_scope: Stack,
|
|
35
|
+
*,
|
|
36
|
+
bucket: str,
|
|
37
|
+
prefix: str | None = None,
|
|
38
|
+
nf_backend_settings: BackendSettings | None = None,
|
|
39
|
+
**kwargs: Any,
|
|
40
|
+
) -> None:
|
|
41
|
+
"""Initialize GCS backend."""
|
|
42
|
+
super().__init__(
|
|
43
|
+
nf_scope=nf_scope,
|
|
44
|
+
nf_id="backend",
|
|
45
|
+
nf_backend_settings=nf_backend_settings,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
self.bucket = bucket
|
|
49
|
+
self.prefix = prefix
|
|
50
|
+
self.additional_config = kwargs
|
|
51
|
+
|
|
52
|
+
def _build_config(self) -> dict[str, Any]:
|
|
53
|
+
"""Build Terraform backend configuration."""
|
|
54
|
+
config: dict[str, Any] = {"bucket": self.bucket}
|
|
55
|
+
if self.prefix:
|
|
56
|
+
config["prefix"] = self.prefix
|
|
57
|
+
config.update(self.additional_config)
|
|
58
|
+
return config
|
|
59
|
+
|
|
60
|
+
def _to_config(self) -> dict[str, Any]:
|
|
61
|
+
"""Convert to Terraform backend configuration."""
|
|
62
|
+
return {"gcs": self._build_config()}
|
|
63
|
+
|
|
64
|
+
def get_state_resources(self) -> list[dict[str, Any]] | None:
|
|
65
|
+
"""Get resources from GCS state using terraform state pull."""
|
|
66
|
+
stack = self.nf_scope
|
|
67
|
+
if not isinstance(stack, Stack) or not stack.app:
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
try:
|
|
71
|
+
working_dir = f"{stack.app.outdir}/{stack.app.nf_id}/{stack.nf_id}"
|
|
72
|
+
result = subprocess.run(
|
|
73
|
+
["terraform", "state", "pull"],
|
|
74
|
+
cwd=working_dir,
|
|
75
|
+
capture_output=True,
|
|
76
|
+
text=True,
|
|
77
|
+
check=True,
|
|
78
|
+
)
|
|
79
|
+
state = json.loads(result.stdout)
|
|
80
|
+
return state.get("resources", [])
|
|
81
|
+
|
|
82
|
+
except subprocess.CalledProcessError, json.JSONDecodeError, FileNotFoundError:
|
|
83
|
+
pass
|
|
84
|
+
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
def get_bootstrapper(self) -> BackendBootstrapper | None:
|
|
88
|
+
"""Return a GCS backend bootstrapper if possible."""
|
|
89
|
+
from netherframe.backends.gcp.gcs_backend_bootstrap import GcsBackendBootstrapper
|
|
90
|
+
|
|
91
|
+
additional = getattr(self, "additional_config", {})
|
|
92
|
+
return GcsBackendBootstrapper(
|
|
93
|
+
bucket_name=self.bucket,
|
|
94
|
+
project=additional.get("project"),
|
|
95
|
+
credentials=additional.get("credentials"),
|
|
96
|
+
location=additional.get("location"),
|
|
97
|
+
storage_class=additional.get("storage_class"),
|
|
98
|
+
labels=additional.get("labels"),
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class GcsStateBackend(DocumentStateBackend):
|
|
103
|
+
"""Google Cloud Storage-based state backend.
|
|
104
|
+
|
|
105
|
+
Compatible with Terraform's gcs backend.
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
storage_name = "GCS"
|
|
109
|
+
state_logger = logger
|
|
110
|
+
|
|
111
|
+
def __init__(
|
|
112
|
+
self,
|
|
113
|
+
bucket: str,
|
|
114
|
+
prefix: str,
|
|
115
|
+
credentials: str | None = None,
|
|
116
|
+
project: str | None = None,
|
|
117
|
+
) -> None:
|
|
118
|
+
"""Initialize GCS state backend.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
bucket: GCS bucket name
|
|
122
|
+
prefix: Object prefix/path
|
|
123
|
+
credentials: Path to service account JSON file
|
|
124
|
+
project: GCP project ID
|
|
125
|
+
|
|
126
|
+
"""
|
|
127
|
+
self.bucket = bucket
|
|
128
|
+
self.prefix = prefix
|
|
129
|
+
self.project = project
|
|
130
|
+
self._lock_state: dict[str, Any] | None = None
|
|
131
|
+
self._heartbeat: LockHeartbeat | None = None
|
|
132
|
+
|
|
133
|
+
# Import GCS SDK
|
|
134
|
+
try:
|
|
135
|
+
from google.cloud import storage
|
|
136
|
+
|
|
137
|
+
# Create client
|
|
138
|
+
if credentials:
|
|
139
|
+
self.client = storage.Client.from_service_account_json(
|
|
140
|
+
credentials,
|
|
141
|
+
project=project,
|
|
142
|
+
)
|
|
143
|
+
else:
|
|
144
|
+
self.client = storage.Client(project=project)
|
|
145
|
+
|
|
146
|
+
# Get bucket
|
|
147
|
+
self.bucket_obj = self.client.bucket(bucket)
|
|
148
|
+
|
|
149
|
+
except ImportError as e:
|
|
150
|
+
raise RuntimeError(
|
|
151
|
+
"Google Cloud Storage SDK is required for gcs backend. Install with: pip install google-cloud-storage",
|
|
152
|
+
) from e
|
|
153
|
+
|
|
154
|
+
def _state_uri(self) -> str:
|
|
155
|
+
"""Return the GCS URI for the state object."""
|
|
156
|
+
return f"gs://{self.bucket}/{self.prefix}"
|
|
157
|
+
|
|
158
|
+
def _state_blob(self) -> Any:
|
|
159
|
+
"""Return the GCS blob used for state storage."""
|
|
160
|
+
return self.bucket_obj.blob(self.prefix)
|
|
161
|
+
|
|
162
|
+
def _lock_blob(self) -> Any:
|
|
163
|
+
"""Return the GCS blob used for state locking."""
|
|
164
|
+
return self.bucket_obj.blob(f"{self.prefix}.lock")
|
|
165
|
+
|
|
166
|
+
def _state_location(self) -> str:
|
|
167
|
+
"""Return the GCS URI of the state object."""
|
|
168
|
+
return self._state_uri()
|
|
169
|
+
|
|
170
|
+
def state_identity(self) -> dict[str, Any]:
|
|
171
|
+
return {"backend": "gcs", "endpoint": self.bucket_obj.client._connection.API_BASE_URL, "bucket": self.bucket_obj.name, "key": self.prefix}
|
|
172
|
+
|
|
173
|
+
#: Reads retried when the object is replaced between reading its generation and its content
|
|
174
|
+
READ_ATTEMPTS = 5
|
|
175
|
+
|
|
176
|
+
def _read_document(self) -> tuple[bytes | None, Any]:
|
|
177
|
+
"""Download the state object with its generation, or return (None, ABSENT) if it does not exist."""
|
|
178
|
+
from google.api_core.exceptions import NotFound, PreconditionFailed
|
|
179
|
+
|
|
180
|
+
blob = self._state_blob()
|
|
181
|
+
for _attempt in range(self.READ_ATTEMPTS):
|
|
182
|
+
try:
|
|
183
|
+
blob.reload()
|
|
184
|
+
except NotFound:
|
|
185
|
+
return None, ABSENT
|
|
186
|
+
generation = blob.generation
|
|
187
|
+
try:
|
|
188
|
+
# The content of exactly that generation, so the pair is consistent
|
|
189
|
+
return blob.download_as_bytes(if_generation_match=generation), generation
|
|
190
|
+
except NotFound, PreconditionFailed:
|
|
191
|
+
continue
|
|
192
|
+
raise RuntimeError(f"State at {self._state_uri()} kept changing while it was read")
|
|
193
|
+
|
|
194
|
+
def _write_document(self, data: bytes, if_token: Any = None) -> Any:
|
|
195
|
+
"""Upload the state object; with a token, only while the stored object is that generation."""
|
|
196
|
+
from google.api_core.exceptions import PreconditionFailed
|
|
197
|
+
|
|
198
|
+
blob = self._state_blob()
|
|
199
|
+
precondition = {} if if_token is None else {"if_generation_match": 0 if if_token is ABSENT else if_token}
|
|
200
|
+
try:
|
|
201
|
+
blob.upload_from_string(data, content_type="application/json", **precondition)
|
|
202
|
+
except PreconditionFailed as e:
|
|
203
|
+
raise DocumentChangedError(str(e)) from e
|
|
204
|
+
return blob.generation
|
|
205
|
+
|
|
206
|
+
def _checkpoint_blob_name(self, name: str) -> str:
|
|
207
|
+
return f"{self.prefix}.checkpoints/{name}"
|
|
208
|
+
|
|
209
|
+
def _checkpoint_location(self, name: str) -> str:
|
|
210
|
+
return f"gs://{self.bucket}/{self._checkpoint_blob_name(name)}"
|
|
211
|
+
|
|
212
|
+
def _write_checkpoint(self, name: str, data: bytes) -> None:
|
|
213
|
+
self.bucket_obj.blob(self._checkpoint_blob_name(name)).upload_from_string(data, content_type="application/json")
|
|
214
|
+
|
|
215
|
+
def _read_checkpoint(self, name: str) -> bytes | None:
|
|
216
|
+
from google.api_core.exceptions import NotFound
|
|
217
|
+
|
|
218
|
+
try:
|
|
219
|
+
return self.bucket_obj.blob(self._checkpoint_blob_name(name)).download_as_bytes()
|
|
220
|
+
except NotFound:
|
|
221
|
+
return None
|
|
222
|
+
|
|
223
|
+
def _checkpoint_names(self) -> list[str]:
|
|
224
|
+
prefix = self._checkpoint_blob_name("")
|
|
225
|
+
return [blob.name.removeprefix(prefix) for blob in self.bucket_obj.list_blobs(prefix=prefix)]
|
|
226
|
+
|
|
227
|
+
def _delete_checkpoint(self, name: str) -> None:
|
|
228
|
+
from google.api_core.exceptions import NotFound
|
|
229
|
+
|
|
230
|
+
try:
|
|
231
|
+
self.bucket_obj.blob(self._checkpoint_blob_name(name)).delete()
|
|
232
|
+
except NotFound:
|
|
233
|
+
pass
|
|
234
|
+
|
|
235
|
+
LOCK_HEARTBEAT_SECONDS: float = 30
|
|
236
|
+
LOCK_STALE_SECONDS: float = 300
|
|
237
|
+
|
|
238
|
+
def lock(self, info: dict[str, Any]) -> bool:
|
|
239
|
+
"""Acquire state lock using a lock object created atomically.
|
|
240
|
+
|
|
241
|
+
The holder rewrites the lock object periodically; a lock whose heartbeat has
|
|
242
|
+
stopped for LOCK_STALE_SECONDS belongs to a crashed run and may be taken over.
|
|
243
|
+
|
|
244
|
+
A write of the lock object can land while its answer is lost, and the client's retry is
|
|
245
|
+
then refused (the object is no longer the generation it expects): a refused create,
|
|
246
|
+
renewal or delete first checks whether the lock object is this lock's own, and goes on
|
|
247
|
+
with its generation if so.
|
|
248
|
+
"""
|
|
249
|
+
from google.api_core.exceptions import PreconditionFailed
|
|
250
|
+
|
|
251
|
+
lock_blob = self._lock_blob()
|
|
252
|
+
now = time.time()
|
|
253
|
+
payload = {**info, "created": now, "heartbeat": now}
|
|
254
|
+
|
|
255
|
+
try:
|
|
256
|
+
for _attempt in range(2):
|
|
257
|
+
try:
|
|
258
|
+
# if_generation_match=0: create only if no lock object exists
|
|
259
|
+
lock_blob.upload_from_string(json.dumps(payload), content_type="application/json", if_generation_match=0)
|
|
260
|
+
generation = lock_blob.generation
|
|
261
|
+
break
|
|
262
|
+
except PreconditionFailed:
|
|
263
|
+
if (generation := self._own_lock_generation(payload)) is not None:
|
|
264
|
+
break
|
|
265
|
+
if not self._remove_stale_lock(lock_blob):
|
|
266
|
+
return False
|
|
267
|
+
else:
|
|
268
|
+
return False
|
|
269
|
+
|
|
270
|
+
self._lock_state = {"blob": lock_blob, "generation": generation, "payload": payload}
|
|
271
|
+
self._heartbeat = LockHeartbeat(self._renew_lock, self.LOCK_HEARTBEAT_SECONDS, name=self._state_uri()).start()
|
|
272
|
+
logger.info("State lock acquired")
|
|
273
|
+
return True
|
|
274
|
+
|
|
275
|
+
except Exception as e:
|
|
276
|
+
logger.error("Failed to acquire lock: %s", e)
|
|
277
|
+
return False
|
|
278
|
+
|
|
279
|
+
def _remove_stale_lock(self, lock_blob: Any) -> bool:
|
|
280
|
+
"""Delete the existing lock if its holder stopped heartbeating. Returns whether to retry."""
|
|
281
|
+
from google.api_core.exceptions import NotFound, PreconditionFailed
|
|
282
|
+
|
|
283
|
+
try:
|
|
284
|
+
lock_blob.reload()
|
|
285
|
+
lock_data = json.loads(lock_blob.download_as_text(if_generation_match=lock_blob.generation))
|
|
286
|
+
except NotFound, PreconditionFailed:
|
|
287
|
+
return True # released or replaced meanwhile; try to create again
|
|
288
|
+
|
|
289
|
+
last_heartbeat = lock_data.get("heartbeat", lock_data.get("created", 0))
|
|
290
|
+
if time.time() - last_heartbeat <= self.LOCK_STALE_SECONDS:
|
|
291
|
+
logger.error("State is locked: %s", lock_data)
|
|
292
|
+
return False
|
|
293
|
+
|
|
294
|
+
logger.warning("Removing stale lock file (no heartbeat for %ss)", int(time.time() - last_heartbeat))
|
|
295
|
+
try:
|
|
296
|
+
# Only delete the exact lock object we judged stale
|
|
297
|
+
lock_blob.delete(if_generation_match=lock_blob.generation)
|
|
298
|
+
except NotFound, PreconditionFailed:
|
|
299
|
+
pass
|
|
300
|
+
return True
|
|
301
|
+
|
|
302
|
+
def _own_lock_generation(self, payload: dict[str, Any]) -> int | None:
|
|
303
|
+
"""The lock object's generation when it is the lock ``payload`` describes (its ID and creation time), else None."""
|
|
304
|
+
lock = self._read_lock()
|
|
305
|
+
if lock is None:
|
|
306
|
+
return None
|
|
307
|
+
info, generation = lock
|
|
308
|
+
return generation if (info.get("ID"), info.get("created")) == (payload.get("ID"), payload.get("created")) else None
|
|
309
|
+
|
|
310
|
+
def _renew_lock(self) -> None:
|
|
311
|
+
"""Rewrite our lock object so other processes see a live heartbeat."""
|
|
312
|
+
from google.api_core.exceptions import PreconditionFailed
|
|
313
|
+
|
|
314
|
+
lock_state = self._lock_state
|
|
315
|
+
if lock_state is None:
|
|
316
|
+
return
|
|
317
|
+
lock_blob = lock_state["blob"]
|
|
318
|
+
lock_state["payload"]["heartbeat"] = time.time()
|
|
319
|
+
try:
|
|
320
|
+
lock_blob.upload_from_string(
|
|
321
|
+
json.dumps(lock_state["payload"]),
|
|
322
|
+
content_type="application/json",
|
|
323
|
+
if_generation_match=lock_state["generation"],
|
|
324
|
+
)
|
|
325
|
+
except PreconditionFailed:
|
|
326
|
+
generation = self._own_lock_generation(lock_state["payload"])
|
|
327
|
+
if generation is None:
|
|
328
|
+
raise
|
|
329
|
+
# An earlier renewal (or this one) landed without its answer: renewed again next time
|
|
330
|
+
lock_state["generation"] = generation
|
|
331
|
+
return
|
|
332
|
+
lock_state["generation"] = lock_blob.generation
|
|
333
|
+
|
|
334
|
+
def unlock(self) -> None:
|
|
335
|
+
"""Release state lock."""
|
|
336
|
+
from google.api_core.exceptions import NotFound, PreconditionFailed
|
|
337
|
+
|
|
338
|
+
if self._heartbeat is not None:
|
|
339
|
+
self._heartbeat.stop()
|
|
340
|
+
self._heartbeat = None
|
|
341
|
+
lock_state, self._lock_state = self._lock_state, None
|
|
342
|
+
if lock_state is None:
|
|
343
|
+
return
|
|
344
|
+
try:
|
|
345
|
+
try:
|
|
346
|
+
lock_state["blob"].delete(if_generation_match=lock_state["generation"])
|
|
347
|
+
except PreconditionFailed:
|
|
348
|
+
generation = self._own_lock_generation(lock_state["payload"])
|
|
349
|
+
if generation is None:
|
|
350
|
+
raise
|
|
351
|
+
lock_state["blob"].delete(if_generation_match=generation)
|
|
352
|
+
logger.info("State lock released")
|
|
353
|
+
except NotFound:
|
|
354
|
+
pass
|
|
355
|
+
except Exception as e:
|
|
356
|
+
logger.error("Failed to release lock: %s", e)
|
|
357
|
+
|
|
358
|
+
can_force_unlock = True
|
|
359
|
+
|
|
360
|
+
def _read_lock(self) -> tuple[dict[str, Any], int] | None:
|
|
361
|
+
"""The lock object's content and generation, or None when state is not locked."""
|
|
362
|
+
from google.api_core.exceptions import NotFound, PreconditionFailed
|
|
363
|
+
|
|
364
|
+
lock_blob = self._lock_blob()
|
|
365
|
+
for _attempt in range(self.READ_ATTEMPTS):
|
|
366
|
+
try:
|
|
367
|
+
lock_blob.reload()
|
|
368
|
+
generation = lock_blob.generation
|
|
369
|
+
return json.loads(lock_blob.download_as_bytes(if_generation_match=generation)), generation
|
|
370
|
+
except NotFound:
|
|
371
|
+
return None
|
|
372
|
+
except PreconditionFailed:
|
|
373
|
+
continue
|
|
374
|
+
raise RuntimeError(f"The lock of {self._state_uri()} kept changing while it was read")
|
|
375
|
+
|
|
376
|
+
def current_lock(self) -> dict[str, Any] | None:
|
|
377
|
+
"""The info of the lock held on this state, or None."""
|
|
378
|
+
lock = self._read_lock()
|
|
379
|
+
return lock[0] if lock is not None else None
|
|
380
|
+
|
|
381
|
+
def force_unlock(self, lock_id: str) -> None:
|
|
382
|
+
"""Delete the lock object, only while it is the lock ``lock_id``."""
|
|
383
|
+
from google.api_core.exceptions import NotFound, PreconditionFailed
|
|
384
|
+
|
|
385
|
+
lock = self._read_lock()
|
|
386
|
+
if lock is None:
|
|
387
|
+
raise StateLockError(f"State at {self._state_uri()} is not locked")
|
|
388
|
+
info, generation = lock
|
|
389
|
+
if str(info.get("ID")) != lock_id:
|
|
390
|
+
raise StateLockError(f"State at {self._state_uri()} is locked by lock {info.get('ID')}, not {lock_id}")
|
|
391
|
+
try:
|
|
392
|
+
self._lock_blob().delete(if_generation_match=generation)
|
|
393
|
+
except (NotFound, PreconditionFailed) as e:
|
|
394
|
+
raise StateLockError(f"State at {self._state_uri()} is no longer locked by lock {lock_id}") from e
|
|
395
|
+
logger.warning("Released state lock %s of %s", lock_id, info)
|
|
396
|
+
|
|
397
|
+
def get_backend_type(self) -> str:
|
|
398
|
+
"""Get the backend type identifier."""
|
|
399
|
+
return "gcs"
|
|
400
|
+
|
|
401
|
+
def get_config(self) -> dict[str, Any]:
|
|
402
|
+
"""Get the backend configuration.
|
|
403
|
+
|
|
404
|
+
Returns the complete configuration needed to recreate this backend.
|
|
405
|
+
"""
|
|
406
|
+
config = {
|
|
407
|
+
"bucket": self.bucket,
|
|
408
|
+
"prefix": self.prefix,
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
if self.project:
|
|
412
|
+
config["project"] = self.project
|
|
413
|
+
|
|
414
|
+
# Note: We don't include credentials path as it may contain sensitive info
|
|
415
|
+
# and the backend can be recreated with default credentials
|
|
416
|
+
|
|
417
|
+
return config
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""GCS backend bootstrapping implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import cast, Protocol
|
|
7
|
+
|
|
8
|
+
from netherframe.core.backends.backend_bootstrap import BackendBootstrapper, BackendResources
|
|
9
|
+
from netherframe.core.logging import get_logger
|
|
10
|
+
|
|
11
|
+
logger = get_logger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class GcsBucket(Protocol):
|
|
15
|
+
"""Minimal GCS bucket interface used by the bootstrapper."""
|
|
16
|
+
|
|
17
|
+
location: str
|
|
18
|
+
storage_class: str
|
|
19
|
+
labels: dict[str, str]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class GcsStorageClient(Protocol):
|
|
23
|
+
"""Minimal GCS storage client interface used by the bootstrapper."""
|
|
24
|
+
|
|
25
|
+
def lookup_bucket(self, bucket_name: str) -> GcsBucket | None: ...
|
|
26
|
+
def bucket(self, bucket_name: str) -> GcsBucket: ...
|
|
27
|
+
def create_bucket(self, bucket: GcsBucket) -> GcsBucket: ...
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class GcsBackendResources(BackendResources):
|
|
32
|
+
"""GCS backend resources information."""
|
|
33
|
+
|
|
34
|
+
bucket_name: str | None = None
|
|
35
|
+
bucket_url: str | None = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class GcsBackendBootstrapper(BackendBootstrapper):
|
|
39
|
+
"""Bootstrap GCS backend resources (bucket)."""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
*,
|
|
44
|
+
bucket_name: str,
|
|
45
|
+
project: str | None = None,
|
|
46
|
+
credentials: str | None = None,
|
|
47
|
+
location: str | None = None,
|
|
48
|
+
storage_class: str | None = None,
|
|
49
|
+
labels: dict[str, str] | None = None,
|
|
50
|
+
) -> None:
|
|
51
|
+
self.bucket_name = bucket_name
|
|
52
|
+
self.project = project
|
|
53
|
+
self.credentials = credentials
|
|
54
|
+
self.location = location
|
|
55
|
+
self.storage_class = storage_class
|
|
56
|
+
self.labels = labels or {}
|
|
57
|
+
self._resources = GcsBackendResources()
|
|
58
|
+
|
|
59
|
+
def _create_client(self) -> GcsStorageClient:
|
|
60
|
+
try:
|
|
61
|
+
from google.cloud import storage
|
|
62
|
+
except ImportError as exc: # pragma: no cover - depends on optional deps
|
|
63
|
+
raise RuntimeError(
|
|
64
|
+
"google-cloud-storage is required for GCS bootstrapping. Install with: pip install google-cloud-storage",
|
|
65
|
+
) from exc
|
|
66
|
+
|
|
67
|
+
if self.credentials:
|
|
68
|
+
return cast(
|
|
69
|
+
"GcsStorageClient",
|
|
70
|
+
storage.Client.from_service_account_json(
|
|
71
|
+
self.credentials,
|
|
72
|
+
project=self.project,
|
|
73
|
+
),
|
|
74
|
+
)
|
|
75
|
+
return cast("GcsStorageClient", storage.Client(project=self.project))
|
|
76
|
+
|
|
77
|
+
def validate(self) -> bool:
|
|
78
|
+
"""Validate that the bucket exists."""
|
|
79
|
+
client = self._create_client()
|
|
80
|
+
bucket = client.lookup_bucket(self.bucket_name)
|
|
81
|
+
if bucket is None:
|
|
82
|
+
return False
|
|
83
|
+
self._resources.bucket_name = self.bucket_name
|
|
84
|
+
self._resources.bucket_url = f"gs://{self.bucket_name}"
|
|
85
|
+
return True
|
|
86
|
+
|
|
87
|
+
def bootstrap(self) -> BackendResources:
|
|
88
|
+
"""Create the bucket if missing."""
|
|
89
|
+
client = self._create_client()
|
|
90
|
+
bucket = client.lookup_bucket(self.bucket_name)
|
|
91
|
+
if bucket is None:
|
|
92
|
+
logger.info("Creating GCS bucket: %s", self.bucket_name)
|
|
93
|
+
bucket = client.bucket(self.bucket_name)
|
|
94
|
+
if self.location:
|
|
95
|
+
bucket.location = self.location
|
|
96
|
+
if self.storage_class:
|
|
97
|
+
bucket.storage_class = self.storage_class
|
|
98
|
+
if self.labels:
|
|
99
|
+
bucket.labels = dict(self.labels)
|
|
100
|
+
bucket = client.create_bucket(bucket)
|
|
101
|
+
|
|
102
|
+
self._resources.bucket_name = self.bucket_name
|
|
103
|
+
self._resources.bucket_url = f"gs://{self.bucket_name}"
|
|
104
|
+
return self._resources
|
|
File without changes
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: netherframe.backends.gcp
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Google Cloud Platform backend implementations for Netherframe
|
|
5
|
+
Author: Sourabh Cheedella
|
|
6
|
+
Author-email: Sourabh Cheedella <cheedella.sourabh@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
12
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
13
|
+
Classifier: Topic :: System :: Systems Administration
|
|
14
|
+
Requires-Dist: netherframe-core>=0.9.0
|
|
15
|
+
Requires-Dist: google-cloud-storage>=3.17.1
|
|
16
|
+
Requires-Dist: pytest>=9.2.0 ; extra == 'dev'
|
|
17
|
+
Requires-Python: >=3.14
|
|
18
|
+
Project-URL: Homepage, https://netherframe.arsenal.sh
|
|
19
|
+
Project-URL: Repository, https://github.com/arsenal-sh/netherframe
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# nf.backends.gcp
|
|
24
|
+
|
|
25
|
+
Google Cloud Platform backend implementations for Netherframe Infrastructure as Code framework.
|
|
26
|
+
|
|
27
|
+
## Installation
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install netherframe.backends.gcp
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Usage
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from nf.backends.gcp import GcsBackend, GcsStateBackend
|
|
37
|
+
|
|
38
|
+
# For Terraform synthesis mode
|
|
39
|
+
backend = GcsBackend(nf_scope=stack, bucket="my-terraform-state", prefix="infrastructure/terraform.tfstate")
|
|
40
|
+
|
|
41
|
+
# For native execution mode
|
|
42
|
+
state_backend = GcsStateBackend(bucket="my-terraform-state", prefix="infrastructure/terraform.tfstate", project="my-gcp-project")
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Features
|
|
46
|
+
|
|
47
|
+
- Google Cloud Storage-based state storage
|
|
48
|
+
- Compatible with Terraform's gcs backend
|
|
49
|
+
- Support for service account authentication
|
|
50
|
+
- State locking using lock files
|
|
51
|
+
- Automatic stale lock detection and cleanup, and force-unlock by lock ID (`nf state force-unlock`)
|
|
52
|
+
- Conditional writes: a write replaces only the state version its run read (generation match)
|
|
53
|
+
- Pre-apply checkpoints kept beside the state (`<prefix>.checkpoints/`)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
netherframe/backends/gcp/__init__.py,sha256=LS0DZAy16JupZOElC43tMKSf1Yxvc1ZWajFKgvhlXgQ,1049
|
|
2
|
+
netherframe/backends/gcp/gcs.py,sha256=1CdObjHo0NG21DoVNLXGb98wIttdRtpU89x3zichcQo,16213
|
|
3
|
+
netherframe/backends/gcp/gcs_backend_bootstrap.py,sha256=SjzgPELReAOtOAK01-Ow-_wBkPvQMzqOmeBFLnPKnU0,3483
|
|
4
|
+
netherframe/backends/gcp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
nf/backends/gcp/__init__.py,sha256=DLIFJZufh2UCpHIKdo9G3V7u7782bpy9NyQJlxQn2ZA,238
|
|
6
|
+
nf/backends/gcp/gcs.py,sha256=EWRNEo8cmIy59Nw3kizJvK2VAsK6ixEy_IMbFqMBiyc,250
|
|
7
|
+
nf/backends/gcp/gcs_backend_bootstrap.py,sha256=42ORUNmQJc3f6TGBPpNPZpz7wB0hKu3CtI04Qt9DJV8,304
|
|
8
|
+
nf/backends/gcp/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
netherframe_backends_gcp-0.2.0.dist-info/licenses/LICENSE,sha256=CmCIBOHbWRqBeux1f3l5G7rXwtrrtVCZwymYiSoAYoE,1068
|
|
10
|
+
netherframe_backends_gcp-0.2.0.dist-info/WHEEL,sha256=G_-rrEibZr7OEM7zdH1dSO6s-VdjfnS5PA4CLAdI9Vw,80
|
|
11
|
+
netherframe_backends_gcp-0.2.0.dist-info/METADATA,sha256=uYyj-o-s59nvgvwQkDnxdszGalJr9D-Dm_VJfGzgf3M,1879
|
|
12
|
+
netherframe_backends_gcp-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Netherframe
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
nf/backends/gcp/gcs.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
# Generated nf.* alias shim (netherframe.generation.nf_alias_shims); do not edit.
|
|
2
|
+
"""Type-checker view of ``nf.backends.gcp.gcs_backend_bootstrap``; at runtime it is ``netherframe.backends.gcp.gcs_backend_bootstrap`` itself."""
|
|
3
|
+
|
|
4
|
+
from netherframe.backends.gcp.gcs_backend_bootstrap import * # noqa: F403
|
nf/backends/gcp/py.typed
ADDED
|
File without changes
|