usr_conf_data_handlers.py 17.4 KB
Newer Older
1
from typing import List, Dict, Union, Any
2 3 4

from yangson.instance import InstanceRoute, ObjectValue, EntryKeys, MemberName
from . import knot_api
5
from .data import BaseDataListener, SchemaNode, ChangeType, DataChange
6
from .helpers import PathFormat, ErrorHelpers, LogHelpers, DataHelpers
7
from .knot_api import RRecordBase, SOARecord, ARecord, AAAARecord, NSRecord, MXRecord
8

9
JsonNodeT = Union[Dict[str, Any], List]
10 11 12 13
epretty = ErrorHelpers.epretty
debug_confh = LogHelpers.create_module_dbg_logger(__name__)


14
# Config handler for "server" section
15 16 17 18 19
class KnotConfServerListener(BaseDataListener):
    def process(self, sn: SchemaNode, ii: InstanceRoute, ch: DataChange):
        debug_confh(self.__class__.__name__ + " triggered")

        base_ii_str = self.schema_path
20
        base_ii = DataHelpers.parse_ii(base_ii_str, PathFormat.URL)
21
        base_nv = self.ds.get_data_root().goto(base_ii).value
22

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
        knot_api.KNOT.unset_section(section="server")

        knot_api.KNOT.set_item(
            section="server",
            identifier=None,
            item="comment",
            value=base_nv.get("description")
        )
        knot_api.KNOT.set_item(
            section="server",
            identifier=None,
            item="async-start",
            value=base_nv.get("knot-dns:async-start")
        )
        knot_api.KNOT.set_item(
            section="server",
            identifier=None,
            item="nsid",
            value=base_nv.get("nsid-identity", {}).get("nsid")
        )
43

44
        listen_endpoints = base_nv.get("listen-endpoint", [])
45 46 47 48 49 50 51 52

        ep_str_list = []
        for ep in listen_endpoints:
            ep_str = ep["ip-address"]
            if ep.get("port"):
                ep_str += "@" + str(ep["port"])
            ep_str_list.append(ep_str)

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
        knot_api.KNOT.set_item_list(
            section="server",
            identifier=None,
            item="listen",
            value=ep_str_list
        )

        knot_api.KNOT.set_item(
            section="server",
            identifier=None,
            item="rundir",
            value=base_nv.get("filesystem-paths", {}).get("run-time-dir")
        )
        knot_api.KNOT.set_item(
            section="server",
            identifier=None,
            item="pidfile",
            value=base_nv.get("filesystem-paths", {}).get("pid-file")
        )
        knot_api.KNOT.set_item(
            section="server",
            identifier=None,
            item="tcp-workers",
            value=base_nv.get("resources", {}).get("knot-dns:tcp-workers")
        )
        knot_api.KNOT.set_item(
            section="server",
            identifier=None,
            item="udp-workers",
            value=base_nv.get("resources", {}).get("knot-dns:udp-workers")
        )
        knot_api.KNOT.set_item(
            section="server",
            identifier=None,
            item="rate-limit-table-size",
            value=base_nv.get("response-rate-limiting", {}).get("table-size")
        )


# Config handler for "log" section
93 94 95 96 97
class KnotConfLogListener(BaseDataListener):
    def process(self, sn: SchemaNode, ii: InstanceRoute, ch: DataChange):
        debug_confh(self.__class__.__name__ + " triggered")

        base_ii_str = self.schema_path
98
        base_ii = DataHelpers.parse_ii(base_ii_str, PathFormat.URL)
99
        base_nv = self.ds.get_data_root().goto(base_ii).value
100

Pavel Spirek's avatar
Pavel Spirek committed
101
        knot_api.KNOT.unset_section(section="log")
102 103 104 105 106 107

        for logitem in base_nv:
            tgt = logitem.get("target")
            if tgt is None:
                continue

Pavel Spirek's avatar
Pavel Spirek committed
108 109 110 111 112
            knot_api.KNOT.set_item(section="log", identifier=None, item="target", value=tgt)
            knot_api.KNOT.set_item(section="log", identifier=tgt, item="comment", value=logitem.get("description"))
            knot_api.KNOT.set_item(section="log", identifier=tgt, item="server", value=logitem.get("server"))
            knot_api.KNOT.set_item(section="log", identifier=tgt, item="zone", value=logitem.get("zone"))
            knot_api.KNOT.set_item(section="log", identifier=tgt, item="any", value=logitem.get("any"))
113 114


115
# Config handler for "zone" section
116 117 118 119 120
class KnotConfZoneListener(BaseDataListener):
    def process(self, sn: SchemaNode, ii: InstanceRoute, ch: DataChange):
        debug_confh(self.__class__.__name__ + " triggered")

        base_ii_str = self.schema_path
