saltext.noderings 0.1.0__py2.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.
- saltext/noderings/__init__.py +28 -0
- saltext/noderings/clouds/__init__.py +0 -0
- saltext/noderings/clouds/noderings_mod.py +457 -0
- saltext/noderings/modules/__init__.py +0 -0
- saltext/noderings/modules/noderings_mod.py +996 -0
- saltext/noderings/states/__init__.py +0 -0
- saltext/noderings/states/noderings_mod.py +562 -0
- saltext/noderings/utils/__init__.py +0 -0
- saltext/noderings/utils/client.py +593 -0
- saltext/noderings/utils/compute.py +392 -0
- saltext/noderings/utils/dns.py +162 -0
- saltext/noderings/utils/firewall.py +323 -0
- saltext/noderings/utils/marketplace.py +182 -0
- saltext/noderings/version.py +1 -0
- saltext_noderings-0.1.0.dist-info/METADATA +198 -0
- saltext_noderings-0.1.0.dist-info/RECORD +21 -0
- saltext_noderings-0.1.0.dist-info/WHEEL +6 -0
- saltext_noderings-0.1.0.dist-info/entry_points.txt +2 -0
- saltext_noderings-0.1.0.dist-info/licenses/LICENSE +201 -0
- saltext_noderings-0.1.0.dist-info/licenses/NOTICE +10 -0
- saltext_noderings-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Virtual machine helpers shared by the execution module, the state module and
|
|
3
|
+
the Salt Cloud driver.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from saltext.noderings.utils.client import NodeRingsError
|
|
9
|
+
from saltext.noderings.utils.client import TimeoutError_
|
|
10
|
+
from saltext.noderings.utils.client import Waiter
|
|
11
|
+
from saltext.noderings.utils.client import is_ambiguous
|
|
12
|
+
from saltext.noderings.utils.client import is_not_found
|
|
13
|
+
from saltext.noderings.utils.client import is_uuid
|
|
14
|
+
from saltext.noderings.utils.client import new_uuid
|
|
15
|
+
from saltext.noderings.utils.client import snake
|
|
16
|
+
from saltext.noderings.utils.client import trim_enum
|
|
17
|
+
from saltext.noderings.utils.marketplace import find_offers
|
|
18
|
+
from saltext.noderings.utils.marketplace import no_offer_message
|
|
19
|
+
from saltext.noderings.utils.marketplace import offer_view
|
|
20
|
+
|
|
21
|
+
NONCE_TAG_PREFIX = "salt-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 Salt returns it: 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}; create it with noderings.create_ssh_key or the "
|
|
137
|
+
f"noderings.ssh_key_present state"
|
|
138
|
+
)
|
|
139
|
+
out.append(match["id"])
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def resolve_ruleset(client, ruleset):
|
|
144
|
+
"""A firewall ruleset name or ID -> ID."""
|
|
145
|
+
if not ruleset:
|
|
146
|
+
return ""
|
|
147
|
+
for rs in client.list_firewall_rulesets():
|
|
148
|
+
if ruleset in (rs.get("id"), rs.get("name")):
|
|
149
|
+
return rs["id"]
|
|
150
|
+
raise NodeRingsUsageError(f"no firewall ruleset is named {ruleset}")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def wait_provisioned(client, vm_id, timeout=DEFAULT_WAIT_TIMEOUT, sleep=time.sleep):
|
|
154
|
+
def check():
|
|
155
|
+
vm = client.get_virtual_machine(vm_id)
|
|
156
|
+
status = vm.get("crStatus")
|
|
157
|
+
if status == "CR_STATUS_APPLIED":
|
|
158
|
+
return True, vm
|
|
159
|
+
if status == "CR_STATUS_FAILED":
|
|
160
|
+
raise RuntimeError(
|
|
161
|
+
f"provisioning of virtual machine {vm_id} failed. The API does not report why; "
|
|
162
|
+
"delete it and try another offer, or contact the provider"
|
|
163
|
+
)
|
|
164
|
+
return False, None
|
|
165
|
+
|
|
166
|
+
return Waiter(timeout, sleep=sleep).wait(f"virtual machine {vm_id} to be provisioned", check)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def wait_idle(client, vm_id, check_vm, what, timeout=DEFAULT_WAIT_TIMEOUT, sleep=time.sleep):
|
|
170
|
+
def check():
|
|
171
|
+
vm = client.get_virtual_machine(vm_id)
|
|
172
|
+
return (check_vm(vm) and vm.get("crStatus") != "CR_STATUS_PROCESSING"), vm
|
|
173
|
+
|
|
174
|
+
return Waiter(timeout, sleep=sleep).wait(what, check)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def wait_settled(client, vm_id, timeout=DEFAULT_WAIT_TIMEOUT, sleep=time.sleep):
|
|
178
|
+
"""Wait while the VM is in a transitional power state (created, reinstalling)."""
|
|
179
|
+
return wait_idle(
|
|
180
|
+
client,
|
|
181
|
+
vm_id,
|
|
182
|
+
lambda vm: power_state(vm) in ("running", "stopped"),
|
|
183
|
+
"the virtual machine to finish booting",
|
|
184
|
+
timeout,
|
|
185
|
+
sleep,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def set_power(client, vm_id, want, wait=True, timeout=DEFAULT_WAIT_TIMEOUT, sleep=time.sleep):
|
|
190
|
+
"""Start (``want="running"``), stop (``"stopped"``) or restart (``"restarted"``) a VM."""
|
|
191
|
+
action = {"running": "start", "stopped": "stop", "restarted": "restart"}[want]
|
|
192
|
+
Waiter(timeout, sleep=sleep).retry_busy(lambda: client.vm_action(vm_id, action))
|
|
193
|
+
if not wait:
|
|
194
|
+
return client.get_virtual_machine(vm_id)
|
|
195
|
+
target = "running" if want == "restarted" else want
|
|
196
|
+
return wait_idle(
|
|
197
|
+
client,
|
|
198
|
+
vm_id,
|
|
199
|
+
lambda vm: power_state(vm) == target,
|
|
200
|
+
f"the virtual machine to be {target}",
|
|
201
|
+
timeout,
|
|
202
|
+
sleep,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def attach_firewall(
|
|
207
|
+
client, vm_id, ruleset_id, wait=True, timeout=DEFAULT_WAIT_TIMEOUT, sleep=time.sleep
|
|
208
|
+
):
|
|
209
|
+
Waiter(timeout, sleep=sleep).retry_busy(
|
|
210
|
+
lambda: client.vm_action(vm_id, "attach-firewall", {"rulesetId": ruleset_id})
|
|
211
|
+
)
|
|
212
|
+
if wait:
|
|
213
|
+
return wait_idle(
|
|
214
|
+
client,
|
|
215
|
+
vm_id,
|
|
216
|
+
lambda vm: vm.get("firewallRulesetId") == ruleset_id,
|
|
217
|
+
"the firewall to be applied",
|
|
218
|
+
timeout,
|
|
219
|
+
sleep,
|
|
220
|
+
)
|
|
221
|
+
return client.get_virtual_machine(vm_id)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def detach_firewall(
|
|
225
|
+
client, vm_id, ruleset_id, wait=True, timeout=DEFAULT_WAIT_TIMEOUT, sleep=time.sleep
|
|
226
|
+
):
|
|
227
|
+
Waiter(timeout, sleep=sleep).retry_busy(
|
|
228
|
+
lambda: client.vm_action(vm_id, "detach-firewall", {"rulesetId": ruleset_id})
|
|
229
|
+
)
|
|
230
|
+
if wait:
|
|
231
|
+
return wait_idle(
|
|
232
|
+
client,
|
|
233
|
+
vm_id,
|
|
234
|
+
lambda vm: not vm.get("firewallRulesetId"),
|
|
235
|
+
"the firewall to be removed",
|
|
236
|
+
timeout,
|
|
237
|
+
sleep,
|
|
238
|
+
)
|
|
239
|
+
return client.get_virtual_machine(vm_id)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def reinstall(
|
|
243
|
+
client,
|
|
244
|
+
vm_id,
|
|
245
|
+
hostname,
|
|
246
|
+
distro,
|
|
247
|
+
ssh_key_ids=None,
|
|
248
|
+
password=None,
|
|
249
|
+
wait=True,
|
|
250
|
+
timeout=DEFAULT_WAIT_TIMEOUT,
|
|
251
|
+
sleep=time.sleep,
|
|
252
|
+
):
|
|
253
|
+
"""Reinstall the operating system. This erases the disk; the IP addresses stay."""
|
|
254
|
+
body = {"hostname": hostname or "", "distro": f"DISTRO_{distro.upper()}"}
|
|
255
|
+
if ssh_key_ids:
|
|
256
|
+
body["sshKeyIds"] = ssh_key_ids
|
|
257
|
+
if password:
|
|
258
|
+
body["password"] = password
|
|
259
|
+
Waiter(timeout, sleep=sleep).retry_busy(lambda: client.vm_action(vm_id, "reinstall", body))
|
|
260
|
+
if not wait:
|
|
261
|
+
return client.get_virtual_machine(vm_id)
|
|
262
|
+
|
|
263
|
+
def check():
|
|
264
|
+
vm = client.get_virtual_machine(vm_id)
|
|
265
|
+
status = vm.get("reinstallStatus")
|
|
266
|
+
if status == "REINSTALL_STATUS_FAILED":
|
|
267
|
+
raise RuntimeError(
|
|
268
|
+
f"the reinstall of virtual machine {vm_id} failed; the API does not report why"
|
|
269
|
+
)
|
|
270
|
+
return (
|
|
271
|
+
status == "REINSTALL_STATUS_COMPLETED" and vm.get("crStatus") != "CR_STATUS_PROCESSING",
|
|
272
|
+
vm,
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
# The status may still read COMPLETED from an earlier reinstall for a moment.
|
|
276
|
+
sleep(3)
|
|
277
|
+
Waiter(timeout, sleep=sleep).wait("the reinstall to finish", check)
|
|
278
|
+
return wait_settled(client, vm_id, timeout, sleep)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def order_vm(
|
|
282
|
+
client,
|
|
283
|
+
hostname,
|
|
284
|
+
plan_id,
|
|
285
|
+
region_id,
|
|
286
|
+
distro=None,
|
|
287
|
+
ssh_key_ids=None,
|
|
288
|
+
password=None,
|
|
289
|
+
tags=None,
|
|
290
|
+
ruleset_id=None,
|
|
291
|
+
wait=True,
|
|
292
|
+
timeout=DEFAULT_WAIT_TIMEOUT,
|
|
293
|
+
sleep=time.sleep,
|
|
294
|
+
):
|
|
295
|
+
"""
|
|
296
|
+
Order a VM and return it. Safe against lost responses: an ambiguous failure
|
|
297
|
+
is retried with the same idempotency key, and free plans (which ignore the
|
|
298
|
+
key) are tagged with a nonce so the VM is found instead of ordered twice.
|
|
299
|
+
"""
|
|
300
|
+
body = {"hostname": hostname, "planId": plan_id, "regionId": region_id}
|
|
301
|
+
body["idempotencyKey"] = new_uuid()
|
|
302
|
+
if distro:
|
|
303
|
+
body["distro"] = f"DISTRO_{distro.upper()}"
|
|
304
|
+
if ssh_key_ids:
|
|
305
|
+
body["sshKeyIds"] = ssh_key_ids
|
|
306
|
+
if password:
|
|
307
|
+
body["password"] = password
|
|
308
|
+
tags = sorted(set(tags or []))
|
|
309
|
+
|
|
310
|
+
nonce = ""
|
|
311
|
+
try:
|
|
312
|
+
free = client.get_marketplace_plan(plan_id).get("billingType") == "BILLING_TYPE_FREE"
|
|
313
|
+
except NodeRingsError:
|
|
314
|
+
free = True
|
|
315
|
+
if free:
|
|
316
|
+
nonce = NONCE_TAG_PREFIX + new_uuid()
|
|
317
|
+
tags = tags + [nonce]
|
|
318
|
+
if tags:
|
|
319
|
+
body["tags"] = tags
|
|
320
|
+
|
|
321
|
+
def find_by_nonce():
|
|
322
|
+
for vm in client.list_virtual_machines():
|
|
323
|
+
if nonce in (vm.get("tags") or []):
|
|
324
|
+
return vm
|
|
325
|
+
return None
|
|
326
|
+
|
|
327
|
+
vm, last_err, new_key = None, None, False
|
|
328
|
+
for attempt in range(6):
|
|
329
|
+
try:
|
|
330
|
+
vm = client.create_virtual_machine(body)
|
|
331
|
+
break
|
|
332
|
+
except NodeRingsError as exc:
|
|
333
|
+
last_err = exc
|
|
334
|
+
if exc.code == 9 and "new idempotency key" in exc.message.lower() and not new_key:
|
|
335
|
+
new_key = True
|
|
336
|
+
body["idempotencyKey"] = new_uuid()
|
|
337
|
+
continue
|
|
338
|
+
if not is_ambiguous(exc):
|
|
339
|
+
raise NodeRingsUsageError(
|
|
340
|
+
f"ordering virtual machine {hostname}: {translate_create_error(exc)}"
|
|
341
|
+
) from exc
|
|
342
|
+
except OSError as exc:
|
|
343
|
+
last_err = exc
|
|
344
|
+
if nonce:
|
|
345
|
+
found = find_by_nonce()
|
|
346
|
+
if found:
|
|
347
|
+
vm = found
|
|
348
|
+
break
|
|
349
|
+
sleep(min(2 * (attempt + 1), 10))
|
|
350
|
+
else:
|
|
351
|
+
raise NodeRingsUsageError(
|
|
352
|
+
f"ordering virtual machine {hostname}: {last_err}. The order may or may not have "
|
|
353
|
+
"been placed; check the console before trying again"
|
|
354
|
+
)
|
|
355
|
+
if (not vm or not vm.get("id")) and nonce:
|
|
356
|
+
vm = find_by_nonce()
|
|
357
|
+
if not vm or not vm.get("id"):
|
|
358
|
+
raise NodeRingsUsageError(
|
|
359
|
+
f"the API accepted the order for {hostname} but did not return the new virtual "
|
|
360
|
+
"machine; check the console before trying again"
|
|
361
|
+
)
|
|
362
|
+
vm_id = vm["id"]
|
|
363
|
+
if wait or ruleset_id or nonce:
|
|
364
|
+
wait_provisioned(client, vm_id, timeout, sleep)
|
|
365
|
+
# The VM reads CREATED until the platform has booted it, then STARTED.
|
|
366
|
+
wait_settled(client, vm_id, timeout, sleep)
|
|
367
|
+
if nonce:
|
|
368
|
+
try:
|
|
369
|
+
client.update_virtual_machine_tags(vm_id, remove=[nonce])
|
|
370
|
+
except NodeRingsError:
|
|
371
|
+
pass
|
|
372
|
+
if ruleset_id:
|
|
373
|
+
attach_firewall(client, vm_id, ruleset_id, wait, timeout, sleep)
|
|
374
|
+
return client.get_virtual_machine(vm_id)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
__all__ = [
|
|
378
|
+
"NodeRingsUsageError",
|
|
379
|
+
"TimeoutError_",
|
|
380
|
+
"attach_firewall",
|
|
381
|
+
"choose_offer",
|
|
382
|
+
"detach_firewall",
|
|
383
|
+
"find_vm",
|
|
384
|
+
"order_vm",
|
|
385
|
+
"power_state",
|
|
386
|
+
"reinstall",
|
|
387
|
+
"resolve_ruleset",
|
|
388
|
+
"resolve_ssh_keys",
|
|
389
|
+
"set_power",
|
|
390
|
+
"vm_view",
|
|
391
|
+
"wait_settled",
|
|
392
|
+
]
|
|
@@ -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()
|