| 1 |
# Copyright (c) 2017-2021 Felix Fontein |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 6 |
# Do not use this from other collections or standalone plugins/modules! |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import typing as t |
| 11 |
|
| 12 |
from ansible.module_utils.common.text.converters import to_native |
| 13 |
|
| 14 |
from ansible_collections.community.dns.plugins.module_utils._record import DNSRecord |
| 15 |
from ansible_collections.community.dns.plugins.module_utils._wsdl import ( |
| 16 |
Composer, |
| 17 |
WSDLError, |
| 18 |
WSDLNetworkError, |
| 19 |
) |
| 20 |
from ansible_collections.community.dns.plugins.module_utils._zone import ( |
| 21 |
DNSZone, |
| 22 |
DNSZoneWithRecords, |
| 23 |
) |
| 24 |
from ansible_collections.community.dns.plugins.module_utils._zone_record_api import ( |
| 25 |
NOT_PROVIDED, |
| 26 |
DNSAPIAuthenticationError, |
| 27 |
DNSAPIError, |
| 28 |
ZoneRecordAPI, |
| 29 |
filter_records, |
| 30 |
) |
| 31 |
|
| 32 |
if t.TYPE_CHECKING: |
| 33 |
from .._http import HTTPHelper # pragma: no cover |
| 34 |
from .._record import IDNSRecord # pragma: no cover |
| 35 |
from .._zone_record_api import NotProvidedType # pragma: no cover |
| 36 |
|
| 37 |
_T = t.TypeVar("_T") # pragma: no cover |
| 38 |
|
| 39 |
|
| 40 |
def _create_record_from_encoding( |
| 41 |
source: dict[str, t.Any], record_type: str | None = None |
| 42 |
) -> DNSRecord[int]: |
| 43 |
source = dict(source) |
| 44 |
record_type = source.pop("type", record_type) |
| 45 |
if record_type is None: |
| 46 |
raise DNSAPIError("Record from API has no type") |
| 47 |
|
| 48 |
priority = source.pop("priority") |
| 49 |
target: str = source.pop("target") |
| 50 |
if record_type in ("PTR", "MX"): |
| 51 |
target = f"{priority} {target}" |
| 52 |
|
| 53 |
result = DNSRecord( |
| 54 |
record_id=source.pop("id"), record_type=record_type, target=target |
| 55 |
) |
| 56 |
result.prefix = source.pop("prefix", None) |
| 57 |
ttl = source.pop("ttl") |
| 58 |
result.ttl = int(ttl) if ttl is not None else None |
| 59 |
source.pop("zone", None) |
| 60 |
result.extra["comment"] = source.pop("comment") or "" |
| 61 |
result.extra.update(source) |
| 62 |
return result |
| 63 |
|
| 64 |
|
| 65 |
def _create_zone_from_encoding( |
| 66 |
source: dict[str, t.Any], |
| 67 |
prefix: str | None | NotProvidedType = NOT_PROVIDED, |
| 68 |
record_type: str | NotProvidedType = NOT_PROVIDED, |
| 69 |
) -> DNSZoneWithRecords[int, int]: |
| 70 |
zone = DNSZone(zone_id=source["id"], name=source["name"]) |
| 71 |
zone.info = { |
| 72 |
"email": source.get("email"), |
| 73 |
"ttl": source["ttl"], |
| 74 |
} |
| 75 |
return DNSZoneWithRecords( |
| 76 |
zone, |
| 77 |
filter_records( |
| 78 |
[_create_record_from_encoding(record) for record in source["records"]], |
| 79 |
prefix=prefix, |
| 80 |
record_type=record_type, |
| 81 |
), |
| 82 |
) |
| 83 |
|
| 84 |
|
| 85 |
def _encode_record( |
| 86 |
record: IDNSRecord[int | None], include_id: bool = False |
| 87 |
) -> dict[str, t.Any]: |
| 88 |
result: dict[str, t.Any] = { |
| 89 |
"type": record.type, |
| 90 |
"prefix": record.prefix, |
| 91 |
"target": record.target, |
| 92 |
"ttl": record.ttl, |
| 93 |
} |
| 94 |
if record.type in ("PTR", "MX"): |
| 95 |
try: |
| 96 |
priority, target = record.target.split(" ", 1) |
| 97 |
result["priority"] = int(priority) |
| 98 |
result["target"] = target |
| 99 |
except Exception as e: |
| 100 |
raise DNSAPIError( |
| 101 |
f'Cannot split {record.type} record "{record.target}" into integer priority and target: {e}' |
| 102 |
) from e |
| 103 |
else: |
| 104 |
result["priority"] = None |
| 105 |
if include_id: |
| 106 |
result["id"] = record.id |
| 107 |
return result |
| 108 |
|
| 109 |
|
| 110 |
class HostTechWSDLAPI(ZoneRecordAPI[int, int]): |
| 111 |
def __init__( |
| 112 |
self, |
| 113 |
http_helper: HTTPHelper, |
| 114 |
username: str, |
| 115 |
password: str, |
| 116 |
api: str = "https://ns1.hosttech.eu/public/api", |
| 117 |
debug: bool = False, |
| 118 |
) -> None: |
| 119 |
""" |
| 120 |
Create a new HostTech API instance with given username and password. |
| 121 |
""" |
| 122 |
self._http_helper = http_helper |
| 123 |
self._api = api |
| 124 |
self._namespaces = { |
| 125 |
"ns1": "https://ns1.hosttech.eu/soap", |
| 126 |
} |
| 127 |
self._username = username |
| 128 |
self._password = password |
| 129 |
self._debug = debug |
| 130 |
|
| 131 |
def _prepare(self) -> Composer: |
| 132 |
command = Composer(self._http_helper, self._api, self._namespaces) |
| 133 |
command.add_auth(self._username, self._password) |
| 134 |
return command |
| 135 |
|
| 136 |
def _announce(self, msg: str) -> None: |
| 137 |
if self._debug: |
| 138 |
pass # pragma: no cover |
| 139 |
# q.q('{0} {1} {2}'.format('=' * 4, msg, '=' * 40)) |
| 140 |
|
| 141 |
def _execute( |
| 142 |
self, command: Composer, result_name: str, acceptable_type: type[_T] |
| 143 |
) -> _T: |
| 144 |
if self._debug: |
| 145 |
pass # pragma: no cover |
| 146 |
# q.q('Request: {0}'.format(command)) |
| 147 |
try: |
| 148 |
result = command.execute(debug=self._debug) |
| 149 |
except WSDLError as e: |
| 150 |
if e.error_code == "998": |
| 151 |
raise DNSAPIAuthenticationError( |
| 152 |
f"Error on authentication ({e.error_message})" |
| 153 |
) from e |
| 154 |
raise |
| 155 |
res = result.get_result(result_name) |
| 156 |
if isinstance(res, acceptable_type): |
| 157 |
if self._debug: |
| 158 |
pass # pragma: no cover |
| 159 |
# q.q('Extracted result: {0} (type {1})'.format(res, type(res))) |
| 160 |
return res |
| 161 |
if self._debug: |
| 162 |
pass # pragma: no cover |
| 163 |
# q.q('Result: {0}; extracted type {1}'.format(result, type(res))) |
| 164 |
raise DNSAPIError( |
| 165 |
f"Result has unexpected type {type(res)} (expecting {acceptable_type})!" |
| 166 |
) |
| 167 |
|
| 168 |
def get_zone_with_records_by_name( |
| 169 |
self, |
| 170 |
name: str, |
| 171 |
prefix: str | None | NotProvidedType = NOT_PROVIDED, |
| 172 |
record_type: str | NotProvidedType = NOT_PROVIDED, |
| 173 |
) -> DNSZoneWithRecords[int, int] | None: |
| 174 |
""" |
| 175 |
Given a zone name, return the zone contents with records if found. |
| 176 |
|
| 177 |
@param name: The zone name (string) |
| 178 |
@param prefix: The prefix to filter for, if provided. Since None is a valid value, |
| 179 |
the special constant NOT_PROVIDED indicates that we are not filtering. |
| 180 |
@param record_type: The record type to filter for, if provided |
| 181 |
@return The zone information with records (DNSZoneWithRecords), or None if not found |
| 182 |
""" |
| 183 |
self._announce("get zone") |
| 184 |
command = self._prepare() |
| 185 |
command.add_simple_command("getZone", sZoneName=name) |
| 186 |
try: |
| 187 |
return _create_zone_from_encoding( |
| 188 |
self._execute(command, "getZoneResponse", dict), |
| 189 |
prefix=prefix, |
| 190 |
record_type=record_type, |
| 191 |
) |
| 192 |
except WSDLError as exc: |
| 193 |
if exc.error_origin == "server" and exc.error_message == "zone not found": |
| 194 |
return None |
| 195 |
raise DNSAPIError(f"Error while getting zone: {to_native(exc)}") from exc |
| 196 |
except WSDLNetworkError as exc: |
| 197 |
raise DNSAPIError( |
| 198 |
f"Network error while getting zone: {to_native(exc)}" |
| 199 |
) from exc |
| 200 |
|
| 201 |
def get_zone_with_records_by_id( |
| 202 |
self, |
| 203 |
zone_id: int, |
| 204 |
prefix: str | None | NotProvidedType = NOT_PROVIDED, |
| 205 |
record_type: str | NotProvidedType = NOT_PROVIDED, |
| 206 |
) -> DNSZoneWithRecords[int, int] | None: |
| 207 |
""" |
| 208 |
Given a zone ID, return the zone contents with records if found. |
| 209 |
|
| 210 |
@param zone_id: The zone ID |
| 211 |
@param prefix: The prefix to filter for, if provided. Since None is a valid value, |
| 212 |
the special constant NOT_PROVIDED indicates that we are not filtering. |
| 213 |
@param record_type: The record type to filter for, if provided |
| 214 |
@return The zone information with records (DNSZoneWithRecords), or None if not found |
| 215 |
""" |
| 216 |
return self.get_zone_with_records_by_name( |
| 217 |
str(zone_id), prefix=prefix, record_type=record_type |
| 218 |
) |
| 219 |
|
| 220 |
def get_zone_records( |
| 221 |
self, |
| 222 |
zone_id: int, |
| 223 |
prefix: str | None | NotProvidedType = NOT_PROVIDED, |
| 224 |
record_type: str | NotProvidedType = NOT_PROVIDED, |
| 225 |
) -> list[DNSRecord[int]] | None: |
| 226 |
""" |
| 227 |
Given a zone ID, return a list of records, optionally filtered by the provided criteria. |
| 228 |
|
| 229 |
@param zone_id: The zone ID |
| 230 |
@param prefix: The prefix to filter for, if provided. Since None is a valid value, |
| 231 |
the special constant NOT_PROVIDED indicates that we are not filtering. |
| 232 |
@param record_type: The record type to filter for, if provided |
| 233 |
@return A list of DNSrecord objects, or None if zone was not found |
| 234 |
""" |
| 235 |
result = self.get_zone_with_records_by_id( |
| 236 |
zone_id, prefix=prefix, record_type=record_type |
| 237 |
) |
| 238 |
return result.records if result is not None else None |
| 239 |
|
| 240 |
def get_zone_by_name(self, name: str) -> DNSZone[int] | None: |
| 241 |
""" |
| 242 |
Given a zone name, return the zone contents if found. |
| 243 |
|
| 244 |
@param name: The zone name (string) |
| 245 |
@return The zone information (DNSZone), or None if not found |
| 246 |
""" |
| 247 |
zone = self.get_zone_with_records_by_name(name) |
| 248 |
return zone.zone if zone else None |
| 249 |
|
| 250 |
def get_zone_by_id(self, zone_id: int) -> DNSZone[int] | None: |
| 251 |
""" |
| 252 |
Given a zone ID, return the zone contents if found. |
| 253 |
|
| 254 |
@param zone_id: The zone ID |
| 255 |
@return The zone information (DNSZone), or None if not found |
| 256 |
""" |
| 257 |
zone = self.get_zone_with_records_by_id(zone_id) |
| 258 |
return zone.zone if zone else None |
| 259 |
|
| 260 |
def add_record( |
| 261 |
self, zone_id: int, record: IDNSRecord[int | None] |
| 262 |
) -> DNSRecord[int]: |
| 263 |
""" |
| 264 |
Adds a new record to an existing zone. |
| 265 |
|
| 266 |
@param zone_id: The zone ID |
| 267 |
@param record: The DNS record (DNSRecord) |
| 268 |
@return The created DNS record (DNSRecord) |
| 269 |
""" |
| 270 |
self._announce("add record") |
| 271 |
command = self._prepare() |
| 272 |
command.add_simple_command( |
| 273 |
"addRecord", |
| 274 |
search=str(zone_id), |
| 275 |
recorddata=_encode_record(record, include_id=False), |
| 276 |
) |
| 277 |
try: |
| 278 |
return _create_record_from_encoding( |
| 279 |
self._execute(command, "addRecordResponse", dict) |
| 280 |
) |
| 281 |
except WSDLError as exc: |
| 282 |
raise DNSAPIError(f"Error while adding record: {to_native(exc)}") from exc |
| 283 |
except WSDLNetworkError as exc: |
| 284 |
raise DNSAPIError( |
| 285 |
f"Network error while adding record: {to_native(exc)}" |
| 286 |
) from exc |
| 287 |
|
| 288 |
def update_record(self, zone_id: int, record: DNSRecord[int]) -> DNSRecord[int]: |
| 289 |
""" |
| 290 |
Update a record. |
| 291 |
|
| 292 |
@param zone_id: The zone ID |
| 293 |
@param record: The DNS record (DNSRecord) |
| 294 |
@return The DNS record (DNSRecord) |
| 295 |
""" |
| 296 |
if record.id is None: |
| 297 |
raise DNSAPIError("Need record ID to update record!") |
| 298 |
self._announce("update record") |
| 299 |
command = self._prepare() |
| 300 |
command.add_simple_command( |
| 301 |
"updateRecord", |
| 302 |
recordId=record.id, |
| 303 |
recorddata=_encode_record(record, include_id=False), |
| 304 |
) |
| 305 |
try: |
| 306 |
return _create_record_from_encoding( |
| 307 |
self._execute(command, "updateRecordResponse", dict) |
| 308 |
) |
| 309 |
except WSDLError as exc: |
| 310 |
raise DNSAPIError(f"Error while updating record: {to_native(exc)}") from exc |
| 311 |
except WSDLNetworkError as exc: |
| 312 |
raise DNSAPIError( |
| 313 |
f"Network error while updating record: {to_native(exc)}" |
| 314 |
) from exc |
| 315 |
|
| 316 |
def delete_record(self, zone_id: int, record: DNSRecord[int]) -> bool: |
| 317 |
""" |
| 318 |
Delete a record. |
| 319 |
|
| 320 |
@param zone_id: The zone ID |
| 321 |
@param record: The DNS record (DNSRecord) |
| 322 |
@return True in case of success (boolean) |
| 323 |
""" |
| 324 |
if record.id is None: |
| 325 |
raise DNSAPIError("Need record ID to delete record!") |
| 326 |
self._announce("delete record") |
| 327 |
command = self._prepare() |
| 328 |
command.add_simple_command("deleteRecord", recordId=record.id) |
| 329 |
try: |
| 330 |
return self._execute(command, "deleteRecordResponse", bool) |
| 331 |
except WSDLError as exc: |
| 332 |
raise DNSAPIError(f"Error while deleting record: {to_native(exc)}") from exc |
| 333 |
except WSDLNetworkError as exc: |
| 334 |
raise DNSAPIError( |
| 335 |
f"Network error while deleting record: {to_native(exc)}" |
| 336 |
) from exc |