| 1 |
# Copyright (c) 2021 Felix Fontein |
| 2 |
# Copyright (c) 2020 Markus Bergholz <[email protected]> |
| 3 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
|
| 6 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 7 |
# Do not use this from other collections or standalone plugins/modules! |
| 8 |
|
| 9 |
# https://dns.hetzner.com/api-docs |
| 10 |
|
| 11 |
from __future__ import annotations |
| 12 |
|
| 13 |
import json |
| 14 |
import time |
| 15 |
import typing as t |
| 16 |
from collections.abc import Mapping |
| 17 |
from urllib.parse import quote |
| 18 |
|
| 19 |
from ansible.module_utils.basic import env_fallback |
| 20 |
|
| 21 |
from ansible_collections.community.dns.plugins.module_utils._argspec import ArgumentSpec |
| 22 |
from ansible_collections.community.dns.plugins.module_utils._json_api_helper import ( |
| 23 |
ERROR_CODES, |
| 24 |
UNKNOWN_ERROR, |
| 25 |
JSONAPIHelper, |
| 26 |
) |
| 27 |
from ansible_collections.community.dns.plugins.module_utils._provider import ( |
| 28 |
ProviderInformation, |
| 29 |
) |
| 30 |
from ansible_collections.community.dns.plugins.module_utils._record import DNSRecord |
| 31 |
from ansible_collections.community.dns.plugins.module_utils._record_set import ( |
| 32 |
DNSRecordSet, |
| 33 |
) |
| 34 |
from ansible_collections.community.dns.plugins.module_utils._zone import DNSZone |
| 35 |
from ansible_collections.community.dns.plugins.module_utils._zone_record_api import ( |
| 36 |
NOT_PROVIDED, |
| 37 |
DNSAPIError, |
| 38 |
ZoneRecordAPI, |
| 39 |
filter_records, |
| 40 |
) |
| 41 |
from ansible_collections.community.dns.plugins.module_utils._zone_record_set_api import ( |
| 42 |
ZoneRecordSetAPI, |
| 43 |
filter_record_sets, |
| 44 |
) |
| 45 |
|
| 46 |
if t.TYPE_CHECKING: |
| 47 |
from collections.abc import Collection, Sequence # pragma: no cover |
| 48 |
|
| 49 |
from .._argspec import OptionProvider # pragma: no cover |
| 50 |
from .._http import HTTPHelper, HTTPMethod # pragma: no cover |
| 51 |
from .._provider import AnsibleType # pragma: no cover |
| 52 |
from .._record import IDNSRecord # pragma: no cover |
| 53 |
from .._record_set import IDNSRecordSet # pragma: no cover |
| 54 |
from .._zone_record_api import NotProvidedType # pragma: no cover |
| 55 |
|
| 56 |
|
| 57 |
def _create_zone_from_json(source: dict[str, t.Any]) -> DNSZone[str]: |
| 58 |
info = source.copy() |
| 59 |
zone = DNSZone(zone_id=info.pop("id"), name=info.pop("name")) |
| 60 |
if "legacy_ns" in info: |
| 61 |
info["legacy_ns"] = sorted(info["legacy_ns"]) |
| 62 |
zone.info = info |
| 63 |
return zone |
| 64 |
|
| 65 |
|
| 66 |
@t.overload |
| 67 |
def _create_record_from_json( |
| 68 |
source: t.Any, *, record_type: str | None = None, has_id: t.Literal[True] = True |
| 69 |
) -> DNSRecord[str]: ... |
| 70 |
|
| 71 |
|
| 72 |
@t.overload |
| 73 |
def _create_record_from_json( |
| 74 |
source: t.Any, *, record_type: str | None = None, has_id: t.Literal[False] |
| 75 |
) -> DNSRecord[str | None]: ... |
| 76 |
|
| 77 |
|
| 78 |
def _create_record_from_json( |
| 79 |
source: t.Any, *, record_type: str | None = None, has_id: bool = True |
| 80 |
) -> DNSRecord: |
| 81 |
if not isinstance(source, dict): |
| 82 |
raise DNSAPIError( |
| 83 |
f"Unexpected data {source!r} when expecting DNS record as JSON object" |
| 84 |
) |
| 85 |
source = dict(source) |
| 86 |
result = DNSRecord( |
| 87 |
record_id=source.pop("id") if has_id else None, |
| 88 |
record_type=source.pop("type", record_type), |
| 89 |
target=source.pop("value"), |
| 90 |
) |
| 91 |
result.ttl = source.pop("ttl", None) |
| 92 |
name = source.pop("name", None) |
| 93 |
if name == "@": |
| 94 |
name = None |
| 95 |
result.prefix = name |
| 96 |
source.pop("zone_id", None) |
| 97 |
result.extra.update(source) |
| 98 |
return result |
| 99 |
|
| 100 |
|
| 101 |
def _record_to_json(record: IDNSRecord[str | None], zone_id: str) -> dict[str, t.Any]: |
| 102 |
result: dict[str, t.Any] = { |
| 103 |
"name": record.prefix or "@", |
| 104 |
"value": record.target, |
| 105 |
"type": record.type, |
| 106 |
"zone_id": zone_id, |
| 107 |
} |
| 108 |
if record.ttl is not None: |
| 109 |
result["ttl"] = record.ttl |
| 110 |
return result |
| 111 |
|
| 112 |
|
| 113 |
def _pagination_query( |
| 114 |
query: dict[str, str] | Sequence[tuple[str, str]] | None, |
| 115 |
*, |
| 116 |
block_size: int, |
| 117 |
page: int, |
| 118 |
) -> dict[str, str] | Sequence[tuple[str, str]]: |
| 119 |
if isinstance(query, dict): |
| 120 |
query_map = query.copy() |
| 121 |
query_map["per_page"] = str(block_size) |
| 122 |
query_map["page"] = str(page) |
| 123 |
return query_map |
| 124 |
query_list = list(query) if query else [] |
| 125 |
query_list.append(("per_page", str(block_size))) |
| 126 |
query_list.append(("page", str(page))) |
| 127 |
return query_list |
| 128 |
|
| 129 |
|
| 130 |
class HetznerAPI(ZoneRecordAPI[str, str], JSONAPIHelper): |
| 131 |
def __init__( |
| 132 |
self, http_helper, token, api="https://dns.hetzner.com/api/", debug=False |
| 133 |
): |
| 134 |
JSONAPIHelper.__init__(self, http_helper, token, api=api, debug=debug) |
| 135 |
|
| 136 |
def _create_headers(self) -> dict[str, str]: |
| 137 |
return { |
| 138 |
"Accept": "application/json", |
| 139 |
"Auth-API-Token": self._token, |
| 140 |
} |
| 141 |
|
| 142 |
def _extract_only_error_message(self, result: t.Any) -> str: |
| 143 |
# These errors are not documented, but are what I experienced the API seems to return: |
| 144 |
if not isinstance(result, dict): |
| 145 |
return f"Unexpected content: {result!r}" |
| 146 |
res = "" |
| 147 |
if isinstance(result.get("error"), dict): |
| 148 |
if "message" in result["error"]: |
| 149 |
msg = result["error"]["message"] |
| 150 |
res = f'{res} with error message "{msg}"' |
| 151 |
if "code" in result["error"]: |
| 152 |
code = result["error"]["code"] |
| 153 |
res = f"{res} (error code {code})" |
| 154 |
if result.get("message"): |
| 155 |
msg = result["message"] |
| 156 |
res = f'{res} with message "{msg}"' |
| 157 |
return res |
| 158 |
|
| 159 |
def _extract_error_message(self, result: t.Any | None) -> str: |
| 160 |
if result is None: |
| 161 |
return "" |
| 162 |
if isinstance(result, dict): |
| 163 |
res = self._extract_only_error_message(result) |
| 164 |
if res: |
| 165 |
return res |
| 166 |
return f" with data: {result}" |
| 167 |
|
| 168 |
def _validate( |
| 169 |
self, |
| 170 |
*, |
| 171 |
result: t.Any | None = None, |
| 172 |
info: dict[str, str], |
| 173 |
expected: Collection[int] | None = None, |
| 174 |
method: HTTPMethod = "GET", |
| 175 |
) -> None: |
| 176 |
super()._validate(result=result, info=info, expected=expected, method=method) |
| 177 |
if isinstance(result, dict): |
| 178 |
error = result.get("error") |
| 179 |
if isinstance(error, dict): |
| 180 |
status = error.get("code") |
| 181 |
if status is None: |
| 182 |
return |
| 183 |
url = info.get("url") # not present when using open_url |
| 184 |
if expected is not None and status in expected: |
| 185 |
return |
| 186 |
error_code = ERROR_CODES.get(status, UNKNOWN_ERROR) |
| 187 |
more = self._extract_error_message(result) |
| 188 |
raise DNSAPIError( |
| 189 |
f"{method} {url} resulted in API error {status} ({error_code}){more}" |
| 190 |
) |
| 191 |
|
| 192 |
def _list_pagination( |
| 193 |
self, |
| 194 |
url: str, |
| 195 |
data_key: str, |
| 196 |
*, |
| 197 |
query: dict[str, str] | Sequence[tuple[str, str]] | None = None, |
| 198 |
block_size: int = 100, |
| 199 |
accept_404: bool = False, |
| 200 |
) -> list[t.Any] | None: |
| 201 |
result: list[t.Any] = [] |
| 202 |
page = 1 |
| 203 |
while True: |
| 204 |
query_ = _pagination_query(query, block_size=block_size, page=page) |
| 205 |
res, info = self._get( |
| 206 |
url, |
| 207 |
query=query_, |
| 208 |
must_have_content=[200], |
| 209 |
expected=[200, 404] if accept_404 and page == 1 else [200], |
| 210 |
require_json_object=True, |
| 211 |
) |
| 212 |
if accept_404 and page == 1 and info["status"] == 404: |
| 213 |
return None |
| 214 |
if not isinstance(res, Mapping): |
| 215 |
raise DNSAPIError( |
| 216 |
f"GET {url} with query parameters {query_} did not result in JSON object, but {type(res)}" |
| 217 |
) |
| 218 |
result.extend(res[data_key]) |
| 219 |
if not isinstance(res.get("meta"), dict) and page == 1: |
| 220 |
return result |
| 221 |
if page >= res["meta"]["pagination"]["last_page"]: |
| 222 |
return result |
| 223 |
page += 1 |
| 224 |
|
| 225 |
def get_zone_by_name(self, name: str) -> DNSZone[str] | None: |
| 226 |
""" |
| 227 |
Given a zone name, return the zone contents if found. |
| 228 |
|
| 229 |
@param name: The zone name (string) |
| 230 |
@return The zone information (DNSZone), or None if not found |
| 231 |
""" |
| 232 |
result, dummy = self._get("v1/zones", expected=[200, 404], query={"name": name}) |
| 233 |
if not isinstance(result, Mapping): |
| 234 |
raise DNSAPIError( |
| 235 |
f"Retrieving zone by name resulted in {type(result)} instead of object" |
| 236 |
) |
| 237 |
for zone in result["zones"]: |
| 238 |
if zone.get("name") == name: |
| 239 |
return _create_zone_from_json(zone) |
| 240 |
return None |
| 241 |
|
| 242 |
def get_zone_by_id(self, zone_id: str) -> DNSZone[str] | None: |
| 243 |
""" |
| 244 |
Given a zone ID, return the zone contents if found. |
| 245 |
|
| 246 |
@param zone_id: The zone ID |
| 247 |
@return The zone information (DNSZone), or None if not found |
| 248 |
""" |
| 249 |
result, info = self._get( |
| 250 |
f"v1/zones/{zone_id}", |
| 251 |
expected=[200, 404], |
| 252 |
must_have_content=[200], |
| 253 |
) |
| 254 |
if not isinstance(result, Mapping): |
| 255 |
raise DNSAPIError( |
| 256 |
f"Retrieving zone by name resulted in {type(result)} instead of object" |
| 257 |
) |
| 258 |
if info["status"] == 404: |
| 259 |
return None |
| 260 |
return _create_zone_from_json(result["zone"]) |
| 261 |
|
| 262 |
def get_zone_records( |
| 263 |
self, |
| 264 |
zone_id: str, |
| 265 |
prefix: str | None | NotProvidedType = NOT_PROVIDED, |
| 266 |
record_type: str | NotProvidedType = NOT_PROVIDED, |
| 267 |
) -> list[DNSRecord[str]] | None: |
| 268 |
""" |
| 269 |
Given a zone ID, return a list of records, optionally filtered by the provided criteria. |
| 270 |
|
| 271 |
@param zone_id: The zone ID |
| 272 |
@param prefix: The prefix to filter for, if provided. Since None is a valid value, |
| 273 |
the special constant NOT_PROVIDED indicates that we are not filtering. |
| 274 |
@param record_type: The record type to filter for, if provided |
| 275 |
@return A list of DNSrecord objects, or None if zone was not found |
| 276 |
""" |
| 277 |
result = self._list_pagination( |
| 278 |
"v1/records", |
| 279 |
data_key="records", |
| 280 |
query={"zone_id": zone_id}, |
| 281 |
accept_404=True, |
| 282 |
) |
| 283 |
if result is None: |
| 284 |
return None |
| 285 |
return filter_records( |
| 286 |
[_create_record_from_json(record) for record in result], |
| 287 |
prefix=prefix, |
| 288 |
record_type=record_type, |
| 289 |
) |
| 290 |
|
| 291 |
def add_record( |
| 292 |
self, zone_id: str, record: IDNSRecord[str | None] |
| 293 |
) -> DNSRecord[str]: |
| 294 |
""" |
| 295 |
Adds a new record to an existing zone. |
| 296 |
|
| 297 |
@param zone_id: The zone ID |
| 298 |
@param record: The DNS record (DNSRecord) |
| 299 |
@return The created DNS record (DNSRecord) |
| 300 |
""" |
| 301 |
data = _record_to_json(record, zone_id=zone_id) |
| 302 |
result, info = self._post( |
| 303 |
"v1/records", data=data, expected=[200, 422], require_json_object=True |
| 304 |
) |
| 305 |
if info["status"] == 422: |
| 306 |
raise DNSAPIError( |
| 307 |
f'The new {record.type} record with value "{record.target}" and TTL {record.ttl}' |
| 308 |
f" has not been accepted by the server{self._extract_only_error_message(result)}" |
| 309 |
) |
| 310 |
return _create_record_from_json(result["record"]) |
| 311 |
|
| 312 |
def update_record(self, zone_id: str, record: DNSRecord[str]) -> DNSRecord[str]: |
| 313 |
""" |
| 314 |
Update a record. |
| 315 |
|
| 316 |
@param zone_id: The zone ID |
| 317 |
@param record: The DNS record (DNSRecord) |
| 318 |
@return The DNS record (DNSRecord) |
| 319 |
""" |
| 320 |
if record.id is None: |
| 321 |
raise DNSAPIError("Need record ID to update record!") |
| 322 |
data = _record_to_json(record, zone_id=zone_id) |
| 323 |
result, info = self._put( |
| 324 |
f"v1/records/{record.id}", |
| 325 |
data=data, |
| 326 |
expected=[200, 422], |
| 327 |
require_json_object=True, |
| 328 |
) |
| 329 |
if info["status"] == 422: |
| 330 |
raise DNSAPIError( |
| 331 |
f'The updated {record.type} record with value "{record.target}" and TTL {record.ttl}' |
| 332 |
f" has not been accepted by the server{self._extract_only_error_message(result)}" |
| 333 |
) |
| 334 |
return _create_record_from_json(result["record"]) |
| 335 |
|
| 336 |
def delete_record(self, zone_id: str, record: DNSRecord[str]) -> bool: |
| 337 |
""" |
| 338 |
Delete a record. |
| 339 |
|
| 340 |
@param zone_id: The zone ID |
| 341 |
@param record: The DNS record (DNSRecord) |
| 342 |
@return True in case of success (boolean) |
| 343 |
""" |
| 344 |
if record.id is None: |
| 345 |
raise DNSAPIError("Need record ID to delete record!") |
| 346 |
dummy, info = self._delete( |
| 347 |
f"v1/records/{record.id}", |
| 348 |
must_have_content=False, |
| 349 |
expected=[200, 404], |
| 350 |
) |
| 351 |
return info["status"] == 200 |
| 352 |
|
| 353 |
@staticmethod |
| 354 |
def _append(results_per_zone_id, zone_id: str, result): |
| 355 |
if zone_id not in results_per_zone_id: |
| 356 |
results_per_zone_id[zone_id] = [] |
| 357 |
results_per_zone_id[zone_id].append(result) |
| 358 |
|
| 359 |
def add_records( |
| 360 |
self, |
| 361 |
records_per_zone_id: Mapping[str, Sequence[IDNSRecord[str | None]]], |
| 362 |
stop_early_on_errors: bool = True, |
| 363 |
) -> dict[ |
| 364 |
str, |
| 365 |
list[ |
| 366 |
tuple[DNSRecord[str], t.Literal[True], None] |
| 367 |
| tuple[IDNSRecord[str | None], t.Literal[False], DNSAPIError | None] |
| 368 |
], |
| 369 |
]: |
| 370 |
""" |
| 371 |
Add new records to an existing zone. |
| 372 |
|
| 373 |
@param records_per_zone_id: Maps a zone ID to a list of DNS records (DNSRecord) |
| 374 |
@param stop_early_on_errors: If set to ``True``, try to stop changes after the first error happens. |
| 375 |
This might only work on some APIs. |
| 376 |
@return A dictionary mapping zone IDs to lists of tuples ``(record, created, failed)``. |
| 377 |
Here ``created`` indicates whether the record was created (``True``) or not (``False``). |
| 378 |
If it was created, ``record`` contains the record ID and ``failed`` is ``None``. |
| 379 |
If it was not created, ``failed`` should be a ``DNSAPIError`` instance indicating why |
| 380 |
it was not created. It is possible that the API only creates records if all succeed, |
| 381 |
in that case ``failed`` can be ``None`` even though ``created`` is ``False``. |
| 382 |
""" |
| 383 |
json_records = [] |
| 384 |
for zone_id, records in records_per_zone_id.items(): |
| 385 |
for record in records: |
| 386 |
json_records.append(_record_to_json(record, zone_id=zone_id)) |
| 387 |
data = {"records": json_records} |
| 388 |
# Error 422 means that at least one of the records was not valid |
| 389 |
result, dummy = self._post( |
| 390 |
"v1/records/bulk", data=data, expected=[200, 422], require_json_object=True |
| 391 |
) |
| 392 |
results_per_zone_id: dict[ |
| 393 |
str, |
| 394 |
list[ |
| 395 |
tuple[DNSRecord[str], t.Literal[True], None] |
| 396 |
| tuple[IDNSRecord[str | None], t.Literal[False], DNSAPIError | None] |
| 397 |
], |
| 398 |
] = {} |
| 399 |
# This is the list of invalid records that was detected before accepting the whole set |
| 400 |
for json_record in result.get("invalid_records") or []: |
| 401 |
record = _create_record_from_json(json_record, has_id=False) |
| 402 |
zone_id = json_record["zone_id"] |
| 403 |
self._append( |
| 404 |
results_per_zone_id, |
| 405 |
zone_id, |
| 406 |
( |
| 407 |
record, |
| 408 |
False, |
| 409 |
DNSAPIError( |
| 410 |
f'Creating {record.type} record "{record.target}" with TTL {record.ttl} for zone {zone_id} failed with unknown reason' |
| 411 |
), |
| 412 |
), |
| 413 |
) |
| 414 |
# This is the list of valid records that were not processed |
| 415 |
for json_record in result.get("valid_records") or []: |
| 416 |
record = _create_record_from_json(json_record, has_id=False) |
| 417 |
zone_id = json_record["zone_id"] |
| 418 |
self._append(results_per_zone_id, zone_id, (record, False, None)) |
| 419 |
# This is the list of correctly processed records |
| 420 |
for json_record in result.get("records") or []: |
| 421 |
record = _create_record_from_json(json_record) |
| 422 |
zone_id = json_record["zone_id"] |
| 423 |
self._append(results_per_zone_id, zone_id, (record, True, None)) |
| 424 |
return results_per_zone_id |
| 425 |
|
| 426 |
def update_records( |
| 427 |
self, |
| 428 |
records_per_zone_id: Mapping[str, Sequence[DNSRecord[str]]], |
| 429 |
stop_early_on_errors: bool = True, |
| 430 |
) -> dict[str, list[tuple[DNSRecord[str], bool, DNSAPIError | None]]]: |
| 431 |
""" |
| 432 |
Update multiple records. |
| 433 |
|
| 434 |
@param records_per_zone_id: Maps a zone ID to a list of DNS records (DNSRecord) |
| 435 |
@param stop_early_on_errors: If set to ``True``, try to stop changes after the first error happens. |
| 436 |
This might only work on some APIs. |
| 437 |
@return A dictionary mapping zone IDs to lists of tuples ``(record, updated, failed)``. |
| 438 |
Here ``updated`` indicates whether the record was updated (``True``) or not (``False``). |
| 439 |
If it was not updated, ``failed`` should be a ``DNSAPIError`` instance. If it was |
| 440 |
updated, ``failed`` should be ``None``. It is possible that the API only updates |
| 441 |
records if all succeed, in that case ``failed`` can be ``None`` even though |
| 442 |
``updated`` is ``False``. |
| 443 |
""" |
| 444 |
# Currently Hetzner's bulk update API seems to be broken, it always returns the error message |
| 445 |
# "An invalid response was received from the upstream server". That's why for now, we always |
| 446 |
# fall back to the default implementation. |
| 447 |
if True: # pylint: disable=using-constant-test |
| 448 |
return super().update_records( |
| 449 |
records_per_zone_id, stop_early_on_errors=stop_early_on_errors |
| 450 |
) |
| 451 |
|
| 452 |
json_records = [] |
| 453 |
for zone_id, records in records_per_zone_id.items(): |
| 454 |
for record in records: |
| 455 |
json_records.append(_record_to_json(record, zone_id=zone_id)) |
| 456 |
data = {"records": json_records} |
| 457 |
result, dummy = self._put( |
| 458 |
"v1/records/bulk", data=data, expected=[200], require_json_object=True |
| 459 |
) |
| 460 |
results_per_zone_id = {} |
| 461 |
for json_record in result.get("failed_records") or []: |
| 462 |
record = _create_record_from_json(json_record) |
| 463 |
zone_id = json_record["zone_id"] |
| 464 |
self._append( |
| 465 |
results_per_zone_id, |
| 466 |
zone_id, |
| 467 |
( |
| 468 |
record, |
| 469 |
False, |
| 470 |
DNSAPIError( |
| 471 |
f'Updating {record.type} record #{record.id} "{record.target}" with TTL {record.ttl} for zone {zone_id} failed with unknown reason' |
| 472 |
), |
| 473 |
), |
| 474 |
) |
| 475 |
for json_record in result.get("records") or []: |
| 476 |
record = _create_record_from_json(json_record) |
| 477 |
zone_id = json_record["zone_id"] |
| 478 |
self._append(results_per_zone_id, zone_id, (record, True, None)) |
| 479 |
return results_per_zone_id |
| 480 |
|
| 481 |
|
| 482 |
def _create_zone_from_new_json(source: dict[str, t.Any]) -> DNSZone[str]: |
| 483 |
info = source.copy() |
| 484 |
# Converting ID to str so both APIs can use same interface |
| 485 |
zone = DNSZone(zone_id=str(info.pop("id")), name=info.pop("name")) |
| 486 |
zone.info = info |
| 487 |
return zone |
| 488 |
|
| 489 |
|
| 490 |
def _create_record_set_from_new_json( |
| 491 |
source: t.Any, *, record_type: str | None = None |
| 492 |
) -> DNSRecordSet[str, str]: |
| 493 |
source = dict(source) |
| 494 |
result: DNSRecordSet[str, str] = DNSRecordSet( |
| 495 |
record_set_id=source.pop("id"), record_type=source.pop("type") |
| 496 |
) |
| 497 |
result.ttl = source.pop("ttl", None) |
| 498 |
name = source.pop("name", None) |
| 499 |
if name == "@": |
| 500 |
name = None |
| 501 |
result.prefix = name |
| 502 |
records = source.pop("records") |
| 503 |
for record in records: |
| 504 |
rec = DNSRecord( |
| 505 |
record_id=result.id, record_type=result.type, target=record["value"] |
| 506 |
) |
| 507 |
rec.prefix = result.prefix |
| 508 |
rec.type = result.type |
| 509 |
rec.ttl = result.ttl |
| 510 |
if record["comment"]: |
| 511 |
rec.extra["comment"] = record["comment"] |
| 512 |
result.records.append(rec) |
| 513 |
source.pop("zone", None) |
| 514 |
result.extra.update(source) |
| 515 |
return result |
| 516 |
|
| 517 |
|
| 518 |
def _get_creation_json_data( |
| 519 |
record_set: IDNSRecordSet[str | None, str | None], |
| 520 |
) -> dict[str, t.Any]: |
| 521 |
return { |
| 522 |
"name": record_set.prefix or "@", |
| 523 |
"type": record_set.type, |
| 524 |
"ttl": record_set.ttl, |
| 525 |
"records": [ |
| 526 |
{ |
| 527 |
"value": record.target, |
| 528 |
"comment": record.extra.get("comment"), |
| 529 |
} |
| 530 |
for record in record_set.records |
| 531 |
], |
| 532 |
} |
| 533 |
|
| 534 |
|
| 535 |
def _get_update_json_data_ttl( |
| 536 |
record_set: IDNSRecordSet[str | None, str | None], |
| 537 |
) -> dict[str, t.Any]: |
| 538 |
return { |
| 539 |
"ttl": record_set.ttl, |
| 540 |
} |
| 541 |
|
| 542 |
|
| 543 |
def _get_update_json_data_value( |
| 544 |
record_set: IDNSRecordSet[str | None, str | None], |
| 545 |
) -> dict[str, t.Any]: |
| 546 |
return { |
| 547 |
"records": [ |
| 548 |
{ |
| 549 |
"value": record.target, |
| 550 |
"comment": record.extra.get("comment"), |
| 551 |
} |
| 552 |
for record in record_set.records |
| 553 |
], |
| 554 |
} |
| 555 |
|
| 556 |
|
| 557 |
def _q(value: t.Any) -> str: |
| 558 |
return quote(str(value), safe="@*") |
| 559 |
|
| 560 |
|
| 561 |
def _get_rrset_url(zone_id: str, prefix: str | None, record_type: str) -> str: |
| 562 |
return f"v1/zones/{_q(zone_id)}/rrsets/{_q(prefix or '@')}/{_q(record_type)}" |
| 563 |
|
| 564 |
|
| 565 |
def _format_action_error(action_with_error) -> str | None: |
| 566 |
error = action_with_error.get("error") |
| 567 |
if not error: |
| 568 |
return None |
| 569 |
return f"{error['message']} ({error['code']})" |
| 570 |
|
| 571 |
|
| 572 |
# Number of actions to query together at most |
| 573 |
_LIMIT_ACTION_QUERYING = 30 |
| 574 |
|
| 575 |
|
| 576 |
class _HetznerNewAPI(ZoneRecordSetAPI[str, str, str], JSONAPIHelper): |
| 577 |
def __init__( |
| 578 |
self, http_helper, token, api="https://api.hetzner.cloud/", debug=False |
| 579 |
): |
| 580 |
JSONAPIHelper.__init__(self, http_helper, token, api=api, debug=debug) |
| 581 |
|
| 582 |
def _create_headers(self) -> dict[str, str]: |
| 583 |
return { |
| 584 |
"Accept": "application/json", |
| 585 |
"Authorization": f"Bearer {self._token}", |
| 586 |
} |
| 587 |
|
| 588 |
def _create_post_headers(self) -> dict[str, str]: |
| 589 |
return { |
| 590 |
"Accept": "application/json", |
| 591 |
"Authorization": f"Bearer {self._token}", |
| 592 |
"Content-Type": "application/json", |
| 593 |
} |
| 594 |
|
| 595 |
def _extract_only_error_message(self, result: dict[str, t.Any]) -> str: |
| 596 |
res = "" |
| 597 |
if isinstance(result.get("error"), dict): |
| 598 |
msg = result["error"]["message"] |
| 599 |
code = result["error"]["code"] |
| 600 |
res = f'{res} with error message "{msg}" (error code {code})' |
| 601 |
if result["error"]["details"]: |
| 602 |
res = f"{res}. Details: {result['error']['details']}" |
| 603 |
return res |
| 604 |
|
| 605 |
def _extract_error_message(self, result: t.Any | None) -> str: |
| 606 |
if result is None: |
| 607 |
return "" |
| 608 |
if isinstance(result, dict): |
| 609 |
res = self._extract_only_error_message(result) |
| 610 |
if res: |
| 611 |
return res |
| 612 |
return f" with data: {result}" |
| 613 |
|
| 614 |
def _is_rate_limiting_result( |
| 615 |
self, content: bytes | None, info: dict[str, t.Any] |
| 616 |
) -> bool | int | float: |
| 617 |
if info["status"] != 429: |
| 618 |
return False |
| 619 |
if content is None: |
| 620 |
return False |
| 621 |
try: |
| 622 |
result = json.loads(content.decode("utf8")) |
| 623 |
except Exception: |
| 624 |
return False |
| 625 |
if not isinstance(result, dict): |
| 626 |
return False |
| 627 |
error = result.get("error") |
| 628 |
if not isinstance(error, dict): |
| 629 |
return False |
| 630 |
status = error.get("code") |
| 631 |
if status != "rate_limit_exceeded": |
| 632 |
return False |
| 633 |
# TODO: is there a hint how much time we should wait? |
| 634 |
# If yes, adjust check_done_delay accordingly! |
| 635 |
return 5 |
| 636 |
|
| 637 |
def _check_error( |
| 638 |
self, |
| 639 |
method: HTTPMethod, |
| 640 |
url: str, |
| 641 |
result: t.Any, |
| 642 |
accepted: Collection[str] | None = None, |
| 643 |
) -> str | None: |
| 644 |
if not isinstance(result, dict): |
| 645 |
return None |
| 646 |
error = result.get("error") |
| 647 |
if not isinstance(error, dict): |
| 648 |
return None |
| 649 |
status = error.get("code") |
| 650 |
if accepted is not None and status in accepted: |
| 651 |
return status |
| 652 |
more = self._extract_error_message(result) |
| 653 |
raise DNSAPIError(f"{method} {url} resulted in API error {status}{more}") |
| 654 |
|
| 655 |
@t.overload |
| 656 |
def _list_pagination( |
| 657 |
self, |
| 658 |
url: str, |
| 659 |
data_key: str, |
| 660 |
*, |
| 661 |
query: dict[str, str] | Sequence[tuple[str, str]] | None = None, |
| 662 |
block_size: int = 100, |
| 663 |
accept_404: t.Literal[False] = False, |
| 664 |
) -> list[t.Any]: ... |
| 665 |
|
| 666 |
@t.overload |
| 667 |
def _list_pagination( |
| 668 |
self, |
| 669 |
url: str, |
| 670 |
data_key: str, |
| 671 |
*, |
| 672 |
query: dict[str, str] | Sequence[tuple[str, str]] | None = None, |
| 673 |
block_size: int = 100, |
| 674 |
accept_404: t.Literal[True], |
| 675 |
) -> list[t.Any] | None: ... |
| 676 |
|
| 677 |
def _list_pagination( |
| 678 |
self, |
| 679 |
url: str, |
| 680 |
data_key: str, |
| 681 |
*, |
| 682 |
query: dict[str, str] | Sequence[tuple[str, str]] | None = None, |
| 683 |
block_size: int = 100, |
| 684 |
accept_404: bool = False, |
| 685 |
) -> list[t.Any] | None: |
| 686 |
result = [] |
| 687 |
page = 1 |
| 688 |
while True: |
| 689 |
query_ = _pagination_query(query, block_size=block_size, page=page) |
| 690 |
res, info = self._get( |
| 691 |
url, |
| 692 |
query=query_, |
| 693 |
must_have_content=[200], |
| 694 |
expected=[200, 404] if accept_404 and page == 1 else [200], |
| 695 |
require_json_object=True, |
| 696 |
) |
| 697 |
if accept_404 and page == 1 and info["status"] == 404: |
| 698 |
return None |
| 699 |
self._check_error( |
| 700 |
"GET", |
| 701 |
url, |
| 702 |
res, |
| 703 |
accepted=["not_found"] if accept_404 and page == 1 else [], |
| 704 |
) |
| 705 |
if not isinstance(res, Mapping): |
| 706 |
raise DNSAPIError( |
| 707 |
f"GET {url} with query parameters {query_} did not result in JSON object, but {type(res)}" |
| 708 |
) |
| 709 |
result.extend(res[data_key]) |
| 710 |
if not isinstance(res.get("meta"), dict) and page == 1: |
| 711 |
return result |
| 712 |
if page >= res["meta"]["pagination"]["last_page"]: |
| 713 |
return result |
| 714 |
page += 1 |
| 715 |
|
| 716 |
def get_zone_by_name(self, name: str) -> DNSZone[str] | None: |
| 717 |
""" |
| 718 |
Given a zone name, return the zone contents if found. |
| 719 |
|
| 720 |
@param name: The zone name (string) |
| 721 |
@return The zone information (DNSZone), or None if not found |
| 722 |
""" |
| 723 |
url = f"v1/zones/{_q(name)}" |
| 724 |
result, _info = self._get(url, expected=[200, 404], require_json_object=True) |
| 725 |
if self._check_error("GET", url, result, accepted=["not_found"]) == "not_found": |
| 726 |
return None |
| 727 |
return _create_zone_from_new_json(result["zone"]) |
| 728 |
|
| 729 |
def get_zone_by_id(self, zone_id: str) -> DNSZone[str] | None: |
| 730 |
""" |
| 731 |
Given a zone ID, return the zone contents if found. |
| 732 |
|
| 733 |
@param zone_id: The zone ID |
| 734 |
@return The zone information (DNSZone), or None if not found |
| 735 |
""" |
| 736 |
return self.get_zone_by_name(str(zone_id)) |
| 737 |
|
| 738 |
def _get_record_set( |
| 739 |
self, zone_id: str, prefix: str | None, record_type: str |
| 740 |
) -> DNSRecordSet[str, str] | None: |
| 741 |
url = _get_rrset_url(zone_id, prefix, record_type) |
| 742 |
result, _info = self._get(url, expected=[200, 404], require_json_object=True) |
| 743 |
if self._check_error("GET", url, result, accepted=["not_found"]) == "not_found": |
| 744 |
return None |
| 745 |
return _create_record_set_from_new_json(result["rrset"]) |
| 746 |
|
| 747 |
def get_zone_record_sets( |
| 748 |
self, |
| 749 |
zone_id: str, |
| 750 |
prefix: str | None | NotProvidedType = NOT_PROVIDED, |
| 751 |
record_type: str | NotProvidedType = NOT_PROVIDED, |
| 752 |
) -> list[DNSRecordSet[str, str]] | None: |
| 753 |
""" |
| 754 |
Given a zone ID, return a list of record sets, optionally filtered by the provided criteria. |
| 755 |
|
| 756 |
@param zone_id: The zone ID |
| 757 |
@param prefix: The prefix to filter for, if provided. Since None is a valid value, |
| 758 |
the special constant NOT_PROVIDED indicates that we are not filtering. |
| 759 |
@param record_type: The record type to filter for, if provided |
| 760 |
@return A list of DNSrecordSet objects, or None if zone was not found |
| 761 |
""" |
| 762 |
query: dict[str, str] = {} |
| 763 |
if prefix is not NOT_PROVIDED: |
| 764 |
query["name"] = prefix or "@" # type: ignore # This is a string |
| 765 |
if record_type is not NOT_PROVIDED: |
| 766 |
query["type"] = record_type # type: ignore # This is a string |
| 767 |
rrsets = self._list_pagination( |
| 768 |
f"v1/zones/{_q(zone_id)}/rrsets", |
| 769 |
"rrsets", |
| 770 |
query=query, |
| 771 |
accept_404=True, |
| 772 |
) |
| 773 |
if rrsets is None: |
| 774 |
return None |
| 775 |
return filter_record_sets( |
| 776 |
[_create_record_set_from_new_json(rrset) for rrset in rrsets], |
| 777 |
prefix=prefix, |
| 778 |
record_type=record_type, |
| 779 |
) |
| 780 |
|
| 781 |
def _wait_for_actions( |
| 782 |
self, |
| 783 |
actions: list[dict[str, t.Any]], |
| 784 |
what: str, |
| 785 |
*, |
| 786 |
fail_on_error: bool = True, |
| 787 |
stop_on_first_error: bool = False, |
| 788 |
) -> tuple[list[dict[str, t.Any]], list[dict[str, t.Any]]]: |
| 789 |
errors: list[dict[str, t.Any]] = [] |
| 790 |
other_actions: list[dict[str, t.Any]] = [] |
| 791 |
# Only do an initial wait if there have been at most _LIMIT_ACTION_QUERYING/2 calls. |
| 792 |
# (This is a heuristic to avoid unnecessary waits when we can already clear the list.) |
| 793 |
do_wait = 2 * len(actions) <= _LIMIT_ACTION_QUERYING |
| 794 |
while True: |
| 795 |
new_errors = [action for action in actions if action["status"] == "error"] |
| 796 |
if new_errors: |
| 797 |
errors.extend(new_errors) |
| 798 |
if stop_on_first_error: |
| 799 |
break |
| 800 |
other_actions.extend( |
| 801 |
action for action in actions if action["status"] != "running" |
| 802 |
) |
| 803 |
actions = [action for action in actions if action["status"] == "running"] |
| 804 |
if not actions: |
| 805 |
break |
| 806 |
if do_wait: |
| 807 |
time.sleep(1) |
| 808 |
do_wait = True |
| 809 |
action_ids = [str(action["id"]) for action in actions] |
| 810 |
if len(action_ids) == 1: |
| 811 |
url = f"v1/actions/{_q(action_ids[0])}" |
| 812 |
result, dummy = self._get(url, expected=[200], require_json_object=True) |
| 813 |
self._check_error("GET", url, result) |
| 814 |
actions = [result["action"]] |
| 815 |
else: |
| 816 |
remaining_actions = [] |
| 817 |
if len(action_ids) > _LIMIT_ACTION_QUERYING: |
| 818 |
action_ids = action_ids[:_LIMIT_ACTION_QUERYING] |
| 819 |
remaining_actions = actions[_LIMIT_ACTION_QUERYING:] |
| 820 |
url = "v1/actions" |
| 821 |
result, dummy = self._get( |
| 822 |
url, |
| 823 |
query=[("id", action_id) for action_id in sorted(action_ids)], |
| 824 |
expected=[200], |
| 825 |
require_json_object=True, |
| 826 |
) |
| 827 |
self._check_error("GET", url, result) |
| 828 |
actions = result["actions"] |
| 829 |
if all(action["status"] != "running" for action in actions): |
| 830 |
# If all actions queried by this request have stopped, don't wait before querying more |
| 831 |
do_wait = False |
| 832 |
actions.extend(remaining_actions) |
| 833 |
if errors and fail_on_error: |
| 834 |
error_messages = [_format_action_error(error) for error in errors] |
| 835 |
joined_msgs = ", ".join(msg for msg in error_messages if msg) or "unknown" |
| 836 |
raise DNSAPIError(f"Error while {what}: {joined_msgs}") |
| 837 |
return errors, other_actions + actions |
| 838 |
|
| 839 |
def add_record_set( |
| 840 |
self, |
| 841 |
zone_id: str, |
| 842 |
record_set: IDNSRecordSet[str | None, str | None], |
| 843 |
) -> DNSRecordSet[str, str]: |
| 844 |
""" |
| 845 |
Adds a new record set to an existing zone. |
| 846 |
|
| 847 |
@param zone_id: The zone ID |
| 848 |
@param record: The DNS record set (DNSRecordSet) |
| 849 |
@return The created DNS record set (DNSRecordSet) |
| 850 |
""" |
| 851 |
data = _get_creation_json_data(record_set) |
| 852 |
url = f"v1/zones/{_q(zone_id)}/rrsets" |
| 853 |
result, dummy = self._post( |
| 854 |
url, data=data, expected=[201], require_json_object=True |
| 855 |
) |
| 856 |
self._check_error("POST", url, result) |
| 857 |
self._wait_for_actions([result["action"]], "adding record set") |
| 858 |
return _create_record_set_from_new_json(result["rrset"]) |
| 859 |
|
| 860 |
def update_record_set( |
| 861 |
self, |
| 862 |
zone_id: str, |
| 863 |
record_set: DNSRecordSet[str, str], |
| 864 |
updated_records: bool = True, |
| 865 |
updated_ttl: bool = True, |
| 866 |
) -> DNSRecordSet[str, str]: |
| 867 |
""" |
| 868 |
Update a record set. |
| 869 |
|
| 870 |
@param zone_id: The zone ID |
| 871 |
@param record_set: The DNS record set (DNSRecordSet) |
| 872 |
@param updated_records: Hint whether the values were updated. |
| 873 |
@param updated_ttl: Hint whether the values were updated. |
| 874 |
@return The DNS record set (DNSRecordSet) |
| 875 |
""" |
| 876 |
actions = [] |
| 877 |
base_url = _get_rrset_url(zone_id, record_set.prefix, record_set.type) |
| 878 |
if updated_ttl: |
| 879 |
data = _get_update_json_data_ttl(record_set) |
| 880 |
url = f"{base_url}/actions/change_ttl" |
| 881 |
ttl_result, dummy = self._post( |
| 882 |
url, data=data, expected=[201], require_json_object=True |
| 883 |
) |
| 884 |
self._check_error("POST", url, ttl_result) |
| 885 |
actions.append(ttl_result["action"]) |
| 886 |
if updated_records: |
| 887 |
data = _get_update_json_data_value(record_set) |
| 888 |
url = f"{base_url}/actions/set_records" |
| 889 |
set_result, dummy = self._post( |
| 890 |
url, data=data, expected=[201], require_json_object=True |
| 891 |
) |
| 892 |
self._check_error("POST", url, set_result) |
| 893 |
actions.append(set_result["action"]) |
| 894 |
self._wait_for_actions(actions, "changing record set") |
| 895 |
result = self._get_record_set(zone_id, record_set.prefix, record_set.type) |
| 896 |
# If the record set suddenly vanished, return the one we *wanted* to have |
| 897 |
return result if result else record_set |
| 898 |
|
| 899 |
def delete_record_set( |
| 900 |
self, zone_id: str, record_set: DNSRecordSet[str, str] |
| 901 |
) -> bool: |
| 902 |
""" |
| 903 |
Delete a record set. |
| 904 |
|
| 905 |
@param zone_id: The zone ID |
| 906 |
@param record_set: The DNS record set (DNSRecordSet) |
| 907 |
@return True in case of success (boolean) |
| 908 |
""" |
| 909 |
url = _get_rrset_url(zone_id, record_set.prefix, record_set.type) |
| 910 |
result, _info = self._delete(url, expected=[201, 404], require_json_object=True) |
| 911 |
if ( |
| 912 |
self._check_error("DELETE", url, result, accepted=["not_found"]) |
| 913 |
== "not_found" |
| 914 |
): |
| 915 |
return False |
| 916 |
self._wait_for_actions([result["action"]], "deleting record set") |
| 917 |
return True |
| 918 |
|
| 919 |
def _fetch_all_records( |
| 920 |
self, zone_id: str, prefixes_and_types: Sequence[tuple[str | None, str]] |
| 921 |
) -> list[DNSRecordSet[str, str]]: |
| 922 |
if not prefixes_and_types: |
| 923 |
return [] |
| 924 |
common_prefix: str | None | NotProvidedType |
| 925 |
common_type: str | NotProvidedType |
| 926 |
common_prefix, common_type = prefixes_and_types[0] |
| 927 |
if len(prefixes_and_types) == 1: |
| 928 |
res = self._get_record_set(zone_id, common_prefix, common_type) |
| 929 |
return [res] if res else [] |
| 930 |
if any(common_prefix != prefix for prefix, _r_type in prefixes_and_types): |
| 931 |
common_prefix = NOT_PROVIDED |
| 932 |
if any(common_type != r_type for _prefix, r_type in prefixes_and_types): |
| 933 |
common_type = NOT_PROVIDED |
| 934 |
return ( |
| 935 |
self.get_zone_record_sets( |
| 936 |
zone_id, prefix=common_prefix, record_type=common_type |
| 937 |
) |
| 938 |
or [] |
| 939 |
) |
| 940 |
|
| 941 |
@t.overload |
| 942 |
def _collect_results( |
| 943 |
self, |
| 944 |
what: str, |
| 945 |
data_per_zone_id: dict[ |
| 946 |
str, |
| 947 |
list[ |
| 948 |
tuple[DNSRecordSet[str, str], list[str], None] |
| 949 |
| tuple[ |
| 950 |
IDNSRecordSet[str | None, str | None], |
| 951 |
None, |
| 952 |
DNSAPIError, |
| 953 |
] |
| 954 |
], |
| 955 |
], |
| 956 |
actions: dict[t.Any, dict[str, t.Any]], |
| 957 |
*, |
| 958 |
do_wait: bool, |
| 959 |
stop_early_on_errors: bool, |
| 960 |
refresh_rrsets: bool = True, |
| 961 |
has_incomplete: t.Literal[True], |
| 962 |
) -> dict[ |
| 963 |
str, |
| 964 |
list[ |
| 965 |
tuple[DNSRecordSet[str, str], t.Literal[True], None] |
| 966 |
| tuple[ |
| 967 |
IDNSRecordSet[str | None, str | None], |
| 968 |
t.Literal[False], |
| 969 |
DNSAPIError | None, |
| 970 |
] |
| 971 |
], |
| 972 |
]: ... |
| 973 |
|
| 974 |
@t.overload |
| 975 |
def _collect_results( |
| 976 |
self, |
| 977 |
what: str, |
| 978 |
data_per_zone_id: dict[ |
| 979 |
str, |
| 980 |
list[tuple[DNSRecordSet[str, str], list[str] | None, DNSAPIError | None]], |
| 981 |
], |
| 982 |
actions: dict[t.Any, dict[str, t.Any]], |
| 983 |
*, |
| 984 |
do_wait: bool, |
| 985 |
stop_early_on_errors: bool, |
| 986 |
refresh_rrsets: bool = True, |
| 987 |
has_incomplete: t.Literal[False], |
| 988 |
) -> dict[ |
| 989 |
str, |
| 990 |
list[tuple[DNSRecordSet[str, str], bool, DNSAPIError | None]], |
| 991 |
]: ... |
| 992 |
|
| 993 |
def _collect_results( |
| 994 |
self, |
| 995 |
what: str, |
| 996 |
data_per_zone_id: Mapping[ |
| 997 |
str, |
| 998 |
Sequence[ |
| 999 |
tuple[ |
| 1000 |
DNSRecordSet[str, str] | IDNSRecordSet[str | None, str | None], |
| 1001 |
list[str] | None, |
| 1002 |
DNSAPIError | None, |
| 1003 |
] |
| 1004 |
], |
| 1005 |
], |
| 1006 |
actions: dict[t.Any, dict[str, t.Any]], |
| 1007 |
*, |
| 1008 |
do_wait: bool, |
| 1009 |
stop_early_on_errors: bool, |
| 1010 |
refresh_rrsets: bool = True, |
| 1011 |
has_incomplete: bool, |
| 1012 |
) -> dict[str, list[t.Any]]: |
| 1013 |
errors = {} |
| 1014 |
if do_wait: |
| 1015 |
action_errors, _other_actions = self._wait_for_actions( |
| 1016 |
list(actions.values()), |
| 1017 |
what, |
| 1018 |
fail_on_error=False, |
| 1019 |
stop_on_first_error=stop_early_on_errors, |
| 1020 |
) |
| 1021 |
for action_error in action_errors: |
| 1022 |
errors[action_error["id"]] = DNSAPIError( |
| 1023 |
_format_action_error(action_error) |
| 1024 |
) |
| 1025 |
results_per_zone_id = {} |
| 1026 |
for zone_id, datas in data_per_zone_id.items(): |
| 1027 |
result: list[ |
| 1028 |
tuple[ |
| 1029 |
DNSRecordSet[str, str] | IDNSRecordSet[str | None, str | None], |
| 1030 |
bool, |
| 1031 |
DNSAPIError | None, |
| 1032 |
] |
| 1033 |
] = [] |
| 1034 |
results_per_zone_id[zone_id] = result |
| 1035 |
refresh = {} |
| 1036 |
for record_set, action_ids, error in datas: |
| 1037 |
if error is not None: |
| 1038 |
result.append((record_set, False, error)) |
| 1039 |
error = None |
| 1040 |
rr_errors = [ |
| 1041 |
errors[action_id] |
| 1042 |
for action_id in action_ids or [] |
| 1043 |
if action_id in errors |
| 1044 |
] |
| 1045 |
if rr_errors: |
| 1046 |
# If there are multiple ones, only use the first |
| 1047 |
result.append((record_set, False, rr_errors[0])) |
| 1048 |
else: |
| 1049 |
# Need to refresh this record set |
| 1050 |
refresh[(record_set.prefix, record_set.type)] = len(result) |
| 1051 |
result.append((record_set, True, None)) |
| 1052 |
if refresh_rrsets: |
| 1053 |
for record_set in self._fetch_all_records( |
| 1054 |
zone_id, list(refresh.keys()) |
| 1055 |
): |
| 1056 |
index = refresh.get((record_set.prefix, record_set.type)) |
| 1057 |
if index is not None: |
| 1058 |
result[index] = (record_set, True, None) |
| 1059 |
return results_per_zone_id |
| 1060 |
|
| 1061 |
def add_record_sets( |
| 1062 |
self, |
| 1063 |
record_sets_per_zone_id: Mapping[ |
| 1064 |
str, Sequence[IDNSRecordSet[str | None, str | None]] |
| 1065 |
], |
| 1066 |
stop_early_on_errors: bool = True, |
| 1067 |
) -> dict[ |
| 1068 |
str, |
| 1069 |
list[ |
| 1070 |
tuple[DNSRecordSet[str, str], t.Literal[True], None] |
| 1071 |
| tuple[ |
| 1072 |
IDNSRecordSet[str | None, str | None], |
| 1073 |
t.Literal[False], |
| 1074 |
DNSAPIError | None, |
| 1075 |
] |
| 1076 |
], |
| 1077 |
]: |
| 1078 |
""" |
| 1079 |
Add new record sets to an existing zone. |
| 1080 |
|
| 1081 |
@param record_sets_per_zone_id: Maps a zone ID to a list of DNS record sets (DNSRecordSet) |
| 1082 |
@param stop_early_on_errors: If set to ``True``, try to stop changes after the first error happens. |
| 1083 |
This might only work on some APIs. |
| 1084 |
@return A dictionary mapping zone IDs to lists of tuples ``(record_set, created, failed)``. |
| 1085 |
Here ``created`` indicates whether the record set was created (``True``) or not (``False``). |
| 1086 |
If it was created, ``record_set`` contains the record set ID and ``failed`` is ``None``. |
| 1087 |
If it was not created, ``failed`` should be a ``DNSAPIError`` instance indicating why |
| 1088 |
it was not created. It is possible that the API only creates record sets if all succeed, |
| 1089 |
in that case ``failed`` can be ``None`` even though ``created`` is ``False``. |
| 1090 |
""" |
| 1091 |
actions = {} |
| 1092 |
data_per_zone_id = {} |
| 1093 |
stop = False |
| 1094 |
for zone_id, record_sets in record_sets_per_zone_id.items(): |
| 1095 |
data: list[ |
| 1096 |
tuple[DNSRecordSet[str, str], list[str], None] |
| 1097 |
| tuple[ |
| 1098 |
IDNSRecordSet[str | None, str | None], |
| 1099 |
None, |
| 1100 |
DNSAPIError, |
| 1101 |
] |
| 1102 |
] = [] |
| 1103 |
data_per_zone_id[zone_id] = data |
| 1104 |
for record_set in record_sets: |
| 1105 |
creation_data = _get_creation_json_data(record_set) |
| 1106 |
try: |
| 1107 |
url = f"v1/zones/{_q(zone_id)}/rrsets" |
| 1108 |
res, dummy = self._post( |
| 1109 |
url, |
| 1110 |
data=creation_data, |
| 1111 |
expected=[201], |
| 1112 |
require_json_object=True, |
| 1113 |
) |
| 1114 |
self._check_error("POST", url, res) |
| 1115 |
action = res["action"] |
| 1116 |
actions[action["id"]] = action |
| 1117 |
data.append( |
| 1118 |
( |
| 1119 |
_create_record_set_from_new_json(res["rrset"]), |
| 1120 |
[action["id"]], |
| 1121 |
None, |
| 1122 |
) |
| 1123 |
) |
| 1124 |
except DNSAPIError as e: |
| 1125 |
data.append((record_set, None, e)) |
| 1126 |
if stop_early_on_errors: |
| 1127 |
stop = True |
| 1128 |
break |
| 1129 |
if stop: |
| 1130 |
break |
| 1131 |
return self._collect_results( |
| 1132 |
"adding record sets", |
| 1133 |
data_per_zone_id, |
| 1134 |
actions, |
| 1135 |
do_wait=not stop, |
| 1136 |
stop_early_on_errors=stop_early_on_errors, |
| 1137 |
refresh_rrsets=False, |
| 1138 |
has_incomplete=True, |
| 1139 |
) |
| 1140 |
|
| 1141 |
def update_record_sets( |
| 1142 |
self, |
| 1143 |
record_sets_per_zone_id: Mapping[ |
| 1144 |
str, Sequence[tuple[DNSRecordSet[str, str], bool, bool]] |
| 1145 |
], |
| 1146 |
stop_early_on_errors: bool = True, |
| 1147 |
) -> dict[ |
| 1148 |
str, |
| 1149 |
list[tuple[DNSRecordSet[str, str], bool, DNSAPIError | None]], |
| 1150 |
]: |
| 1151 |
""" |
| 1152 |
Update multiple record sets. |
| 1153 |
|
| 1154 |
@param record_sets_per_zone_id: Maps a zone ID to a list of tuples |
| 1155 |
(record_set, updated_records, updated_ttl) |
| 1156 |
of type (DNSRecordSet, bool, bool). |
| 1157 |
@param stop_early_on_errors: If set to ``True``, try to stop changes after the first error happens. |
| 1158 |
This might only work on some APIs. |
| 1159 |
@return A dictionary mapping zone IDs to lists of tuples ``(record_set, updated, failed)``. |
| 1160 |
Here ``updated`` indicates whether the record set was updated (``True``) or not (``False``). |
| 1161 |
If it was not updated, ``failed`` should be a ``DNSAPIError`` instance. If it was |
| 1162 |
updated, ``failed`` should be ``None``. It is possible that the API only updates |
| 1163 |
record sets if all succeed, in that case ``failed`` can be ``None`` even though |
| 1164 |
``updated`` is ``False``. |
| 1165 |
""" |
| 1166 |
actions = {} |
| 1167 |
data_per_zone_id = {} |
| 1168 |
stop = False |
| 1169 |
for zone_id, record_sets in record_sets_per_zone_id.items(): |
| 1170 |
data: list[ |
| 1171 |
tuple[DNSRecordSet[str, str], list[str] | None, DNSAPIError | None] |
| 1172 |
] = [] |
| 1173 |
data_per_zone_id[zone_id] = data |
| 1174 |
for record_set, updated_records, updated_ttl in record_sets: |
| 1175 |
base_url = _get_rrset_url(zone_id, record_set.prefix, record_set.type) |
| 1176 |
try: |
| 1177 |
action_ids = [] |
| 1178 |
if updated_ttl: |
| 1179 |
ttl_data = _get_update_json_data_ttl(record_set) |
| 1180 |
ttl_url = f"{base_url}/actions/change_ttl" |
| 1181 |
ttl_result, dummy = self._post( |
| 1182 |
ttl_url, |
| 1183 |
data=ttl_data, |
| 1184 |
expected=[201], |
| 1185 |
require_json_object=True, |
| 1186 |
) |
| 1187 |
self._check_error("POST", ttl_url, ttl_result) |
| 1188 |
action = ttl_result["action"] |
| 1189 |
action_id = action["id"] |
| 1190 |
actions[action_id] = action |
| 1191 |
action_ids.append(action_id) |
| 1192 |
if updated_records: |
| 1193 |
set_data = _get_update_json_data_value(record_set) |
| 1194 |
set_url = f"{base_url}/actions/set_records" |
| 1195 |
set_result, dummy = self._post( |
| 1196 |
set_url, |
| 1197 |
data=set_data, |
| 1198 |
expected=[201], |
| 1199 |
require_json_object=True, |
| 1200 |
) |
| 1201 |
self._check_error("POST", set_url, set_result) |
| 1202 |
action = set_result["action"] |
| 1203 |
action_id = action["id"] |
| 1204 |
actions[action_id] = action |
| 1205 |
action_ids.append(action_id) |
| 1206 |
data.append((record_set, action_ids, None)) |
| 1207 |
except DNSAPIError as e: |
| 1208 |
data.append((record_set, None, e)) |
| 1209 |
if stop_early_on_errors: |
| 1210 |
stop = True |
| 1211 |
break |
| 1212 |
if stop: |
| 1213 |
break |
| 1214 |
return self._collect_results( |
| 1215 |
"updating record sets", |
| 1216 |
data_per_zone_id, |
| 1217 |
actions, |
| 1218 |
do_wait=not stop, |
| 1219 |
stop_early_on_errors=stop_early_on_errors, |
| 1220 |
refresh_rrsets=not stop, |
| 1221 |
has_incomplete=False, |
| 1222 |
) |
| 1223 |
|
| 1224 |
def delete_record_sets( |
| 1225 |
self, |
| 1226 |
record_sets_per_zone_id: Mapping[str, Sequence[DNSRecordSet[str, str]]], |
| 1227 |
stop_early_on_errors: bool = True, |
| 1228 |
) -> dict[ |
| 1229 |
str, |
| 1230 |
list[tuple[DNSRecordSet[str, str], bool, DNSAPIError | None]], |
| 1231 |
]: |
| 1232 |
""" |
| 1233 |
Delete multiple record_sets. |
| 1234 |
|
| 1235 |
@param record_sets_per_zone_id: Maps a zone ID to a list of DNS record sets (DNSRecordSet) |
| 1236 |
@param stop_early_on_errors: If set to ``True``, try to stop changes after the first error happens. |
| 1237 |
This might only work on some APIs. |
| 1238 |
@return A dictionary mapping zone IDs to lists of tuples ``(record_set, deleted, failed)``. |
| 1239 |
In case ``record_set`` was deleted or not deleted, ``deleted`` is ``True`` |
| 1240 |
respectively ``False``, and ``failed`` is ``None``. In case an error happened |
| 1241 |
while deleting, ``deleted`` is ``False`` and ``failed`` is a ``DNSAPIError`` |
| 1242 |
instance hopefully providing information on the error. |
| 1243 |
""" |
| 1244 |
actions = {} |
| 1245 |
data_per_zone_id = {} |
| 1246 |
stop = False |
| 1247 |
for zone_id, record_sets in record_sets_per_zone_id.items(): |
| 1248 |
data: list[ |
| 1249 |
tuple[DNSRecordSet[str, str], list[str] | None, DNSAPIError | None] |
| 1250 |
] = [] |
| 1251 |
data_per_zone_id[zone_id] = data |
| 1252 |
for record_set in record_sets: |
| 1253 |
try: |
| 1254 |
url = _get_rrset_url(zone_id, record_set.prefix, record_set.type) |
| 1255 |
result, _info = self._delete( |
| 1256 |
url, expected=[201, 404], require_json_object=True |
| 1257 |
) |
| 1258 |
if ( |
| 1259 |
self._check_error("DELETE", url, result, accepted=["not_found"]) |
| 1260 |
== "not_found" |
| 1261 |
): |
| 1262 |
data.append((record_set, None, None)) |
| 1263 |
else: |
| 1264 |
action = result["action"] |
| 1265 |
actions[action["id"]] = action |
| 1266 |
data.append((record_set, [action["id"]], None)) |
| 1267 |
except DNSAPIError as e: |
| 1268 |
data.append((record_set, None, e)) |
| 1269 |
if stop_early_on_errors: |
| 1270 |
stop = True |
| 1271 |
break |
| 1272 |
if stop: |
| 1273 |
break |
| 1274 |
return self._collect_results( |
| 1275 |
"deleting record sets", |
| 1276 |
data_per_zone_id, |
| 1277 |
actions, |
| 1278 |
do_wait=not stop, |
| 1279 |
stop_early_on_errors=stop_early_on_errors, |
| 1280 |
refresh_rrsets=False, |
| 1281 |
has_incomplete=False, |
| 1282 |
) |
| 1283 |
|
| 1284 |
|
| 1285 |
class HetznerProviderInformation(ProviderInformation): |
| 1286 |
def __init__(self, option_provider: OptionProvider | None = None) -> None: |
| 1287 |
self._api = None |
| 1288 |
if option_provider is not None: |
| 1289 |
hetzner_token = option_provider.get_option("hetzner_token") |
| 1290 |
hetzner_api_token = option_provider.get_option("hetzner_api_token") |
| 1291 |
if hetzner_token is not None: |
| 1292 |
self._api = "old" |
| 1293 |
if hetzner_api_token is not None: |
| 1294 |
self._api = "new" |
| 1295 |
|
| 1296 |
def get_supported_record_types(self) -> list[str]: |
| 1297 |
""" |
| 1298 |
Return a list of supported record types. |
| 1299 |
""" |
| 1300 |
old_api = [ |
| 1301 |
"A", |
| 1302 |
"AAAA", |
| 1303 |
"NS", |
| 1304 |
"MX", |
| 1305 |
"CNAME", |
| 1306 |
"RP", |
| 1307 |
"TXT", |
| 1308 |
"SOA", |
| 1309 |
"HINFO", |
| 1310 |
"SRV", |
| 1311 |
"TLSA", |
| 1312 |
"DS", |
| 1313 |
"CAA", |
| 1314 |
"DANE", |
| 1315 |
] |
| 1316 |
new_api = [ |
| 1317 |
"A", |
| 1318 |
"AAAA", |
| 1319 |
"NS", |
| 1320 |
"MX", |
| 1321 |
"CNAME", |
| 1322 |
"RP", |
| 1323 |
"TXT", |
| 1324 |
"SOA", |
| 1325 |
"HINFO", |
| 1326 |
"SRV", |
| 1327 |
"TLSA", |
| 1328 |
"DS", |
| 1329 |
"CAA", |
| 1330 |
"HTTPS", |
| 1331 |
"PTR", |
| 1332 |
"SVCB", |
| 1333 |
] |
| 1334 |
if self._api == "old": |
| 1335 |
return old_api |
| 1336 |
if self._api == "new": |
| 1337 |
return new_api |
| 1338 |
return sorted(set(old_api) | set(new_api)) |
| 1339 |
|
| 1340 |
def get_zone_id_type(self) -> AnsibleType: |
| 1341 |
""" |
| 1342 |
Return the (short) type for zone IDs, like ``'int'`` or ``'str'``. |
| 1343 |
""" |
| 1344 |
# For the new API, this would be 'int'. |
| 1345 |
# Since we have to support both APIs, we're using 'str'. |
| 1346 |
return "str" |
| 1347 |
|
| 1348 |
def get_record_id_type(self) -> AnsibleType: |
| 1349 |
""" |
| 1350 |
Return the (short) type for record IDs, like ``'int'`` or ``'str'``. |
| 1351 |
""" |
| 1352 |
return "str" |
| 1353 |
|
| 1354 |
def get_record_default_ttl(self) -> int | None: |
| 1355 |
""" |
| 1356 |
Return the default TTL for records, like 300, 3600 or None. |
| 1357 |
None means that some other TTL (usually from the zone) will be used. |
| 1358 |
""" |
| 1359 |
return None |
| 1360 |
|
| 1361 |
def normalize_prefix(self, prefix: str | None) -> str | None: |
| 1362 |
""" |
| 1363 |
Given a prefix (string or None), return its normalized form. |
| 1364 |
|
| 1365 |
The result should always be None for the trivial prefix, and a non-zero length DNS name |
| 1366 |
for a non-trivial prefix. |
| 1367 |
|
| 1368 |
If a provider supports other identifiers for the trivial prefix, such as '@', this |
| 1369 |
function needs to convert them to None as well. |
| 1370 |
""" |
| 1371 |
return None if prefix in ("@", "") else prefix |
| 1372 |
|
| 1373 |
def supports_bulk_actions(self) -> bool: |
| 1374 |
""" |
| 1375 |
Return whether the API supports some kind of bulk actions. |
| 1376 |
""" |
| 1377 |
return True |
| 1378 |
|
| 1379 |
def txt_record_handling( |
| 1380 |
self, |
| 1381 |
) -> t.Literal["decoded", "encoded", "encoded-no-char-encoding"]: |
| 1382 |
""" |
| 1383 |
Return how the API handles TXT records. |
| 1384 |
|
| 1385 |
Returns one of the following strings: |
| 1386 |
* 'decoded' - the API works with unencoded values |
| 1387 |
* 'encoded' - the API works with encoded values |
| 1388 |
* 'encoded-no-char-encoding' - the API works with encoded values, but without character encoding |
| 1389 |
""" |
| 1390 |
return "encoded-no-char-encoding" |
| 1391 |
|
| 1392 |
def txt_always_quote(self) -> bool: |
| 1393 |
""" |
| 1394 |
Return whether TXT records sent to the API should always be quoted. |
| 1395 |
|
| 1396 |
Returns a boolean. |
| 1397 |
|
| 1398 |
This return value is only used if txt_record_handling does not return 'decoded'. |
| 1399 |
""" |
| 1400 |
return self._api == "new" |
| 1401 |
|
| 1402 |
|
| 1403 |
def create_hetzner_provider_information( |
| 1404 |
option_provider: OptionProvider | None = None, |
| 1405 |
) -> HetznerProviderInformation: |
| 1406 |
return HetznerProviderInformation(option_provider=option_provider) |
| 1407 |
|
| 1408 |
|
| 1409 |
def create_hetzner_argument_spec() -> ArgumentSpec: |
| 1410 |
return ArgumentSpec( |
| 1411 |
argument_spec={ |
| 1412 |
"hetzner_token": { |
| 1413 |
"type": "str", |
| 1414 |
"no_log": True, |
| 1415 |
"aliases": ["api_token"], |
| 1416 |
"fallback": (env_fallback, ["HETZNER_DNS_TOKEN"]), |
| 1417 |
}, |
| 1418 |
"hetzner_api_token": { |
| 1419 |
"type": "str", |
| 1420 |
"no_log": True, |
| 1421 |
"fallback": (env_fallback, ["HETZNER_API_TOKEN"]), |
| 1422 |
}, |
| 1423 |
}, |
| 1424 |
mutually_exclusive=[["hetzner_token", "hetzner_api_token"]], |
| 1425 |
required_one_of=[["hetzner_token", "hetzner_api_token"]], |
| 1426 |
) |
| 1427 |
|
| 1428 |
|
| 1429 |
def create_hetzner_api( |
| 1430 |
option_provider: OptionProvider, http_helper: HTTPHelper |
| 1431 |
) -> HetznerAPI | _HetznerNewAPI: |
| 1432 |
hetzner_token = option_provider.get_option("hetzner_token") |
| 1433 |
hetzner_api_token = option_provider.get_option("hetzner_api_token") |
| 1434 |
if hetzner_token is not None: |
| 1435 |
return HetznerAPI(http_helper, hetzner_token) |
| 1436 |
if hetzner_api_token is not None: |
| 1437 |
return _HetznerNewAPI(http_helper, hetzner_api_token) |
| 1438 |
raise AssertionError( |
| 1439 |
"One of hetzner_token and hetzner_api_token must be provided" |
| 1440 |
) # pragma: no cover |