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.
@@ -0,0 +1,391 @@
1
+ """
2
+ Virtual machine helpers shared by the execution module, the state module and
3
+ the drivers.
4
+ """
5
+
6
+ import time
7
+
8
+ from libcloud_noderings._api.client import NodeRingsError
9
+ from libcloud_noderings._api.client import TimeoutError_
10
+ from libcloud_noderings._api.client import Waiter
11
+ from libcloud_noderings._api.client import is_ambiguous
12
+ from libcloud_noderings._api.client import is_not_found
13
+ from libcloud_noderings._api.client import is_uuid
14
+ from libcloud_noderings._api.client import new_uuid
15
+ from libcloud_noderings._api.client import snake
16
+ from libcloud_noderings._api.client import trim_enum
17
+ from libcloud_noderings._api.marketplace import find_offers
18
+ from libcloud_noderings._api.marketplace import no_offer_message
19
+ from libcloud_noderings._api.marketplace import offer_view
20
+
21
+ NONCE_TAG_PREFIX = "libcloud-create-"
22
+ DEFAULT_WAIT_TIMEOUT = 900
23
+
24
+
25
+ class NodeRingsUsageError(Exception):
26
+ """The caller asked for something that cannot work (bad name, ambiguous match)."""
27
+
28
+
29
+ def power_state(vm):
30
+ op = (vm or {}).get("operationStatus") or ""
31
+ if op in ("OPERATION_STATUS_STARTED", "OPERATION_STATUS_RESTARTED"):
32
+ return "running"
33
+ if op == "OPERATION_STATUS_STOPPED":
34
+ return "stopped"
35
+ return trim_enum(op, "OPERATION_STATUS_") or "unknown"
36
+
37
+
38
+ def vm_view(vm):
39
+ """The VM as a dict: snake_case keys plus a few friendly fields."""
40
+ if not vm:
41
+ return {}
42
+ out = snake(vm)
43
+ out["power_state"] = power_state(vm)
44
+ out["distro"] = trim_enum(vm.get("distro"), "DISTRO_")
45
+ out["billing_type"] = trim_enum(vm.get("planBillingType"), "BILLING_TYPE_")
46
+ out["provisioning_status"] = trim_enum(vm.get("crStatus"), "CR_STATUS_")
47
+ out["tags"] = sorted(t for t in vm.get("tags") or [] if not t.startswith(NONCE_TAG_PREFIX))
48
+ return out
49
+
50
+
51
+ def find_vm(client, name_or_id):
52
+ """Return the VM with this ID or unique hostname, or None."""
53
+ if is_uuid(name_or_id):
54
+ try:
55
+ return client.get_virtual_machine(name_or_id)
56
+ except NodeRingsError as exc:
57
+ if is_not_found(exc):
58
+ return None
59
+ raise
60
+ matches = [v for v in client.list_virtual_machines() if v.get("hostname") == name_or_id]
61
+ if len(matches) > 1:
62
+ raise NodeRingsUsageError(
63
+ f"{len(matches)} virtual machines are named {name_or_id}; use the ID of the one you "
64
+ f"mean: {', '.join(v.get('id') for v in matches)}"
65
+ )
66
+ if not matches:
67
+ return None
68
+ # List entries omit details such as add-on subscriptions; read the full VM.
69
+ return client.get_virtual_machine(matches[0]["id"])
70
+
71
+
72
+ def translate_create_error(err):
73
+ msg = str(err)
74
+ low = msg.lower()
75
+ if "payment method" in low:
76
+ msg += (
77
+ ". Add a payment method to the organization in the NodeRings console. Paid plans, "
78
+ "including usage-billed ones, need one."
79
+ )
80
+ elif "runway" in low or "insufficient" in low:
81
+ msg += ". Top up the organization's credit balance, or choose a cheaper plan."
82
+ elif "no vm template" in low:
83
+ msg += (
84
+ ". This provider has no image for the chosen distro in this region. Pick another "
85
+ "distro, or another offer."
86
+ )
87
+ elif "capacity" in low or "marketplace-ready node" in low:
88
+ msg += ". The region is out of capacity for this plan. Try another provider or city."
89
+ if isinstance(err, NodeRingsError) and err.is_quota():
90
+ msg += (
91
+ ". The organization has reached its virtual machine quota. Delete unused VMs or ask "
92
+ "NodeRings support to raise the limit."
93
+ )
94
+ return msg
95
+
96
+
97
+ def choose_offer(
98
+ client,
99
+ plan_code,
100
+ country,
101
+ city,
102
+ billing_type="usage",
103
+ provider_id=None,
104
+ require_capabilities=None,
105
+ require_ipv6=False,
106
+ sort="price",
107
+ ):
108
+ """Return ``(plan_id, region_id, offer)`` for the best matching offer."""
109
+ offers, located = find_offers(
110
+ client,
111
+ plan_code,
112
+ country,
113
+ city,
114
+ billing_type=billing_type,
115
+ provider_id=provider_id,
116
+ require_capabilities=require_capabilities or [],
117
+ require_ipv6=require_ipv6,
118
+ sort=sort,
119
+ )
120
+ if not offers:
121
+ raise NodeRingsUsageError(no_offer_message(plan_code, country, city, billing_type, located))
122
+ best = offers[0]
123
+ return best["plan_id"], best["region_id"], offer_view(best)
124
+
125
+
126
+ def resolve_ssh_keys(client, keys):
127
+ """SSH key names or IDs -> IDs."""
128
+ if not keys:
129
+ return []
130
+ existing = client.list_ssh_keys()
131
+ out = []
132
+ for key in keys:
133
+ match = next((k for k in existing if k.get("id") == key or k.get("name") == key), None)
134
+ if not match:
135
+ raise NodeRingsUsageError(
136
+ f"no SSH key is named {key}; import it with driver.import_key_pair_from_string()"
137
+ )
138
+ out.append(match["id"])
139
+ return out
140
+
141
+
142
+ def resolve_ruleset(client, ruleset):
143
+ """A firewall ruleset name or ID -> ID."""
144
+ if not ruleset:
145
+ return ""
146
+ for rs in client.list_firewall_rulesets():
147
+ if ruleset in (rs.get("id"), rs.get("name")):
148
+ return rs["id"]
149
+ raise NodeRingsUsageError(f"no firewall ruleset is named {ruleset}")
150
+
151
+
152
+ def wait_provisioned(client, vm_id, timeout=DEFAULT_WAIT_TIMEOUT, sleep=time.sleep):
153
+ def check():
154
+ vm = client.get_virtual_machine(vm_id)
155
+ status = vm.get("crStatus")
156
+ if status == "CR_STATUS_APPLIED":
157
+ return True, vm
158
+ if status == "CR_STATUS_FAILED":
159
+ raise RuntimeError(
160
+ f"provisioning of virtual machine {vm_id} failed. The API does not report why; "
161
+ "delete it and try another offer, or contact the provider"
162
+ )
163
+ return False, None
164
+
165
+ return Waiter(timeout, sleep=sleep).wait(f"virtual machine {vm_id} to be provisioned", check)
166
+
167
+
168
+ def wait_idle(client, vm_id, check_vm, what, timeout=DEFAULT_WAIT_TIMEOUT, sleep=time.sleep):
169
+ def check():
170
+ vm = client.get_virtual_machine(vm_id)
171
+ return (check_vm(vm) and vm.get("crStatus") != "CR_STATUS_PROCESSING"), vm
172
+
173
+ return Waiter(timeout, sleep=sleep).wait(what, check)
174
+
175
+
176
+ def wait_settled(client, vm_id, timeout=DEFAULT_WAIT_TIMEOUT, sleep=time.sleep):
177
+ """Wait while the VM is in a transitional power state (created, reinstalling)."""
178
+ return wait_idle(
179
+ client,
180
+ vm_id,
181
+ lambda vm: power_state(vm) in ("running", "stopped"),
182
+ "the virtual machine to finish booting",
183
+ timeout,
184
+ sleep,
185
+ )
186
+
187
+
188
+ def set_power(client, vm_id, want, wait=True, timeout=DEFAULT_WAIT_TIMEOUT, sleep=time.sleep):
189
+ """Start (``want="running"``), stop (``"stopped"``) or restart (``"restarted"``) a VM."""
190
+ action = {"running": "start", "stopped": "stop", "restarted": "restart"}[want]
191
+ Waiter(timeout, sleep=sleep).retry_busy(lambda: client.vm_action(vm_id, action))
192
+ if not wait:
193
+ return client.get_virtual_machine(vm_id)
194
+ target = "running" if want == "restarted" else want
195
+ return wait_idle(
196
+ client,
197
+ vm_id,
198
+ lambda vm: power_state(vm) == target,
199
+ f"the virtual machine to be {target}",
200
+ timeout,
201
+ sleep,
202
+ )
203
+
204
+
205
+ def attach_firewall(
206
+ client, vm_id, ruleset_id, wait=True, timeout=DEFAULT_WAIT_TIMEOUT, sleep=time.sleep
207
+ ):
208
+ Waiter(timeout, sleep=sleep).retry_busy(
209
+ lambda: client.vm_action(vm_id, "attach-firewall", {"rulesetId": ruleset_id})
210
+ )
211
+ if wait:
212
+ return wait_idle(
213
+ client,
214
+ vm_id,
215
+ lambda vm: vm.get("firewallRulesetId") == ruleset_id,
216
+ "the firewall to be applied",
217
+ timeout,
218
+ sleep,
219
+ )
220
+ return client.get_virtual_machine(vm_id)
221
+
222
+
223
+ def detach_firewall(
224
+ client, vm_id, ruleset_id, wait=True, timeout=DEFAULT_WAIT_TIMEOUT, sleep=time.sleep
225
+ ):
226
+ Waiter(timeout, sleep=sleep).retry_busy(
227
+ lambda: client.vm_action(vm_id, "detach-firewall", {"rulesetId": ruleset_id})
228
+ )
229
+ if wait:
230
+ return wait_idle(
231
+ client,
232
+ vm_id,
233
+ lambda vm: not vm.get("firewallRulesetId"),
234
+ "the firewall to be removed",
235
+ timeout,
236
+ sleep,
237
+ )
238
+ return client.get_virtual_machine(vm_id)
239
+
240
+
241
+ def reinstall(
242
+ client,
243
+ vm_id,
244
+ hostname,
245
+ distro,
246
+ ssh_key_ids=None,
247
+ password=None,
248
+ wait=True,
249
+ timeout=DEFAULT_WAIT_TIMEOUT,
250
+ sleep=time.sleep,
251
+ ):
252
+ """Reinstall the operating system. This erases the disk; the IP addresses stay."""
253
+ body = {"hostname": hostname or "", "distro": f"DISTRO_{distro.upper()}"}
254
+ if ssh_key_ids:
255
+ body["sshKeyIds"] = ssh_key_ids
256
+ if password:
257
+ body["password"] = password
258
+ Waiter(timeout, sleep=sleep).retry_busy(lambda: client.vm_action(vm_id, "reinstall", body))
259
+ if not wait:
260
+ return client.get_virtual_machine(vm_id)
261
+
262
+ def check():
263
+ vm = client.get_virtual_machine(vm_id)
264
+ status = vm.get("reinstallStatus")
265
+ if status == "REINSTALL_STATUS_FAILED":
266
+ raise RuntimeError(
267
+ f"the reinstall of virtual machine {vm_id} failed; the API does not report why"
268
+ )
269
+ return (
270
+ status == "REINSTALL_STATUS_COMPLETED" and vm.get("crStatus") != "CR_STATUS_PROCESSING",
271
+ vm,
272
+ )
273
+
274
+ # The status may still read COMPLETED from an earlier reinstall for a moment.
275
+ sleep(3)
276
+ Waiter(timeout, sleep=sleep).wait("the reinstall to finish", check)
277
+ return wait_settled(client, vm_id, timeout, sleep)
278
+
279
+
280
+ def order_vm(
281
+ client,
282
+ hostname,
283
+ plan_id,
284
+ region_id,
285
+ distro=None,
286
+ ssh_key_ids=None,
287
+ password=None,
288
+ tags=None,
289
+ ruleset_id=None,
290
+ wait=True,
291
+ timeout=DEFAULT_WAIT_TIMEOUT,
292
+ sleep=time.sleep,
293
+ ):
294
+ """
295
+ Order a VM and return it. Safe against lost responses: an ambiguous failure
296
+ is retried with the same idempotency key, and free plans (which ignore the
297
+ key) are tagged with a nonce so the VM is found instead of ordered twice.
298
+ """
299
+ body = {"hostname": hostname, "planId": plan_id, "regionId": region_id}
300
+ body["idempotencyKey"] = new_uuid()
301
+ if distro:
302
+ body["distro"] = f"DISTRO_{distro.upper()}"
303
+ if ssh_key_ids:
304
+ body["sshKeyIds"] = ssh_key_ids
305
+ if password:
306
+ body["password"] = password
307
+ tags = sorted(set(tags or []))
308
+
309
+ nonce = ""
310
+ try:
311
+ free = client.get_marketplace_plan(plan_id).get("billingType") == "BILLING_TYPE_FREE"
312
+ except NodeRingsError:
313
+ free = True
314
+ if free:
315
+ nonce = NONCE_TAG_PREFIX + new_uuid()
316
+ tags = tags + [nonce]
317
+ if tags:
318
+ body["tags"] = tags
319
+
320
+ def find_by_nonce():
321
+ for vm in client.list_virtual_machines():
322
+ if nonce in (vm.get("tags") or []):
323
+ return vm
324
+ return None
325
+
326
+ vm, last_err, new_key = None, None, False
327
+ for attempt in range(6):
328
+ try:
329
+ vm = client.create_virtual_machine(body)
330
+ break
331
+ except NodeRingsError as exc:
332
+ last_err = exc
333
+ if exc.code == 9 and "new idempotency key" in exc.message.lower() and not new_key:
334
+ new_key = True
335
+ body["idempotencyKey"] = new_uuid()
336
+ continue
337
+ if not is_ambiguous(exc):
338
+ raise NodeRingsUsageError(
339
+ f"ordering virtual machine {hostname}: {translate_create_error(exc)}"
340
+ ) from exc
341
+ except OSError as exc:
342
+ last_err = exc
343
+ if nonce:
344
+ found = find_by_nonce()
345
+ if found:
346
+ vm = found
347
+ break
348
+ sleep(min(2 * (attempt + 1), 10))
349
+ else:
350
+ raise NodeRingsUsageError(
351
+ f"ordering virtual machine {hostname}: {last_err}. The order may or may not have "
352
+ "been placed; check the console before trying again"
353
+ )
354
+ if (not vm or not vm.get("id")) and nonce:
355
+ vm = find_by_nonce()
356
+ if not vm or not vm.get("id"):
357
+ raise NodeRingsUsageError(
358
+ f"the API accepted the order for {hostname} but did not return the new virtual "
359
+ "machine; check the console before trying again"
360
+ )
361
+ vm_id = vm["id"]
362
+ if wait or ruleset_id or nonce:
363
+ wait_provisioned(client, vm_id, timeout, sleep)
364
+ # The VM reads CREATED until the platform has booted it, then STARTED.
365
+ wait_settled(client, vm_id, timeout, sleep)
366
+ if nonce:
367
+ try:
368
+ client.update_virtual_machine_tags(vm_id, remove=[nonce])
369
+ except NodeRingsError:
370
+ pass
371
+ if ruleset_id:
372
+ attach_firewall(client, vm_id, ruleset_id, wait, timeout, sleep)
373
+ return client.get_virtual_machine(vm_id)
374
+
375
+
376
+ __all__ = [
377
+ "NodeRingsUsageError",
378
+ "TimeoutError_",
379
+ "attach_firewall",
380
+ "choose_offer",
381
+ "detach_firewall",
382
+ "find_vm",
383
+ "order_vm",
384
+ "power_state",
385
+ "reinstall",
386
+ "resolve_ruleset",
387
+ "resolve_ssh_keys",
388
+ "set_power",
389
+ "vm_view",
390
+ "wait_settled",
391
+ ]
@@ -0,0 +1,162 @@
1
+ """
2
+ DNS name and record-value helpers.
3
+ """
4
+
5
+ import ipaddress
6
+
7
+ RECORD_TYPES = [
8
+ "A",
9
+ "AAAA",
10
+ "ALIAS",
11
+ "CAA",
12
+ "CERT",
13
+ "CNAME",
14
+ "DNAME",
15
+ "DS",
16
+ "HINFO",
17
+ "HTTPS",
18
+ "LOC",
19
+ "MX",
20
+ "NAPTR",
21
+ "NS",
22
+ "OPENPGPKEY",
23
+ "PTR",
24
+ "RP",
25
+ "SMIMEA",
26
+ "SRV",
27
+ "SSHFP",
28
+ "SVCB",
29
+ "TLSA",
30
+ "TXT",
31
+ ]
32
+ GEO_RECORD_TYPES = ["A", "AAAA", "CNAME", "NAPTR", "SRV"]
33
+ SINGLE_VALUE_TYPES = frozenset(["CNAME", "DNAME", "ALIAS"])
34
+
35
+
36
+ def normalize_zone_name(name):
37
+ return (name or "").strip().lower().rstrip(".")
38
+
39
+
40
+ def relative_name(name, zone):
41
+ """www.example.com. in example.com -> www; the apex -> @."""
42
+ n = (name or "").strip().lower()
43
+ z = normalize_zone_name(zone)
44
+ if n in ("", "@"):
45
+ return "@"
46
+ n = n.rstrip(".")
47
+ if z:
48
+ if n == z:
49
+ return "@"
50
+ if n.endswith(f".{z}"):
51
+ n = n[: -len(z) - 1]
52
+ return n
53
+
54
+
55
+ def validate_values(rrtype, values):
56
+ """Return an error message, or None when the values are acceptable."""
57
+ if not values:
58
+ return "at least one record value is required"
59
+ if rrtype in SINGLE_VALUE_TYPES and len(values) > 1:
60
+ return f"{rrtype} records take exactly one value"
61
+ for v in values:
62
+ v = str(v)
63
+ if not v.strip():
64
+ return "record values must not be empty"
65
+ if rrtype in ("A", "AAAA", "ALIAS"):
66
+ try:
67
+ ip = ipaddress.ip_address(v.strip())
68
+ except ValueError:
69
+ ip = None
70
+ if rrtype == "A" and (ip is None or ip.version != 4):
71
+ return f"{v!r} is not an IPv4 address"
72
+ if rrtype == "AAAA" and (ip is None or ip.version != 6 or ip.ipv4_mapped):
73
+ return f"{v!r} is not an IPv6 address"
74
+ if rrtype == "ALIAS" and ip is not None:
75
+ return "ALIAS must point to a hostname, not an address"
76
+ if rrtype == "TXT" and len(v) > 4096:
77
+ return "TXT values are limited to 4096 characters"
78
+ return None
79
+
80
+
81
+ def _fqdn(h):
82
+ h = (h or "").strip().lower()
83
+ if h in ("", "."):
84
+ return h
85
+ return f"{h.rstrip('.')}."
86
+
87
+
88
+ def canonical(rrtype, v):
89
+ """A comparable form of one value: the API may lowercase names or add trailing dots."""
90
+ v = str(v).strip()
91
+ if rrtype == "TXT":
92
+ return v
93
+ if rrtype in ("A", "AAAA"):
94
+ try:
95
+ return str(ipaddress.ip_address(v))
96
+ except ValueError:
97
+ return v.lower()
98
+ if rrtype in ("CNAME", "DNAME", "ALIAS", "NS", "PTR"):
99
+ return _fqdn(v)
100
+ f = v.split()
101
+ if rrtype == "MX" and len(f) == 2:
102
+ return f"{f[0]} {_fqdn(f[1])}"
103
+ if rrtype == "SRV" and len(f) == 4:
104
+ return f"{' '.join(f[:3])} {_fqdn(f[3])}"
105
+ return " ".join(v.lower().split())
106
+
107
+
108
+ def same_values(rrtype, a, b):
109
+ return sorted(canonical(rrtype, x) for x in a or []) == sorted(
110
+ canonical(rrtype, x) for x in b or []
111
+ )
112
+
113
+
114
+ def _utf8_start(b):
115
+ return (b & 0xC0) != 0x80
116
+
117
+
118
+ def quote_txt(v):
119
+ """Split a TXT value into 255-byte quoted strings, as the API expects."""
120
+ raw = str(v).encode("utf-8")
121
+ parts = []
122
+ while len(raw) > 255:
123
+ cut = 255
124
+ while cut > 0 and not _utf8_start(raw[cut]):
125
+ cut -= 1
126
+ parts.append(raw[:cut])
127
+ raw = raw[cut:]
128
+ parts.append(raw)
129
+ out = []
130
+ for p in parts:
131
+ s = p.decode("utf-8").replace("\\", "\\\\").replace('"', '\\"')
132
+ out.append(f'"{s}"')
133
+ return " ".join(out)
134
+
135
+
136
+ def unquote_txt(v):
137
+ """Join the API's quoted TXT strings back into one value."""
138
+ v = str(v).strip()
139
+ if not v.startswith('"'):
140
+ return v
141
+ out = []
142
+ inside = False
143
+ i = 0
144
+ while i < len(v):
145
+ c = v[i]
146
+ if c == '"':
147
+ inside = not inside
148
+ elif c == "\\" and inside and i + 1 < len(v):
149
+ i += 1
150
+ out.append(v[i])
151
+ elif inside:
152
+ out.append(c)
153
+ i += 1
154
+ return "".join(out)
155
+
156
+
157
+ def to_api(rrtype, v):
158
+ return quote_txt(v) if rrtype == "TXT" else str(v).strip()
159
+
160
+
161
+ def from_api(rrtype, v):
162
+ return unquote_txt(v) if rrtype == "TXT" else str(v).strip()