netherframe.backends.azure 0.2.0__tar.gz
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_azure-0.2.0/LICENSE +21 -0
- netherframe_backends_azure-0.2.0/PKG-INFO +55 -0
- netherframe_backends_azure-0.2.0/README.md +32 -0
- netherframe_backends_azure-0.2.0/netherframe/backends/azure/__init__.py +43 -0
- netherframe_backends_azure-0.2.0/netherframe/backends/azure/azurerm.py +427 -0
- netherframe_backends_azure-0.2.0/netherframe/backends/azure/azurerm_backend_bootstrap.py +100 -0
- netherframe_backends_azure-0.2.0/netherframe/backends/azure/py.typed +0 -0
- netherframe_backends_azure-0.2.0/nf/backends/azure/__init__.py +4 -0
- netherframe_backends_azure-0.2.0/nf/backends/azure/azurerm.py +4 -0
- netherframe_backends_azure-0.2.0/nf/backends/azure/azurerm_backend_bootstrap.py +4 -0
- netherframe_backends_azure-0.2.0/nf/backends/azure/py.typed +0 -0
- netherframe_backends_azure-0.2.0/pyproject.toml +48 -0
- netherframe_backends_azure-0.2.0/pyproject.toml.orig +47 -0
|
@@ -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.
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: netherframe.backends.azure
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Azure 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: azure-storage-blob>=12.31.1
|
|
16
|
+
Requires-Dist: azure-identity>=1.27.0
|
|
17
|
+
Requires-Dist: pytest>=9.2.0 ; extra == 'dev'
|
|
18
|
+
Requires-Python: >=3.14
|
|
19
|
+
Project-URL: Homepage, https://netherframe.arsenal.sh
|
|
20
|
+
Project-URL: Repository, https://github.com/arsenal-sh/netherframe
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# nf.backends.azure
|
|
25
|
+
|
|
26
|
+
Azure backend implementations for Netherframe Infrastructure as Code framework.
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install netherframe.backends.azure
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from nf.backends.azure import AzurermBackend, AzurermStateBackend
|
|
38
|
+
|
|
39
|
+
# For Terraform synthesis mode
|
|
40
|
+
backend = AzurermBackend(nf_scope=stack, resource_group_name="terraform-state-rg", storage_account_name="tfstatestorage", container_name="tfstate", key="infrastructure.tfstate")
|
|
41
|
+
|
|
42
|
+
# For native execution mode
|
|
43
|
+
state_backend = AzurermStateBackend(storage_account_name="tfstatestorage", container_name="tfstate", key="infrastructure.tfstate", resource_group_name="terraform-state-rg")
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Features
|
|
47
|
+
|
|
48
|
+
- Azure Blob Storage-based state storage
|
|
49
|
+
- Compatible with Terraform's azurerm backend
|
|
50
|
+
- Support for multiple authentication methods (Service Principal, MSI, CLI)
|
|
51
|
+
- State locking using blob leases
|
|
52
|
+
- Automatic blob creation if it doesn't exist
|
|
53
|
+
- Force-unlock by lock ID (the lease's; `nf state force-unlock`), with the lock's info in the blob's metadata while leased
|
|
54
|
+
- Conditional writes: a write replaces only the state version its run read (ETag match)
|
|
55
|
+
- Pre-apply checkpoints kept beside the state (`<key>.checkpoints/`)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# nf.backends.azure
|
|
2
|
+
|
|
3
|
+
Azure backend implementations for Netherframe Infrastructure as Code framework.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install netherframe.backends.azure
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from nf.backends.azure import AzurermBackend, AzurermStateBackend
|
|
15
|
+
|
|
16
|
+
# For Terraform synthesis mode
|
|
17
|
+
backend = AzurermBackend(nf_scope=stack, resource_group_name="terraform-state-rg", storage_account_name="tfstatestorage", container_name="tfstate", key="infrastructure.tfstate")
|
|
18
|
+
|
|
19
|
+
# For native execution mode
|
|
20
|
+
state_backend = AzurermStateBackend(storage_account_name="tfstatestorage", container_name="tfstate", key="infrastructure.tfstate", resource_group_name="terraform-state-rg")
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Features
|
|
24
|
+
|
|
25
|
+
- Azure Blob Storage-based state storage
|
|
26
|
+
- Compatible with Terraform's azurerm backend
|
|
27
|
+
- Support for multiple authentication methods (Service Principal, MSI, CLI)
|
|
28
|
+
- State locking using blob leases
|
|
29
|
+
- Automatic blob creation if it doesn't exist
|
|
30
|
+
- Force-unlock by lock ID (the lease's; `nf state force-unlock`), with the lock's info in the blob's metadata while leased
|
|
31
|
+
- Conditional writes: a write replaces only the state version its run read (ETag match)
|
|
32
|
+
- Pre-apply checkpoints kept beside the state (`<key>.checkpoints/`)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Azure backend implementations for Netherframe."""
|
|
2
|
+
|
|
3
|
+
from netherframe.backends.azure.azurerm import AzurermBackend, AzurermStateBackend
|
|
4
|
+
from netherframe.backends.azure.azurerm_backend_bootstrap import (
|
|
5
|
+
AzurermBackendBootstrapper,
|
|
6
|
+
AzurermBackendResources,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"AzurermBackend",
|
|
11
|
+
"AzurermStateBackend",
|
|
12
|
+
"AzurermBackendBootstrapper",
|
|
13
|
+
"AzurermBackendResources",
|
|
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 Azure backend constructs and state backends."""
|
|
22
|
+
BackendBootstrapManager.register_bootstrapper(
|
|
23
|
+
"azurerm",
|
|
24
|
+
AzurermBackendBootstrapper,
|
|
25
|
+
)
|
|
26
|
+
BackendRegistry.register_backend_construct(
|
|
27
|
+
"azurerm",
|
|
28
|
+
AzurermBackend,
|
|
29
|
+
"netherframe.backends.azure",
|
|
30
|
+
)
|
|
31
|
+
BackendRegistry.register_state_backend(
|
|
32
|
+
"azurerm",
|
|
33
|
+
AzurermStateBackend,
|
|
34
|
+
"netherframe.backends.azure",
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
_register_core_components()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def register_backends() -> None:
|
|
42
|
+
"""Register Azure backends. Called by entry points."""
|
|
43
|
+
_register_core_components()
|
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
"""Azure Storage backend implementation for Terraform and native execution modes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import contextlib
|
|
7
|
+
import uuid
|
|
8
|
+
from netherframe.core.serialization import orjson_compat as json
|
|
9
|
+
import subprocess
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
|
|
12
|
+
from netherframe.core.backends.lock_heartbeat import LockHeartbeat
|
|
13
|
+
from netherframe.core.backends.document_state_backend import ABSENT, DocumentChangedError, DocumentStateBackend
|
|
14
|
+
from netherframe.core.backends.state_engine import State
|
|
15
|
+
from netherframe.core.constructs.backend_base import Backend
|
|
16
|
+
from netherframe.core.constructs.app_stack import Stack
|
|
17
|
+
from netherframe.core.exceptions import StateLockError
|
|
18
|
+
from netherframe.core.logging import get_logger
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from netherframe.core.backends.backend_bootstrap import BackendBootstrapper
|
|
22
|
+
from netherframe.core.constructs.framework_settings import BackendSettings
|
|
23
|
+
|
|
24
|
+
logger = get_logger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AzurermBackend(Backend):
|
|
28
|
+
"""Azure Storage backend for Terraform state."""
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def backend_type(self) -> str:
|
|
32
|
+
"""Get the backend type name."""
|
|
33
|
+
return "azurerm"
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
nf_scope: Stack,
|
|
38
|
+
*,
|
|
39
|
+
resource_group_name: str,
|
|
40
|
+
storage_account_name: str,
|
|
41
|
+
container_name: str,
|
|
42
|
+
key: str,
|
|
43
|
+
nf_backend_settings: BackendSettings | None = None,
|
|
44
|
+
**kwargs: Any,
|
|
45
|
+
) -> None:
|
|
46
|
+
"""Initialize Azure backend.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
nf_scope: Parent stack
|
|
50
|
+
resource_group_name: Resource group containing storage account
|
|
51
|
+
storage_account_name: Storage account name
|
|
52
|
+
container_name: Blob container name
|
|
53
|
+
key: Blob name for state file
|
|
54
|
+
**kwargs: Additional backend configuration
|
|
55
|
+
|
|
56
|
+
"""
|
|
57
|
+
super().__init__(
|
|
58
|
+
nf_scope=nf_scope,
|
|
59
|
+
nf_id="backend",
|
|
60
|
+
nf_backend_settings=nf_backend_settings,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
self.resource_group_name = resource_group_name
|
|
64
|
+
self.storage_account_name = storage_account_name
|
|
65
|
+
self.container_name = container_name
|
|
66
|
+
self.key = key
|
|
67
|
+
self.additional_config = kwargs
|
|
68
|
+
|
|
69
|
+
def _build_config(self) -> dict[str, Any]:
|
|
70
|
+
"""Build Terraform backend configuration."""
|
|
71
|
+
config: dict[str, Any] = {
|
|
72
|
+
"resource_group_name": self.resource_group_name,
|
|
73
|
+
"storage_account_name": self.storage_account_name,
|
|
74
|
+
"container_name": self.container_name,
|
|
75
|
+
"key": self.key,
|
|
76
|
+
}
|
|
77
|
+
config.update(self.additional_config)
|
|
78
|
+
return config
|
|
79
|
+
|
|
80
|
+
def _to_config(self) -> dict[str, Any]:
|
|
81
|
+
"""Convert to Terraform backend configuration."""
|
|
82
|
+
return {"azurerm": self._build_config()}
|
|
83
|
+
|
|
84
|
+
def get_state_resources(self) -> list[dict[str, Any]] | None:
|
|
85
|
+
"""Get resources from Azure state using terraform state pull."""
|
|
86
|
+
stack = self.nf_scope
|
|
87
|
+
if not isinstance(stack, Stack) or not stack.app:
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
# Similar to S3, use terraform state pull
|
|
92
|
+
working_dir = f"{stack.app.outdir}/{stack.app.nf_id}/{stack.nf_id}"
|
|
93
|
+
result = subprocess.run(
|
|
94
|
+
["terraform", "state", "pull"],
|
|
95
|
+
cwd=working_dir,
|
|
96
|
+
capture_output=True,
|
|
97
|
+
text=True,
|
|
98
|
+
check=True,
|
|
99
|
+
)
|
|
100
|
+
state = json.loads(result.stdout)
|
|
101
|
+
return state.get("resources", [])
|
|
102
|
+
|
|
103
|
+
except subprocess.CalledProcessError, json.JSONDecodeError, FileNotFoundError:
|
|
104
|
+
pass
|
|
105
|
+
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
def get_bootstrapper(self) -> BackendBootstrapper | None:
|
|
109
|
+
"""Return an Azurerm backend bootstrapper if possible."""
|
|
110
|
+
from netherframe.backends.azure.azurerm_backend_bootstrap import (
|
|
111
|
+
AzurermBackendBootstrapper,
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
additional = getattr(self, "additional_config", {})
|
|
115
|
+
return AzurermBackendBootstrapper(
|
|
116
|
+
storage_account_name=self.storage_account_name,
|
|
117
|
+
container_name=self.container_name,
|
|
118
|
+
tenant_id=additional.get("tenant_id"),
|
|
119
|
+
client_id=additional.get("client_id"),
|
|
120
|
+
client_secret=additional.get("client_secret"),
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class AzurermStateBackend(DocumentStateBackend):
|
|
125
|
+
"""Azure Storage-based state backend.
|
|
126
|
+
|
|
127
|
+
Compatible with Terraform's azurerm backend.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
def __init__(
|
|
131
|
+
self,
|
|
132
|
+
storage_account_name: str,
|
|
133
|
+
container_name: str,
|
|
134
|
+
key: str,
|
|
135
|
+
resource_group_name: str | None = None,
|
|
136
|
+
subscription_id: str | None = None,
|
|
137
|
+
tenant_id: str | None = None,
|
|
138
|
+
client_id: str | None = None,
|
|
139
|
+
client_secret: str | None = None,
|
|
140
|
+
use_msi: bool = False,
|
|
141
|
+
) -> None:
|
|
142
|
+
"""Initialize Azure Storage state backend.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
storage_account_name: Storage account name
|
|
146
|
+
container_name: Container name
|
|
147
|
+
key: Blob name
|
|
148
|
+
resource_group_name: Resource group name
|
|
149
|
+
subscription_id: Azure subscription ID
|
|
150
|
+
tenant_id: Azure AD tenant ID
|
|
151
|
+
client_id: Service principal client ID
|
|
152
|
+
client_secret: Service principal client secret
|
|
153
|
+
use_msi: Use Managed Service Identity
|
|
154
|
+
|
|
155
|
+
"""
|
|
156
|
+
self.storage_account_name = storage_account_name
|
|
157
|
+
self.container_name = container_name
|
|
158
|
+
self.key = key
|
|
159
|
+
self.resource_group_name = resource_group_name
|
|
160
|
+
self._lease: Any = None
|
|
161
|
+
self._lock_metadata: dict[str, str] = {}
|
|
162
|
+
self._heartbeat: LockHeartbeat | None = None
|
|
163
|
+
|
|
164
|
+
# Import Azure SDK
|
|
165
|
+
try:
|
|
166
|
+
from azure.identity import ClientSecretCredential, DefaultAzureCredential
|
|
167
|
+
from azure.storage.blob import BlobServiceClient
|
|
168
|
+
|
|
169
|
+
# Create credential
|
|
170
|
+
if client_id and client_secret and tenant_id:
|
|
171
|
+
credential = ClientSecretCredential(
|
|
172
|
+
tenant_id=tenant_id,
|
|
173
|
+
client_id=client_id,
|
|
174
|
+
client_secret=client_secret,
|
|
175
|
+
)
|
|
176
|
+
else:
|
|
177
|
+
credential = DefaultAzureCredential()
|
|
178
|
+
|
|
179
|
+
# Create blob service client
|
|
180
|
+
account_url = f"https://{storage_account_name}.blob.core.windows.net"
|
|
181
|
+
self.blob_service = BlobServiceClient(
|
|
182
|
+
account_url=account_url,
|
|
183
|
+
credential=credential,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
# Get container client
|
|
187
|
+
self.container = self.blob_service.get_container_client(container_name)
|
|
188
|
+
|
|
189
|
+
except ImportError as e:
|
|
190
|
+
raise RuntimeError(
|
|
191
|
+
"Azure SDK is required for azurerm backend. Install with: pip install azure-storage-blob azure-identity",
|
|
192
|
+
) from e
|
|
193
|
+
|
|
194
|
+
storage_name = "Azure Storage"
|
|
195
|
+
state_logger = logger
|
|
196
|
+
|
|
197
|
+
def _get_blob_client(self) -> Any:
|
|
198
|
+
"""Return the state blob client."""
|
|
199
|
+
return self.container.get_blob_client(self.key)
|
|
200
|
+
|
|
201
|
+
@staticmethod
|
|
202
|
+
def _is_missing_blob_error(error: Exception) -> bool:
|
|
203
|
+
"""Return whether the Azure error indicates a missing blob."""
|
|
204
|
+
return getattr(error, "error_code", None) == "BlobNotFound" or "BlobNotFound" in str(error)
|
|
205
|
+
|
|
206
|
+
@staticmethod
|
|
207
|
+
def _json_content_settings() -> Any:
|
|
208
|
+
"""Return blob content settings for a JSON document."""
|
|
209
|
+
from azure.storage.blob import ContentSettings
|
|
210
|
+
|
|
211
|
+
return ContentSettings(content_type="application/json")
|
|
212
|
+
|
|
213
|
+
def _state_location(self) -> str:
|
|
214
|
+
"""Return the container/blob path of the state."""
|
|
215
|
+
return f"{self.container_name}/{self.key}"
|
|
216
|
+
|
|
217
|
+
def state_identity(self) -> dict[str, Any]:
|
|
218
|
+
return {"backend": "azurerm", "endpoint": self.blob_service.url, "container": self.container_name, "key": self.key}
|
|
219
|
+
|
|
220
|
+
def _checkpoint_blob_name(self, name: str) -> str:
|
|
221
|
+
return f"{self.key}.checkpoints/{name}"
|
|
222
|
+
|
|
223
|
+
def _checkpoint_location(self, name: str) -> str:
|
|
224
|
+
return f"azurerm://{self.storage_account_name}/{self.container_name}/{self._checkpoint_blob_name(name)}"
|
|
225
|
+
|
|
226
|
+
def _write_checkpoint(self, name: str, data: bytes) -> None:
|
|
227
|
+
self.container.get_blob_client(self._checkpoint_blob_name(name)).upload_blob(data=data, overwrite=True, content_settings=self._json_content_settings())
|
|
228
|
+
|
|
229
|
+
def _read_checkpoint(self, name: str) -> bytes | None:
|
|
230
|
+
try:
|
|
231
|
+
return self.container.get_blob_client(self._checkpoint_blob_name(name)).download_blob().readall()
|
|
232
|
+
except Exception as e:
|
|
233
|
+
if self._is_missing_blob_error(e):
|
|
234
|
+
return None
|
|
235
|
+
raise
|
|
236
|
+
|
|
237
|
+
def _checkpoint_names(self) -> list[str]:
|
|
238
|
+
prefix = self._checkpoint_blob_name("")
|
|
239
|
+
return [blob.name.removeprefix(prefix) for blob in self.container.list_blobs(name_starts_with=prefix)]
|
|
240
|
+
|
|
241
|
+
def _delete_checkpoint(self, name: str) -> None:
|
|
242
|
+
try:
|
|
243
|
+
self.container.delete_blob(self._checkpoint_blob_name(name))
|
|
244
|
+
except Exception as e:
|
|
245
|
+
if not self._is_missing_blob_error(e):
|
|
246
|
+
raise
|
|
247
|
+
|
|
248
|
+
def _read_document(self) -> tuple[bytes | None, Any]:
|
|
249
|
+
"""Download the state blob with its ETag, or return (None, ABSENT) if it does not exist."""
|
|
250
|
+
blob_client = self._get_blob_client()
|
|
251
|
+
try:
|
|
252
|
+
downloader = blob_client.download_blob()
|
|
253
|
+
except Exception as e:
|
|
254
|
+
if self._is_missing_blob_error(e):
|
|
255
|
+
return None, ABSENT
|
|
256
|
+
raise
|
|
257
|
+
return downloader.readall(), downloader.properties.etag
|
|
258
|
+
|
|
259
|
+
def _write_document(self, data: bytes, if_token: Any = None) -> Any:
|
|
260
|
+
"""Upload the state blob; with a token, only while the stored blob has that ETag."""
|
|
261
|
+
from azure.core import MatchConditions
|
|
262
|
+
from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceModifiedError, ResourceNotFoundError
|
|
263
|
+
|
|
264
|
+
blob_client = self._get_blob_client()
|
|
265
|
+
# While we hold the lock the blob is leased, and Azure rejects writes without the lease; a
|
|
266
|
+
# write replaces the blob's metadata, so it passes the lock's info on
|
|
267
|
+
kwargs: dict[str, Any] = {"lease": self._lease, "metadata": self._lock_metadata} if self._lease is not None else {}
|
|
268
|
+
if if_token is ABSENT:
|
|
269
|
+
kwargs["overwrite"] = False
|
|
270
|
+
else:
|
|
271
|
+
kwargs["overwrite"] = True
|
|
272
|
+
if if_token is not None:
|
|
273
|
+
kwargs.update(etag=if_token, match_condition=MatchConditions.IfNotModified)
|
|
274
|
+
try:
|
|
275
|
+
result = blob_client.upload_blob(data=data, content_settings=self._json_content_settings(), **kwargs)
|
|
276
|
+
except (ResourceExistsError, ResourceModifiedError, ResourceNotFoundError) as e:
|
|
277
|
+
if if_token is None:
|
|
278
|
+
raise
|
|
279
|
+
raise DocumentChangedError(str(e)) from e
|
|
280
|
+
except HttpResponseError as e:
|
|
281
|
+
code = getattr(e, "error_code", None)
|
|
282
|
+
if code in self._LEASE_REFUSALS:
|
|
283
|
+
# Another run leased the blob: it holds the state lock
|
|
284
|
+
raise StateLockError(f"Cannot write state to {self._state_location()}: it is locked by another run ({code})") from e
|
|
285
|
+
raise
|
|
286
|
+
return result.get("etag") if isinstance(result, dict) else None
|
|
287
|
+
|
|
288
|
+
#: Error codes of a write refused because another run holds the blob's lease
|
|
289
|
+
_LEASE_REFUSALS = frozenset({"LeaseIdMissing", "LeaseIdMismatchWithBlobOperation", "LeaseLost"})
|
|
290
|
+
|
|
291
|
+
LEASE_SECONDS = 60
|
|
292
|
+
LEASE_RENEW_SECONDS: float = 20
|
|
293
|
+
|
|
294
|
+
def _ensure_state_blob(self, blob_client: Any) -> None:
|
|
295
|
+
"""Create an empty state blob so it can be leased on the first run."""
|
|
296
|
+
from azure.core.exceptions import ResourceExistsError
|
|
297
|
+
|
|
298
|
+
try:
|
|
299
|
+
blob_client.upload_blob(
|
|
300
|
+
data=json.dumps(State().to_dict()),
|
|
301
|
+
overwrite=False,
|
|
302
|
+
content_settings=self._json_content_settings(),
|
|
303
|
+
)
|
|
304
|
+
except ResourceExistsError:
|
|
305
|
+
pass
|
|
306
|
+
|
|
307
|
+
#: The blob metadata key holding the lock's info (base64 JSON) while the blob is leased
|
|
308
|
+
LOCK_METADATA_KEY = "nflockinfo"
|
|
309
|
+
|
|
310
|
+
@staticmethod
|
|
311
|
+
def _as_lease_id(lock_id: object) -> str | None:
|
|
312
|
+
"""A lock ID Azure accepts as a proposed lease ID (a GUID), or None to let Azure choose one."""
|
|
313
|
+
try:
|
|
314
|
+
return str(uuid.UUID(str(lock_id))) if lock_id else None
|
|
315
|
+
except ValueError:
|
|
316
|
+
return None
|
|
317
|
+
|
|
318
|
+
def lock(self, info: dict[str, Any]) -> bool:
|
|
319
|
+
"""Acquire state lock using a blob lease, renewed until unlock().
|
|
320
|
+
|
|
321
|
+
The lease's ID is the lock's (``info["ID"]``, a GUID), and the lock's info is kept in the
|
|
322
|
+
blob's metadata while it is leased, so another run can tell who holds it and force-unlock it.
|
|
323
|
+
"""
|
|
324
|
+
try:
|
|
325
|
+
blob_client = self._get_blob_client()
|
|
326
|
+
self._ensure_state_blob(blob_client)
|
|
327
|
+
|
|
328
|
+
lease_kwargs = {"lease_id": lease_id} if (lease_id := self._as_lease_id(info.get("ID") or info.get("id"))) else {}
|
|
329
|
+
lease = blob_client.acquire_lease(lease_duration=self.LEASE_SECONDS, **lease_kwargs)
|
|
330
|
+
self._lease = lease
|
|
331
|
+
lock_info = {**info, "ID": str(lease.id)}
|
|
332
|
+
self._lock_metadata = {self.LOCK_METADATA_KEY: base64.b64encode(json.dumps(lock_info).encode("utf-8")).decode("ascii")}
|
|
333
|
+
blob_client.set_blob_metadata(metadata=self._lock_metadata, lease=lease)
|
|
334
|
+
self._heartbeat = LockHeartbeat(lease.renew, self.LEASE_RENEW_SECONDS, name=f"azurerm:{self.key}").start()
|
|
335
|
+
|
|
336
|
+
logger.info(f"State lock acquired (Lease ID: {lease.id})")
|
|
337
|
+
return True
|
|
338
|
+
|
|
339
|
+
except Exception as e:
|
|
340
|
+
logger.error("Failed to acquire lock: %s", e)
|
|
341
|
+
if self._lease is not None:
|
|
342
|
+
with contextlib.suppress(Exception):
|
|
343
|
+
self._lease.release()
|
|
344
|
+
self._lease = None
|
|
345
|
+
return False
|
|
346
|
+
|
|
347
|
+
def unlock(self) -> None:
|
|
348
|
+
"""Release state lock."""
|
|
349
|
+
if self._lease is None:
|
|
350
|
+
return
|
|
351
|
+
if self._heartbeat is not None:
|
|
352
|
+
self._heartbeat.stop()
|
|
353
|
+
self._heartbeat = None
|
|
354
|
+
try:
|
|
355
|
+
with contextlib.suppress(Exception):
|
|
356
|
+
self._get_blob_client().set_blob_metadata(metadata={}, lease=self._lease)
|
|
357
|
+
self._lease.release()
|
|
358
|
+
logger.info(f"State lock released (Lease ID: {self._lease.id})")
|
|
359
|
+
except Exception as e:
|
|
360
|
+
logger.error("Failed to release lock: %s", e)
|
|
361
|
+
finally:
|
|
362
|
+
self._lease = None
|
|
363
|
+
self._lock_metadata = {}
|
|
364
|
+
|
|
365
|
+
can_force_unlock = True
|
|
366
|
+
|
|
367
|
+
def current_lock(self) -> dict[str, Any] | None:
|
|
368
|
+
"""The info of the lock held on this state (its lease's), or None when the blob is not leased."""
|
|
369
|
+
try:
|
|
370
|
+
properties = self._get_blob_client().get_blob_properties()
|
|
371
|
+
except Exception as e:
|
|
372
|
+
if self._is_missing_blob_error(e):
|
|
373
|
+
return None
|
|
374
|
+
raise
|
|
375
|
+
if getattr(properties.lease, "state", None) != "leased":
|
|
376
|
+
return None
|
|
377
|
+
encoded = (properties.metadata or {}).get(self.LOCK_METADATA_KEY)
|
|
378
|
+
if not encoded:
|
|
379
|
+
return {"ID": None, "Who": "a run that did not record its lock info"}
|
|
380
|
+
return json.loads(base64.b64decode(encoded))
|
|
381
|
+
|
|
382
|
+
def force_unlock(self, lock_id: str) -> None:
|
|
383
|
+
"""Release the blob's lease, only while it is the lock (lease) ``lock_id``."""
|
|
384
|
+
holder = self.current_lock()
|
|
385
|
+
if holder is None:
|
|
386
|
+
raise StateLockError(f"State at {self._state_location()} is not locked")
|
|
387
|
+
if str(holder.get("ID")) != lock_id:
|
|
388
|
+
raise StateLockError(f"State at {self._state_location()} is locked by lock {holder.get('ID')}, not {lock_id}")
|
|
389
|
+
blob_client = self._get_blob_client()
|
|
390
|
+
# Proposing the active lease's ID gets that lease, which can then be released
|
|
391
|
+
lease = blob_client.acquire_lease(lease_duration=self.LEASE_SECONDS, lease_id=lock_id)
|
|
392
|
+
with contextlib.suppress(Exception):
|
|
393
|
+
blob_client.set_blob_metadata(metadata={}, lease=lease)
|
|
394
|
+
lease.release()
|
|
395
|
+
logger.warning("Released state lock %s of %s", lock_id, holder)
|
|
396
|
+
|
|
397
|
+
def get_backend_type(self) -> str:
|
|
398
|
+
"""Get the backend type identifier.
|
|
399
|
+
|
|
400
|
+
Returns:
|
|
401
|
+
"azurerm" for Azure Storage backend
|
|
402
|
+
|
|
403
|
+
"""
|
|
404
|
+
return "azurerm"
|
|
405
|
+
|
|
406
|
+
def get_config(self) -> dict[str, Any]:
|
|
407
|
+
"""Get the backend configuration.
|
|
408
|
+
|
|
409
|
+
Returns:
|
|
410
|
+
Complete configuration dictionary for recreating this backend
|
|
411
|
+
|
|
412
|
+
"""
|
|
413
|
+
config = {
|
|
414
|
+
"storage_account_name": self.storage_account_name,
|
|
415
|
+
"container_name": self.container_name,
|
|
416
|
+
"key": self.key,
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
# Include optional configuration if present
|
|
420
|
+
if self.resource_group_name:
|
|
421
|
+
config["resource_group_name"] = self.resource_group_name
|
|
422
|
+
|
|
423
|
+
# Note: We don't include sensitive credentials in the config
|
|
424
|
+
# These should be provided via environment variables or
|
|
425
|
+
# managed identity when recreating the backend
|
|
426
|
+
|
|
427
|
+
return config
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Azurerm backend bootstrapping implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any, 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 AzureContainerClient(Protocol):
|
|
15
|
+
"""Minimal Azure container client interface used for bootstrap operations."""
|
|
16
|
+
|
|
17
|
+
def exists(self) -> bool: ...
|
|
18
|
+
def create_container(self) -> Any: ...
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class AzurermBackendResources(BackendResources):
|
|
23
|
+
"""Azurerm backend resources information."""
|
|
24
|
+
|
|
25
|
+
storage_account_name: str | None = None
|
|
26
|
+
container_name: str | None = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class AzurermBackendBootstrapper(BackendBootstrapper):
|
|
30
|
+
"""Bootstrap Azure Storage backend resources (container)."""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
*,
|
|
35
|
+
storage_account_name: str,
|
|
36
|
+
container_name: str,
|
|
37
|
+
tenant_id: str | None = None,
|
|
38
|
+
client_id: str | None = None,
|
|
39
|
+
client_secret: str | None = None,
|
|
40
|
+
) -> None:
|
|
41
|
+
self.storage_account_name = storage_account_name
|
|
42
|
+
self.container_name = container_name
|
|
43
|
+
self.tenant_id = tenant_id
|
|
44
|
+
self.client_id = client_id
|
|
45
|
+
self.client_secret = client_secret
|
|
46
|
+
self._resources = AzurermBackendResources()
|
|
47
|
+
|
|
48
|
+
def _create_container_client(self) -> AzureContainerClient:
|
|
49
|
+
try:
|
|
50
|
+
from azure.identity import ClientSecretCredential, DefaultAzureCredential
|
|
51
|
+
from azure.storage.blob import BlobServiceClient
|
|
52
|
+
except ImportError as exc: # pragma: no cover - optional deps
|
|
53
|
+
raise RuntimeError(
|
|
54
|
+
"Azure SDK is required for azurerm bootstrapping. Install with: pip install azure-storage-blob azure-identity",
|
|
55
|
+
) from exc
|
|
56
|
+
|
|
57
|
+
if self.client_id and self.client_secret and self.tenant_id:
|
|
58
|
+
credential = ClientSecretCredential(
|
|
59
|
+
tenant_id=self.tenant_id,
|
|
60
|
+
client_id=self.client_id,
|
|
61
|
+
client_secret=self.client_secret,
|
|
62
|
+
)
|
|
63
|
+
else:
|
|
64
|
+
credential = DefaultAzureCredential()
|
|
65
|
+
|
|
66
|
+
account_url = f"https://{self.storage_account_name}.blob.core.windows.net"
|
|
67
|
+
service = BlobServiceClient(account_url=account_url, credential=credential)
|
|
68
|
+
return service.get_container_client(self.container_name)
|
|
69
|
+
|
|
70
|
+
def validate(self) -> bool:
|
|
71
|
+
"""Validate that the container exists."""
|
|
72
|
+
container = self._create_container_client()
|
|
73
|
+
try:
|
|
74
|
+
exists = container.exists()
|
|
75
|
+
except Exception: # pragma: no cover - best effort
|
|
76
|
+
return False
|
|
77
|
+
if not exists:
|
|
78
|
+
return False
|
|
79
|
+
self._resources.storage_account_name = self.storage_account_name
|
|
80
|
+
self._resources.container_name = self.container_name
|
|
81
|
+
return True
|
|
82
|
+
|
|
83
|
+
def bootstrap(self) -> BackendResources:
|
|
84
|
+
"""Create the container if missing."""
|
|
85
|
+
container = self._create_container_client()
|
|
86
|
+
try:
|
|
87
|
+
exists = container.exists()
|
|
88
|
+
except Exception:
|
|
89
|
+
exists = False
|
|
90
|
+
if not exists:
|
|
91
|
+
logger.info(
|
|
92
|
+
"Creating Azure storage container %s in %s",
|
|
93
|
+
self.container_name,
|
|
94
|
+
self.storage_account_name,
|
|
95
|
+
)
|
|
96
|
+
container.create_container()
|
|
97
|
+
|
|
98
|
+
self._resources.storage_account_name = self.storage_account_name
|
|
99
|
+
self._resources.container_name = self.container_name
|
|
100
|
+
return self._resources
|
|
File without changes
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
# Generated nf.* alias shim (netherframe.generation.nf_alias_shims); do not edit.
|
|
2
|
+
"""Type-checker view of ``nf.backends.azure.azurerm_backend_bootstrap``; at runtime it is ``netherframe.backends.azure.azurerm_backend_bootstrap`` itself."""
|
|
3
|
+
|
|
4
|
+
from netherframe.backends.azure.azurerm_backend_bootstrap import * # noqa: F403
|
|
File without changes
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "netherframe.backends.azure"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "Azure backend implementations for Netherframe"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.14"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
classifiers = [
|
|
10
|
+
"Development Status :: 4 - Beta",
|
|
11
|
+
"Intended Audience :: Developers",
|
|
12
|
+
"Programming Language :: Python :: 3.14",
|
|
13
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
14
|
+
"Topic :: System :: Systems Administration",
|
|
15
|
+
]
|
|
16
|
+
dependencies = [
|
|
17
|
+
"netherframe.core>=0.9.0",
|
|
18
|
+
"azure-storage-blob>=12.31.1",
|
|
19
|
+
"azure-identity>=1.27.0",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[[project.authors]]
|
|
23
|
+
name = "Sourabh Cheedella"
|
|
24
|
+
email = "cheedella.sourabh@gmail.com"
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
dev = ["pytest>=9.2.0"]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://netherframe.arsenal.sh"
|
|
31
|
+
Repository = "https://github.com/arsenal-sh/netherframe"
|
|
32
|
+
|
|
33
|
+
[build-system]
|
|
34
|
+
requires = ["uv_build>=0.13.9,<0.14.0"]
|
|
35
|
+
build-backend = "uv_build"
|
|
36
|
+
|
|
37
|
+
[tool.uv]
|
|
38
|
+
package = true
|
|
39
|
+
|
|
40
|
+
[tool.uv.build-backend]
|
|
41
|
+
module-name = [
|
|
42
|
+
"netherframe.backends.azure",
|
|
43
|
+
"nf.backends.azure",
|
|
44
|
+
]
|
|
45
|
+
module-root = ""
|
|
46
|
+
|
|
47
|
+
[tool.uv.sources."netherframe.core"]
|
|
48
|
+
workspace = true
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "netherframe.backends.azure"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "Azure backend implementations for Netherframe"
|
|
5
|
+
authors = [
|
|
6
|
+
{name = "Sourabh Cheedella", email = "cheedella.sourabh@gmail.com"},
|
|
7
|
+
]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.14"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 4 - Beta",
|
|
14
|
+
"Intended Audience :: Developers",
|
|
15
|
+
"Programming Language :: Python :: 3.14",
|
|
16
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
17
|
+
"Topic :: System :: Systems Administration",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
dependencies = [
|
|
21
|
+
"netherframe.core>=0.9.0",
|
|
22
|
+
"azure-storage-blob>=12.31.1",
|
|
23
|
+
"azure-identity>=1.27.0",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
dev = [
|
|
28
|
+
"pytest>=9.2.0",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://netherframe.arsenal.sh"
|
|
33
|
+
Repository = "https://github.com/arsenal-sh/netherframe"
|
|
34
|
+
|
|
35
|
+
[build-system]
|
|
36
|
+
requires = ["uv_build>=0.13.9,<0.14.0"]
|
|
37
|
+
build-backend = "uv_build"
|
|
38
|
+
|
|
39
|
+
[tool.uv]
|
|
40
|
+
package = true
|
|
41
|
+
|
|
42
|
+
[tool.uv.build-backend]
|
|
43
|
+
module-name = ["netherframe.backends.azure", "nf.backends.azure"]
|
|
44
|
+
module-root = ""
|
|
45
|
+
|
|
46
|
+
[tool.uv.sources]
|
|
47
|
+
"netherframe.core" = { workspace = true }
|