121
        base_ii = DataHelpers.parse_ii(base_ii_str, PathFormat.URL)
122 123 124 125 126 127 128

        # Create new zone
        if (ii == base_ii) and (ch.change_type == ChangeType.CREATE):
            domain = ch.data["zone"]["domain"]
            debug_confh("Creating new zone \"{}\"".format(domain))
            knot_api.KNOT.zone_new(domain)
        # Delete zone
129 130
        elif (len(ii) == 4) and isinstance(ii[3], EntryKeys) and (ch.change_type == ChangeType.DELETE):
            domain = ii[3].keys["domain"]
131 132 133
            debug_confh("Deleting zone \"{}\"".format(domain))
            knot_api.KNOT.zone_remove(domain)
        # Edit particular zone
134 135
        elif (len(ii) >= 4) and isinstance(ii[2], MemberName) and isinstance(ii[3], EntryKeys):
            domain = ii[3].keys["domain"]
136 137 138
            debug_confh("Editing config of zone \"{}\"".format(domain))

            # Write whole zone config to Knot
139 140
            zone_nv = self.ds.get_data_root().goto(ii[0:4]).value
            knot_api.KNOT.unset_section(section="zone", identifier=domain)
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
            knot_api.KNOT.set_item(
                section="zone",
                identifier=None,
                item="domain",
                value=domain
            )
            knot_api.KNOT.set_item(
                section="zone",
                identifier=domain,
                item="comment",
                value=zone_nv.get("description")
            )
            knot_api.KNOT.set_item(
                section="zone",
                identifier=domain,
                item="file",
                value=zone_nv.get("file")
            )
            knot_api.KNOT.set_item_list(
                section="zone",
                identifier=domain,
                item="master",
                value=zone_nv.get("master", [])
            )
            knot_api.KNOT.set_item_list(
                section="zone",
                identifier=domain,
                item="notify",
                value=zone_nv.get("notify", {}).get("recipient", [])
            )
            knot_api.KNOT.set_item_list(
                section="zone",
                identifier=domain,
                item="acl",
                value=zone_nv.get("access-control-list", [])
            )
            knot_api.KNOT.set_item(
                section="zone",
                identifier=domain,
                item="serial-policy",
                value=zone_nv.get("serial-update-method")
            )
183 184

            anytotcp = zone_nv.get("any-to-tcp")
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
            knot_api.KNOT.set_item(
                section="zone",
                identifier=domain,
                item="disable-any",
                value=str(not anytotcp) if isinstance(anytotcp, bool) else None
            )
            knot_api.KNOT.set_item(
                section="zone",
                identifier=domain,
                item="max-journal-size",
                value=zone_nv.get("journal", {}).get("maximum-journal-size")
            )
            knot_api.KNOT.set_item(
                section="zone",
                identifier=domain,
                item="zonefile-sync",
                value=zone_nv.get("journal", {}).get("zone-file-sync-delay")
            )
            knot_api.KNOT.set_item(
                section="zone",
                identifier=domain,
                item="ixfr-from-differences",
                value=zone_nv.get("journal", {}).get("from-differences")
            )

            qm_list = zone_nv.get("query-module", [])
            knot_api.KNOT.set_item_list(
                section="zone",
                identifier=domain,
                item="module",
                value=list(map(lambda n: n["name"] + "/" + n["type"][0], qm_list))
            )
            knot_api.KNOT.set_item(
                section="zone",
                identifier=domain,
                item="semantic-checks",
                value=zone_nv.get("knot-dns:semantic-checks")
            )


# Config handler for "control" section
226 227 228 229 230
class KnotConfControlListener(BaseDataListener):
    def process(self, sn: SchemaNode, ii: InstanceRoute, ch: DataChange):
        debug_confh(self.__class__.__name__ + " triggered")

        base_ii_str = self.schema_path
231
        base_ii = DataHelpers.parse_ii(base_ii_str, PathFormat.URL)
232
        base_nv = self.ds.get_data_root().goto(base_ii).value
233

234 235 236 237 238 239
        knot_api.KNOT.set_item(
            section="control",
            identifier=None,
            item="listen",
            value=base_nv.get("unix")
        )
240 241


242
# Config handler for "acl" section
243
class KnotConfAclListener(BaseDataListener):
244 245
    @staticmethod
    def _process_list_item(acl_nv: ObjectValue):
246 247 248
        name = acl_nv.get("name")
        debug_confh("ACL name={}".format(name))

