libcloud-noderings 0.1.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.
- libcloud_noderings/__init__.py +34 -0
- libcloud_noderings/_api/__init__.py +0 -0
- libcloud_noderings/_api/client.py +592 -0
- libcloud_noderings/_api/compute.py +391 -0
- libcloud_noderings/_api/dns.py +162 -0
- libcloud_noderings/_api/marketplace.py +182 -0
- libcloud_noderings/_version.py +8 -0
- libcloud_noderings/common.py +95 -0
- libcloud_noderings/compute.py +404 -0
- libcloud_noderings/dns.py +252 -0
- libcloud_noderings-0.1.0.dist-info/METADATA +177 -0
- libcloud_noderings-0.1.0.dist-info/RECORD +15 -0
- libcloud_noderings-0.1.0.dist-info/WHEEL +5 -0
- libcloud_noderings-0.1.0.dist-info/licenses/LICENSE +201 -0
- libcloud_noderings-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Apache Libcloud drivers for NodeRings: virtual machines (compute) and DNS.
|
|
3
|
+
|
|
4
|
+
Register them once, then use them like any built-in Libcloud provider::
|
|
5
|
+
|
|
6
|
+
import libcloud_noderings
|
|
7
|
+
from libcloud.compute.providers import get_driver
|
|
8
|
+
|
|
9
|
+
libcloud_noderings.register()
|
|
10
|
+
cls = get_driver("noderings")
|
|
11
|
+
driver = cls("YOUR_TOKEN")
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import contextlib
|
|
15
|
+
|
|
16
|
+
from libcloud_noderings._version import __version__
|
|
17
|
+
|
|
18
|
+
PROVIDER = "noderings"
|
|
19
|
+
|
|
20
|
+
__all__ = ["PROVIDER", "__version__", "register"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def register():
|
|
24
|
+
"""Register the NodeRings compute and DNS drivers under the name ``noderings``."""
|
|
25
|
+
from libcloud.compute.providers import set_driver as set_compute_driver
|
|
26
|
+
from libcloud.dns.providers import set_driver as set_dns_driver
|
|
27
|
+
|
|
28
|
+
for setter, module, klass in (
|
|
29
|
+
(set_compute_driver, "libcloud_noderings.compute", "NodeRingsNodeDriver"),
|
|
30
|
+
(set_dns_driver, "libcloud_noderings.dns", "NodeRingsDNSDriver"),
|
|
31
|
+
):
|
|
32
|
+
# set_driver refuses to register a name twice; a second register() is a no-op.
|
|
33
|
+
with contextlib.suppress(AttributeError):
|
|
34
|
+
setter(PROVIDER, module, klass)
|
|
File without changes
|
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
"""
|
|
2
|
+
A small JSON client for the NodeRings public API.
|
|
3
|
+
|
|
4
|
+
It is shared by the compute and DNS drivers (the same code drives the NodeRings
|
|
5
|
+
Salt extension). It retries rate-limited and transient failures, never retries orders
|
|
6
|
+
blindly, and keeps secrets out of error messages. It uses only the standard
|
|
7
|
+
library.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import random
|
|
13
|
+
import re
|
|
14
|
+
import time
|
|
15
|
+
import uuid
|
|
16
|
+
from urllib.error import HTTPError
|
|
17
|
+
from urllib.error import URLError
|
|
18
|
+
from urllib.parse import quote
|
|
19
|
+
from urllib.parse import urlencode
|
|
20
|
+
from urllib.request import Request
|
|
21
|
+
from urllib.request import urlopen
|
|
22
|
+
|
|
23
|
+
from libcloud_noderings._version import __version__
|
|
24
|
+
|
|
25
|
+
DEFAULT_API_URL = "https://api.noderings.com"
|
|
26
|
+
TOKEN_ENV_VARS = ("NODERINGS_TOKEN", "NODERINGS_API_TOKEN", "NR_API_TOKEN")
|
|
27
|
+
|
|
28
|
+
# gRPC status codes carried in the API's error bodies.
|
|
29
|
+
CODE_INVALID_ARGUMENT = 3
|
|
30
|
+
CODE_NOT_FOUND = 5
|
|
31
|
+
CODE_ALREADY_EXISTS = 6
|
|
32
|
+
CODE_PERMISSION_DENIED = 7
|
|
33
|
+
CODE_FAILED_PRECONDITION = 9
|
|
34
|
+
CODE_UNAUTHENTICATED = 16
|
|
35
|
+
|
|
36
|
+
_UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class NodeRingsError(Exception):
|
|
40
|
+
"""An error returned by the NodeRings API."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, status, code=0, message="", details=None, method="", path=""):
|
|
43
|
+
self.status = status
|
|
44
|
+
self.code = code
|
|
45
|
+
self.message = (message or "").strip()
|
|
46
|
+
self.details = details or []
|
|
47
|
+
self.method = method
|
|
48
|
+
self.path = path
|
|
49
|
+
super().__init__(str(self))
|
|
50
|
+
|
|
51
|
+
def quota_info(self):
|
|
52
|
+
for detail in self.details:
|
|
53
|
+
if not isinstance(detail, dict):
|
|
54
|
+
continue
|
|
55
|
+
if str(detail.get("@type", "")).endswith("google.rpc.ErrorInfo") and str(
|
|
56
|
+
detail.get("reason", "")
|
|
57
|
+
).endswith("LIMIT_REACHED"):
|
|
58
|
+
return detail
|
|
59
|
+
return None
|
|
60
|
+
|
|
61
|
+
def is_quota(self):
|
|
62
|
+
return self.quota_info() is not None
|
|
63
|
+
|
|
64
|
+
def __str__(self):
|
|
65
|
+
msg = self.message or f"HTTP {self.status}"
|
|
66
|
+
quota = self.quota_info()
|
|
67
|
+
if quota:
|
|
68
|
+
meta = quota.get("metadata") or {}
|
|
69
|
+
if "limit" in meta:
|
|
70
|
+
return (
|
|
71
|
+
f"{msg} (quota {meta.get('limit_key')}: "
|
|
72
|
+
f"{meta.get('current')} of {meta.get('limit')} used)"
|
|
73
|
+
)
|
|
74
|
+
where = f" on {self.method} {self.path}" if self.method else ""
|
|
75
|
+
return f"{msg} (HTTP {self.status}{where})"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class TimeoutError_(Exception): # pylint: disable=invalid-name
|
|
79
|
+
"""A wait ran out of time (named to avoid shadowing the builtin)."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def is_not_found(err):
|
|
83
|
+
return isinstance(err, NodeRingsError) and err.code == CODE_NOT_FOUND
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def is_busy(err):
|
|
87
|
+
"""The API refuses changes while a VM operation is running."""
|
|
88
|
+
return (
|
|
89
|
+
isinstance(err, NodeRingsError)
|
|
90
|
+
and err.code == CODE_FAILED_PRECONDITION
|
|
91
|
+
and "in progress" in err.message.lower()
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def is_ambiguous(err):
|
|
96
|
+
"""True when a request may or may not have been applied (lost response)."""
|
|
97
|
+
if isinstance(err, NodeRingsError):
|
|
98
|
+
if err.status in (502, 503, 504):
|
|
99
|
+
return True
|
|
100
|
+
if err.status == 429:
|
|
101
|
+
return not err.is_quota()
|
|
102
|
+
return False
|
|
103
|
+
return isinstance(err, (URLError, OSError))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def decode_error(status, body, method="", path=""):
|
|
107
|
+
code, message, details = 0, "", []
|
|
108
|
+
try:
|
|
109
|
+
data = json.loads((body or b"{}").decode("utf-8"))
|
|
110
|
+
if isinstance(data, dict):
|
|
111
|
+
code = int(data.get("code") or 0)
|
|
112
|
+
message = data.get("message") or ""
|
|
113
|
+
details = data.get("details") or []
|
|
114
|
+
else:
|
|
115
|
+
message = str(data)[:300]
|
|
116
|
+
except (ValueError, TypeError, UnicodeDecodeError):
|
|
117
|
+
message = (body or b"").decode("utf-8", "replace").strip()[:300]
|
|
118
|
+
if not code:
|
|
119
|
+
code = {
|
|
120
|
+
404: CODE_NOT_FOUND,
|
|
121
|
+
409: CODE_ALREADY_EXISTS,
|
|
122
|
+
403: CODE_PERMISSION_DENIED,
|
|
123
|
+
401: CODE_UNAUTHENTICATED,
|
|
124
|
+
}.get(status, 0)
|
|
125
|
+
return NodeRingsError(status, code, message, details, method, path)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def new_uuid():
|
|
129
|
+
return str(uuid.uuid4())
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def is_uuid(value):
|
|
133
|
+
return bool(_UUID_RE.match(str(value or "")))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def path_escape(value):
|
|
137
|
+
return quote(str(value), safe="")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def trim_enum(value, prefix):
|
|
141
|
+
"""BILLING_TYPE_USAGE -> usage."""
|
|
142
|
+
if not value:
|
|
143
|
+
return ""
|
|
144
|
+
value = str(value)
|
|
145
|
+
value = value.removeprefix(prefix)
|
|
146
|
+
if value == "UNSPECIFIED":
|
|
147
|
+
return ""
|
|
148
|
+
return value.lower()
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# Values under these keys are free-form maps (user data); their keys are kept as-is.
|
|
152
|
+
OPAQUE_KEYS = frozenset(
|
|
153
|
+
[
|
|
154
|
+
"metadata",
|
|
155
|
+
"continents",
|
|
156
|
+
"countries",
|
|
157
|
+
"regions",
|
|
158
|
+
"environment",
|
|
159
|
+
"instantAppVariables",
|
|
160
|
+
"labels",
|
|
161
|
+
]
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _snake_key(key):
|
|
166
|
+
if not isinstance(key, str):
|
|
167
|
+
return key
|
|
168
|
+
out = []
|
|
169
|
+
for i, ch in enumerate(key):
|
|
170
|
+
if ch.isupper():
|
|
171
|
+
if i and (not key[i - 1].isupper() or (i + 1 < len(key) and key[i + 1].islower())):
|
|
172
|
+
out.append("_")
|
|
173
|
+
out.append(ch.lower())
|
|
174
|
+
else:
|
|
175
|
+
out.append(ch)
|
|
176
|
+
return "".join(out).lstrip("@")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def snake(value):
|
|
180
|
+
"""Convert API camelCase keys to snake_case, recursively."""
|
|
181
|
+
if isinstance(value, dict):
|
|
182
|
+
out = {}
|
|
183
|
+
for key, item in value.items():
|
|
184
|
+
if key in OPAQUE_KEYS and isinstance(item, dict):
|
|
185
|
+
out[_snake_key(key)] = item
|
|
186
|
+
else:
|
|
187
|
+
out[_snake_key(key)] = snake(item)
|
|
188
|
+
return out
|
|
189
|
+
if isinstance(value, list):
|
|
190
|
+
return [snake(v) for v in value]
|
|
191
|
+
return value
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _urllib_open(url, method, data, headers, timeout):
|
|
195
|
+
req = Request(url, data=data, headers=headers, method=method)
|
|
196
|
+
return urlopen(req, timeout=timeout) # nosec B310 - the URL is the configured https API
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class NodeRingsClient: # pylint: disable=too-many-public-methods
|
|
200
|
+
"""JSON client for the NodeRings public API."""
|
|
201
|
+
|
|
202
|
+
def __init__(
|
|
203
|
+
self,
|
|
204
|
+
token,
|
|
205
|
+
api_url=DEFAULT_API_URL,
|
|
206
|
+
organization_id=None,
|
|
207
|
+
timeout=60,
|
|
208
|
+
retries=5,
|
|
209
|
+
user_agent=None,
|
|
210
|
+
opener=None,
|
|
211
|
+
sleep=time.sleep,
|
|
212
|
+
):
|
|
213
|
+
if not token or not str(token).strip():
|
|
214
|
+
raise ValueError(
|
|
215
|
+
"A NodeRings API token is required. Pass it as the driver's key, or set the "
|
|
216
|
+
"NODERINGS_TOKEN environment variable. Create a "
|
|
217
|
+
"service account token in the NodeRings console under Organization, Access "
|
|
218
|
+
"Control, Service accounts."
|
|
219
|
+
)
|
|
220
|
+
self.base = (api_url or DEFAULT_API_URL).rstrip("/")
|
|
221
|
+
if not self.base.startswith(("https://", "http://")):
|
|
222
|
+
raise ValueError(f"api_url must be an absolute URL such as {DEFAULT_API_URL}")
|
|
223
|
+
self.token = str(token).strip()
|
|
224
|
+
self.organization_id = (organization_id or "").strip()
|
|
225
|
+
self.timeout = timeout
|
|
226
|
+
self.retries = max(0, int(retries))
|
|
227
|
+
self.user_agent = user_agent or f"libcloud-noderings/{__version__}"
|
|
228
|
+
self._open = opener or _urllib_open
|
|
229
|
+
self._sleep = sleep
|
|
230
|
+
|
|
231
|
+
# -- transport --------------------------------------------------------------
|
|
232
|
+
|
|
233
|
+
@staticmethod
|
|
234
|
+
def _backoff(attempt):
|
|
235
|
+
delay = min(0.5 * (2 ** min(attempt, 10)), 10.0)
|
|
236
|
+
return delay / 2 + random.uniform(0, delay / 2) # nosec B311 - jitter, not security
|
|
237
|
+
|
|
238
|
+
@staticmethod
|
|
239
|
+
def _retryable(err, retry_unavailable):
|
|
240
|
+
if isinstance(err, NodeRingsError):
|
|
241
|
+
if err.status == 429:
|
|
242
|
+
return not err.is_quota()
|
|
243
|
+
if err.status in (502, 504):
|
|
244
|
+
return True
|
|
245
|
+
if err.status == 503:
|
|
246
|
+
return retry_unavailable
|
|
247
|
+
return False
|
|
248
|
+
return True # connection errors
|
|
249
|
+
|
|
250
|
+
def request(self, method, path, query=None, body=None, retry_unavailable=None, retries=None):
|
|
251
|
+
"""
|
|
252
|
+
Send one API request and return the decoded JSON body, or ``{}``.
|
|
253
|
+
|
|
254
|
+
GET requests retry on 503. Writes do not, because some write endpoints
|
|
255
|
+
(DNS) report validation errors as 503.
|
|
256
|
+
"""
|
|
257
|
+
if retry_unavailable is None:
|
|
258
|
+
retry_unavailable = method == "GET"
|
|
259
|
+
max_retries = self.retries if retries is None else retries
|
|
260
|
+
url = self.base + path
|
|
261
|
+
if query:
|
|
262
|
+
pairs = []
|
|
263
|
+
for key in sorted(query):
|
|
264
|
+
value = query[key]
|
|
265
|
+
if value is None or value == "":
|
|
266
|
+
continue
|
|
267
|
+
if isinstance(value, (list, tuple)):
|
|
268
|
+
pairs.extend((key, str(item)) for item in value)
|
|
269
|
+
elif isinstance(value, bool):
|
|
270
|
+
pairs.append((key, "true" if value else "false"))
|
|
271
|
+
else:
|
|
272
|
+
pairs.append((key, str(value)))
|
|
273
|
+
if pairs:
|
|
274
|
+
url += f"?{urlencode(pairs)}"
|
|
275
|
+
headers = {
|
|
276
|
+
"Authorization": f"Bearer {self.token}",
|
|
277
|
+
"Accept": "application/json",
|
|
278
|
+
"User-Agent": self.user_agent,
|
|
279
|
+
}
|
|
280
|
+
data = None
|
|
281
|
+
if body is not None:
|
|
282
|
+
data = json.dumps(body).encode("utf-8")
|
|
283
|
+
headers["Content-Type"] = "application/json"
|
|
284
|
+
if self.organization_id:
|
|
285
|
+
headers["X-Organization-ID"] = self.organization_id
|
|
286
|
+
|
|
287
|
+
attempt = 0
|
|
288
|
+
while True:
|
|
289
|
+
try:
|
|
290
|
+
with self._open(url, method, data, headers, self.timeout) as resp:
|
|
291
|
+
raw = resp.read()
|
|
292
|
+
if not raw or not raw.strip():
|
|
293
|
+
return {}
|
|
294
|
+
return json.loads(raw.decode("utf-8"))
|
|
295
|
+
except HTTPError as exc:
|
|
296
|
+
try:
|
|
297
|
+
raw = exc.read()
|
|
298
|
+
except Exception: # pylint: disable=broad-except
|
|
299
|
+
raw = b""
|
|
300
|
+
err = decode_error(exc.code, raw, method, path)
|
|
301
|
+
except (URLError, OSError) as exc:
|
|
302
|
+
err = exc
|
|
303
|
+
if attempt >= max_retries or not self._retryable(err, retry_unavailable):
|
|
304
|
+
raise err
|
|
305
|
+
self._sleep(self._backoff(attempt))
|
|
306
|
+
attempt += 1
|
|
307
|
+
|
|
308
|
+
def get(self, path, query=None):
|
|
309
|
+
return self.request("GET", path, query=query)
|
|
310
|
+
|
|
311
|
+
def list_all(self, path, key, query=None):
|
|
312
|
+
params = {"page": "0", "pageSize": "-1"}
|
|
313
|
+
params.update(query or {})
|
|
314
|
+
return self.get(path, params).get(key) or []
|
|
315
|
+
|
|
316
|
+
def list_paged(self, path, key, query=None, page_size=100):
|
|
317
|
+
out = []
|
|
318
|
+
page = 0
|
|
319
|
+
while True:
|
|
320
|
+
params = {"page": str(page), "pageSize": str(page_size)}
|
|
321
|
+
params.update(query or {})
|
|
322
|
+
data = self.get(path, params)
|
|
323
|
+
items = data.get(key) or []
|
|
324
|
+
out.extend(items)
|
|
325
|
+
total = int(data.get("totalCount") or 0)
|
|
326
|
+
if len(items) < page_size or len(out) >= total:
|
|
327
|
+
return out
|
|
328
|
+
page += 1
|
|
329
|
+
|
|
330
|
+
# -- organization and billing -------------------------------------------------
|
|
331
|
+
|
|
332
|
+
def get_organization(self):
|
|
333
|
+
return self.get("/v1/organization").get("organization")
|
|
334
|
+
|
|
335
|
+
def get_credit_balance(self):
|
|
336
|
+
return self.get("/v1/credits/balance")
|
|
337
|
+
|
|
338
|
+
# -- SSH keys -----------------------------------------------------------------
|
|
339
|
+
|
|
340
|
+
def list_ssh_keys(self):
|
|
341
|
+
return self.list_all("/v1/ssh-keys", "sshKeys")
|
|
342
|
+
|
|
343
|
+
def create_ssh_key(self, name, public_key):
|
|
344
|
+
return self.request(
|
|
345
|
+
"POST", "/v1/ssh-keys", body={"name": name, "publicKey": public_key}
|
|
346
|
+
).get("sshKey")
|
|
347
|
+
|
|
348
|
+
def delete_ssh_key(self, key_id):
|
|
349
|
+
self.request("DELETE", f"/v1/ssh-keys/{path_escape(key_id)}")
|
|
350
|
+
|
|
351
|
+
# -- DNS ----------------------------------------------------------------------
|
|
352
|
+
|
|
353
|
+
@staticmethod
|
|
354
|
+
def zone_path(zone_id):
|
|
355
|
+
return f"/v1/dns/zones/{path_escape(zone_id)}"
|
|
356
|
+
|
|
357
|
+
def list_dns_zones(self):
|
|
358
|
+
return self.list_all("/v1/dns/zones", "zones")
|
|
359
|
+
|
|
360
|
+
def get_dns_zone(self, zone_id):
|
|
361
|
+
return self.get(self.zone_path(zone_id)).get("zone")
|
|
362
|
+
|
|
363
|
+
def create_dns_zone(self, name):
|
|
364
|
+
return self.request("POST", "/v1/dns/zones", body={"name": name}).get("zone")
|
|
365
|
+
|
|
366
|
+
def delete_dns_zone(self, zone_id, force=False):
|
|
367
|
+
self.request("DELETE", self.zone_path(zone_id), query={"force": "true"} if force else None)
|
|
368
|
+
|
|
369
|
+
def list_dns_records(self, zone_id, name=None, rrtype=None):
|
|
370
|
+
return self.list_paged(
|
|
371
|
+
f"{self.zone_path(zone_id)}/records", "records", {"name": name, "type": rrtype}
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
def upsert_dns_record(self, zone_id, record):
|
|
375
|
+
return self.request("PUT", f"{self.zone_path(zone_id)}/records", body={"record": record})
|
|
376
|
+
|
|
377
|
+
def delete_dns_record(self, zone_id, name, rrtype):
|
|
378
|
+
self.request(
|
|
379
|
+
"DELETE", f"{self.zone_path(zone_id)}/records", query={"name": name, "type": rrtype}
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
def get_dnssec(self, zone_id):
|
|
383
|
+
return self.get(f"{self.zone_path(zone_id)}/dnssec")
|
|
384
|
+
|
|
385
|
+
def enable_dnssec(self, zone_id):
|
|
386
|
+
return self.request("POST", f"{self.zone_path(zone_id)}/dnssec/enable", body={})
|
|
387
|
+
|
|
388
|
+
def disable_dnssec(self, zone_id, force=False):
|
|
389
|
+
return self.request(
|
|
390
|
+
"POST", f"{self.zone_path(zone_id)}/dnssec/disable", body={"force": force}
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
# -- firewall -----------------------------------------------------------------
|
|
394
|
+
|
|
395
|
+
def list_firewall_address_groups(self, name=None):
|
|
396
|
+
return self.list_all("/v1/firewall/address-groups", "groups", {"name": name})
|
|
397
|
+
|
|
398
|
+
def list_firewall_rulesets(self, name=None):
|
|
399
|
+
return self.list_all("/v1/firewall/rulesets", "rulesets", {"name": name})
|
|
400
|
+
|
|
401
|
+
def get_firewall_ruleset(self, ruleset_id):
|
|
402
|
+
return self.get(f"/v1/firewall/rulesets/{path_escape(ruleset_id)}")
|
|
403
|
+
|
|
404
|
+
def create_firewall_ruleset(self, name):
|
|
405
|
+
out = self.request("POST", "/v1/firewall/rulesets", body={"ruleset": {"name": name}}).get(
|
|
406
|
+
"ruleset"
|
|
407
|
+
)
|
|
408
|
+
if out and out.get("id"):
|
|
409
|
+
return out
|
|
410
|
+
return find_by_name(self.list_firewall_rulesets(name), name)
|
|
411
|
+
|
|
412
|
+
def delete_firewall_ruleset(self, ruleset_id, force=False):
|
|
413
|
+
self.request(
|
|
414
|
+
"DELETE",
|
|
415
|
+
f"/v1/firewall/rulesets/{path_escape(ruleset_id)}",
|
|
416
|
+
query={"force": "true"} if force else None,
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
def list_firewall_rules(self, ruleset_id):
|
|
420
|
+
rules = self.list_all(f"/v1/firewall/rulesets/{path_escape(ruleset_id)}/rules", "rules")
|
|
421
|
+
return sorted(rules, key=lambda r: int(r.get("position") or 0))
|
|
422
|
+
|
|
423
|
+
def create_firewall_rule(self, ruleset_id, rule):
|
|
424
|
+
return self.request(
|
|
425
|
+
"POST",
|
|
426
|
+
f"/v1/firewall/rulesets/{path_escape(ruleset_id)}/rules",
|
|
427
|
+
body={"rule": rule},
|
|
428
|
+
).get("rule")
|
|
429
|
+
|
|
430
|
+
def update_firewall_rule(self, rule_id, rule):
|
|
431
|
+
return self.request(
|
|
432
|
+
"PATCH", f"/v1/firewall/rules/{path_escape(rule_id)}", body={"rule": rule}
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
def move_firewall_rule(self, rule_id, target_id, position="FIREWALL_RULE_POSITION_BEFORE"):
|
|
436
|
+
return self.request(
|
|
437
|
+
"POST",
|
|
438
|
+
f"/v1/firewall/rules/{path_escape(rule_id)}/move",
|
|
439
|
+
body={"targetRuleId": target_id, "position": position},
|
|
440
|
+
)
|
|
441
|
+
|
|
442
|
+
def delete_firewall_rule(self, rule_id):
|
|
443
|
+
self.request("DELETE", f"/v1/firewall/rules/{path_escape(rule_id)}")
|
|
444
|
+
|
|
445
|
+
# -- virtual machines ---------------------------------------------------------
|
|
446
|
+
|
|
447
|
+
@staticmethod
|
|
448
|
+
def vm_path(vm_id):
|
|
449
|
+
return f"/v1/virtual-machines/{path_escape(vm_id)}"
|
|
450
|
+
|
|
451
|
+
def list_virtual_machines(self):
|
|
452
|
+
return self.list_all("/v1/virtual-machines", "virtualMachines")
|
|
453
|
+
|
|
454
|
+
def get_virtual_machine(self, vm_id):
|
|
455
|
+
vm = self.get(self.vm_path(vm_id))
|
|
456
|
+
if not vm or not vm.get("id"):
|
|
457
|
+
raise NodeRingsError(404, CODE_NOT_FOUND, f"virtual machine {vm_id} not found")
|
|
458
|
+
return vm
|
|
459
|
+
|
|
460
|
+
def create_virtual_machine(self, body):
|
|
461
|
+
# Never retried blindly: the caller handles ambiguous failures.
|
|
462
|
+
return self.request("POST", "/v1/virtual-machines", body=body, retries=0).get(
|
|
463
|
+
"virtualMachine"
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
def update_virtual_machine_tags(self, vm_id, add=None, remove=None):
|
|
467
|
+
return self.request(
|
|
468
|
+
"PATCH", self.vm_path(vm_id), body={"addTags": add or [], "removeTags": remove or []}
|
|
469
|
+
)
|
|
470
|
+
|
|
471
|
+
def delete_virtual_machine(self, vm_id):
|
|
472
|
+
self.request("DELETE", self.vm_path(vm_id))
|
|
473
|
+
|
|
474
|
+
def vm_action(self, vm_id, action, body=None):
|
|
475
|
+
return self.request(
|
|
476
|
+
"POST", f"{self.vm_path(vm_id)}:{action}", body=body if body is not None else {}
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
# -- marketplace and catalog --------------------------------------------------
|
|
480
|
+
|
|
481
|
+
def list_marketplace_regions(self, asset_type=None):
|
|
482
|
+
return (
|
|
483
|
+
self.get("/v1/marketplace/regions", {"filterAssetType": asset_type}).get("regions")
|
|
484
|
+
or []
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
def list_available_plans(self, country=None, city=None, billing_type=None, asset_type=None):
|
|
488
|
+
return (
|
|
489
|
+
self.get(
|
|
490
|
+
"/v1/marketplace/plans",
|
|
491
|
+
{
|
|
492
|
+
"filterCountry": country,
|
|
493
|
+
"filterCity": city,
|
|
494
|
+
"filterBillingType": billing_type,
|
|
495
|
+
"filterAssetType": asset_type,
|
|
496
|
+
},
|
|
497
|
+
).get("plans")
|
|
498
|
+
or []
|
|
499
|
+
)
|
|
500
|
+
|
|
501
|
+
def get_marketplace_plan(self, plan_id):
|
|
502
|
+
return self.get(f"/v1/marketplace/plans/{path_escape(plan_id)}")
|
|
503
|
+
|
|
504
|
+
def list_providers(self, plan_code, country, city, billing_type=None, ipv6_only=False):
|
|
505
|
+
query = {
|
|
506
|
+
"page": "0",
|
|
507
|
+
"pageSize": "-1",
|
|
508
|
+
"filterPlanCode": plan_code,
|
|
509
|
+
"filterCountry": country,
|
|
510
|
+
"filterCity": city,
|
|
511
|
+
"filterBillingType": billing_type,
|
|
512
|
+
}
|
|
513
|
+
if ipv6_only:
|
|
514
|
+
query["filterIpv6AvailableOnly"] = "true"
|
|
515
|
+
return self.get("/v1/marketplace/providers", query).get("providers") or []
|
|
516
|
+
|
|
517
|
+
def get_provider(self, provider_id):
|
|
518
|
+
return self.get(f"/v1/marketplace/providers/{path_escape(provider_id)}").get("provider")
|
|
519
|
+
|
|
520
|
+
def list_distros(self):
|
|
521
|
+
return self.get("/v1/distros").get("distros") or []
|
|
522
|
+
|
|
523
|
+
|
|
524
|
+
class Waiter:
|
|
525
|
+
"""Polls with a growing interval until a check reports done or a timeout passes."""
|
|
526
|
+
|
|
527
|
+
def __init__(self, timeout, interval=2.0, max_interval=15.0, sleep=time.sleep, clock=time.time):
|
|
528
|
+
self.deadline = clock() + timeout
|
|
529
|
+
self.interval = interval
|
|
530
|
+
self.max_interval = max_interval
|
|
531
|
+
self._sleep = sleep
|
|
532
|
+
self._clock = clock
|
|
533
|
+
|
|
534
|
+
def wait(self, what, check):
|
|
535
|
+
delay = self.interval
|
|
536
|
+
while True:
|
|
537
|
+
done, value = check()
|
|
538
|
+
if done:
|
|
539
|
+
return value
|
|
540
|
+
if self._clock() + delay > self.deadline:
|
|
541
|
+
raise TimeoutError_(f"timed out waiting for {what}")
|
|
542
|
+
self._sleep(delay)
|
|
543
|
+
delay = min(delay * 1.5, self.max_interval)
|
|
544
|
+
|
|
545
|
+
def retry_busy(self, func):
|
|
546
|
+
"""Run func until the VM stops reporting 'operation in progress'."""
|
|
547
|
+
last = [None]
|
|
548
|
+
|
|
549
|
+
def check():
|
|
550
|
+
try:
|
|
551
|
+
return True, func()
|
|
552
|
+
except NodeRingsError as exc:
|
|
553
|
+
if is_busy(exc):
|
|
554
|
+
last[0] = exc
|
|
555
|
+
return False, None
|
|
556
|
+
raise
|
|
557
|
+
|
|
558
|
+
try:
|
|
559
|
+
return self.wait("the virtual machine to finish its current operation", check)
|
|
560
|
+
except TimeoutError_ as exc:
|
|
561
|
+
raise TimeoutError_(f"{exc} (last error: {last[0]})") from exc
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def find_by_name(items, name):
|
|
565
|
+
for item in items or []:
|
|
566
|
+
if item.get("name") == name:
|
|
567
|
+
return item
|
|
568
|
+
return None
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def client_from_config(conf, user_agent=None):
|
|
572
|
+
"""
|
|
573
|
+
Build a client from a config mapping.
|
|
574
|
+
|
|
575
|
+
Keys: ``token`` (falls back to ``NODERINGS_TOKEN``), ``api_url``,
|
|
576
|
+
``organization_id``, ``timeout``, ``retries``.
|
|
577
|
+
"""
|
|
578
|
+
conf = conf or {}
|
|
579
|
+
token = conf.get("token")
|
|
580
|
+
if not token:
|
|
581
|
+
for var in TOKEN_ENV_VARS:
|
|
582
|
+
if os.environ.get(var):
|
|
583
|
+
token = os.environ[var]
|
|
584
|
+
break
|
|
585
|
+
return NodeRingsClient(
|
|
586
|
+
token=token,
|
|
587
|
+
api_url=conf.get("api_url") or os.environ.get("NODERINGS_API_URL") or DEFAULT_API_URL,
|
|
588
|
+
organization_id=conf.get("organization_id") or os.environ.get("NODERINGS_ORGANIZATION_ID"),
|
|
589
|
+
timeout=int(conf.get("timeout") or 60),
|
|
590
|
+
retries=int(conf.get("retries") if conf.get("retries") is not None else 5),
|
|
591
|
+
user_agent=user_agent,
|
|
592
|
+
)
|