249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
        knot_api.KNOT.set_item(
            section="acl",
            identifier=None,
            item="id",
            value=name
        )
        knot_api.KNOT.set_item(
            section="acl",
            identifier=name,
            item="comment",
            value=acl_nv.get("description")
        )
        knot_api.KNOT.set_item_list(
            section="acl",
            identifier=name,
            item="key",
            value=acl_nv.get("key", [])
        )
        knot_api.KNOT.set_item_list(
            section="acl",
            identifier=name,
            item="action",
            value=acl_nv.get("operation", [])
        )

        netws = acl_nv.get("network", [])
        knot_api.KNOT.set_item_list(
            section="acl",
            identifier=name,
            item="address",
            value=list(map(lambda n: n["ip-prefix"], netws))
        )
281 282

        action = acl_nv.get("action")
283 284 285 286 287 288
        knot_api.KNOT.set_item(
            section="acl",
            identifier=name,
            item="deny",
            value={"deny": "true", "allow": "false"}.get(action)
        )
289 290 291 292 293

    def process(self, sn: SchemaNode, ii: InstanceRoute, ch: DataChange):
        debug_confh(self.__class__.__name__ + " triggered")

        base_ii_str = self.schema_path
294
        base_ii = DataHelpers.parse_ii(base_ii_str, PathFormat.URL)
295
        base_nv = self.ds.get_data_root().goto(base_ii).value
296

Pavel Spirek's avatar
Pavel Spirek committed
297
        knot_api.KNOT.unset_section(section="acl")
298
        for acl_nv in base_nv:
299 300 301
            self._process_list_item(acl_nv)


302
# Zone data handler
303
class KnotZoneDataListener(BaseDataListener):
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
    # Create RR object from "rdata" json node
    @staticmethod
    def _rr_from_rdata_item(domain_name: str, rr_owner: str, rr_ttl: int, rr_type: str, rdata_item: JsonNodeT) -> RRecordBase:
        try:
            if rr_type == "A":
                new_rr = ARecord(domain_name, rr_ttl)
                new_rr.owner = rr_owner
                new_rr.address = rdata_item["A"]["address"]
            elif rr_type == "AAAA":
                new_rr = AAAARecord(domain_name, rr_ttl)
                new_rr.owner = rr_owner
                new_rr.address = rdata_item["AAAA"]["address"]
            elif rr_type == "NS":
                new_rr = NSRecord(domain_name, rr_ttl)
                new_rr.owner = rr_owner
                new_rr.nsdname = rdata_item["NS"]["nsdname"]
            elif rr_type == "MX":
                new_rr = MXRecord(domain_name, rr_ttl)
                new_rr.owner = rr_owner
                new_rr.exchange = rdata_item["MX"]["exchange"]
            else:
                new_rr = None
        except KeyError:
            new_rr = None

        return new_rr

331 332 333 334
    def process(self, sn: SchemaNode, ii: InstanceRoute, ch: DataChange):
        debug_confh(self.__class__.__name__ + " triggered")

        base_ii_str = "/dns-zones:zone-data"
335
        base_ii = DataHelpers.parse_ii(base_ii_str, PathFormat.URL)
336 337 338 339 340 341 342 343
        base_ii_len = len(base_ii)
        ii_str = "".join([str(seg) for seg in ii])

        debug_confh("ZoneDataHandler: Change at sn \"{}\", dn \"{}\"".format(sn.name, ii_str))

        # Create new zone with SOA in zone data section
        if (ii == base_ii) and (ch.change_type == ChangeType.CREATE):
            domain_name = ch.data["zone"]["name"]
344
            def_ttl = ch.data["zone"]["default-ttl"]
345 346 347 348

            soa = ch.data.get("zone", {}).get("SOA")

            soarr = SOARecord()
349
            soarr.ttl = def_ttl
350 351 352 353 354 355 356 357 358 359 360 361 362 363
            soarr.mname = soa["mname"]
            soarr.rname = soa["rname"]
            soarr.serial = soa["serial"]
            soarr.refresh = soa["refresh"]
            soarr.retry = soa["retry"]
            soarr.expire = soa["expire"]
            soarr.minimum = soa["minimum"]

            debug_confh("KnotApi: adding new SOA RR to zone \"{}\"".format(domain_name))
            knot_api.KNOT.zone_add_record(domain_name, soarr)

        # Add resource record to particular zone
        elif (
                len(ii) == (base_ii_len + 2)) \
364
                and isinstance(ii[base_ii_len], MemberName) and (ii[base_ii_len].key == "zone") \
365
                and isinstance(ii[base_ii_len + 1], EntryKeys) \
366 367
                and (ch.change_type == ChangeType.CREATE) \
                and (ch.data.get("rrset") is not None):
368 369
            domain_name = ii[base_ii_len + 1].keys["name"]
            rr = ch.data.get("rrset", {})
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
            rr_owner = rr["owner"]
            rr_type = rr.get("type").split(":")[-1]
            rr_ttl = rr.get("ttl")
            if rr_ttl is None:
                # Obtain default ttl from datastore if not specified explicitly
                rr_ttl = self.ds.get_data_root().goto(ii[0:3]).value["default-ttl"]

            for rdata_item in rr["rdata"]:
                new_rr = self._rr_from_rdata_item(domain_name, rr_owner, rr_ttl, rr_type, rdata_item)
                if new_rr is not None:
                    debug_confh("KnotApi: adding new {} RR to zone \"{}\"".format(rr_type, domain_name))
                    knot_api.KNOT.zone_add_record(domain_name, new_rr)

        # Add resource record to particular zone (only specific "rdata" item)
        elif (
                len(ii) == (base_ii_len + 4)) \
386
                and isinstance(ii[base_ii_len], MemberName) and (ii[base_ii_len].key == "zone") \
387
                and isinstance(ii[base_ii_len + 1], EntryKeys) \
388
                and isinstance(ii[base_ii_len + 2], MemberName) and (ii[base_ii_len + 2].key == "rrset") \
389 390 391 392 393 394 395 396
                and isinstance(ii[base_ii_len + 3], EntryKeys) \
                and (ch.change_type == ChangeType.CREATE) \
                and (ch.data.get("rdata") is not None):
            domain_name = ii[base_ii_len + 1].keys["name"]
            rdata_item = ch.data.get("rdata", {})
            keys_ii_seg = ii[len(base_ii) + 3]
            rr_owner = keys_ii_seg.keys["owner"]
            rr_type = keys_ii_seg.keys["type"][0].split(":")[-1]
397

398 399 400 401 402 403 404
            # Try to use record-specific ttl first
            rr_ttl = self.ds.get_data_root().goto(ii).value.get("ttl")
            if rr_ttl is None:
                # Obtain default ttl from datastore if not specified explicitly
                rr_ttl = self.ds.get_data_root().goto(ii[0:3]).value["default-ttl"]

            new_rr = self._rr_from_rdata_item(domain_name, rr_owner, rr_ttl, rr_type, rdata_item)
405 406

            if new_rr is not None:
407
                debug_confh("KnotApi: adding new {} RR to zone \"{}\"".format(rr_type, domain_name))
408 409 410 411 412
                knot_api.KNOT.zone_add_record(domain_name, new_rr)

        # Delete resource record from particular zone
        elif (
                len(ii) == (base_ii_len + 4)) \
413
                and isinstance(ii[base_ii_len], MemberName) and (ii[base_ii_len].key == "zone") \
414
                and isinstance(ii[base_ii_len + 1], EntryKeys) \
415
                and isinstance(ii[base_ii_len + 2], MemberName) and (ii[base_ii_len + 2].key == "rrset") \
416 417 418 419 420 421 422
                and isinstance(ii[base_ii_len + 3], EntryKeys) \
                and (ch.change_type == ChangeType.DELETE):
            domain_name = ii[base_ii_len + 1].keys["name"]
            keys_ii_seg = ii[len(base_ii) + 3]
            rr_owner = keys_ii_seg.keys["owner"]
            rr_type = keys_ii_seg.keys["type"][0]

423
            debug_confh("KnotApi: deleting {} RR from zone \"{}\"".format(rr_type, domain_name))
424 425
            knot_api.KNOT.zone_del_record(domain_name, rr_owner, rr_type)

426 427 428
        # Delete resource record from particular zone (only specific "rdata" item)
        elif (
                len(ii) == (base_ii_len + 6)) \
429
                and isinstance(ii[base_ii_len], MemberName) and (ii[base_ii_len].key == "zone") \
430
                and isinstance(ii[base_ii_len + 1], EntryKeys) \
431
                and isinstance(ii[base_ii_len + 2], MemberName) and (ii[base_ii_len + 2].key == "rrset") \
432
                and isinstance(ii[base_ii_len + 3], EntryKeys) \
433
                and isinstance(ii[base_ii_len + 4], MemberName) and (ii[base_ii_len + 4].key == "rdata") \
434 435 436 437 438 439 440 441 442 443 444 445
                and isinstance(ii[base_ii_len + 5], EntryKeys) \
                and (ch.change_type == ChangeType.DELETE):
            domain_name = ii[base_ii_len + 1].keys["name"]
            keys_ii_seg = ii[len(base_ii) + 3]
            rr_owner = keys_ii_seg.keys["owner"]
            rr_type = keys_ii_seg.keys["type"][0]
            rdata_item = self.ds.get_data_root(previous_version=1).goto(ii).value

            rr_sel = self._rr_from_rdata_item(domain_name, rr_owner, 0, rr_type, rdata_item)

            debug_confh("KnotApi: deleting {} RR from zone \"{}\"".format(rr_type, domain_name))
            knot_api.KNOT.zone_del_record(domain_name, rr_owner, rr_type, selector=rr_sel.rrdata_format())