Zack Williams | caf0566 | 2020-10-09 19:52:40 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | |
| 3 | # SPDX-FileCopyrightText: © 2020 Open Networking Foundation <support@opennetworking.org> |
| 4 | # SPDX-License-Identifier: Apache-2.0 |
| 5 | |
| 6 | # netbox_edgeconfig.py |
| 7 | # given a s |
| 8 | |
| 9 | from __future__ import absolute_import |
| 10 | |
| 11 | import argparse |
| 12 | import json |
| 13 | import logging |
| 14 | import netaddr |
| 15 | import os |
| 16 | import re |
| 17 | import ssl |
| 18 | import urllib.parse |
| 19 | import urllib.request |
| 20 | from ruamel import yaml |
| 21 | |
| 22 | # create shared logger |
| 23 | logging.basicConfig() |
| 24 | logger = logging.getLogger("nbec") |
| 25 | |
| 26 | # global dict of jsonpath expressions -> compiled jsonpath parsers, as |
| 27 | # reparsing expressions in each loop results in 100x longer execution time |
| 28 | jpathexpr = {} |
| 29 | |
| 30 | # headers to pass, set globally |
| 31 | headers = [] |
| 32 | |
| 33 | # settings |
| 34 | settings = {} |
| 35 | |
| 36 | # cached data from API |
| 37 | device_interface_cache = {} |
| 38 | device_services_cache = {} |
| 39 | interface_mac_cache = {} |
| 40 | |
| 41 | |
| 42 | def parse_nb_args(): |
| 43 | """ |
| 44 | parse CLI arguments |
| 45 | """ |
| 46 | |
| 47 | parser = argparse.ArgumentParser(description="NetBox Edge Config") |
| 48 | |
| 49 | # Positional args |
| 50 | parser.add_argument( |
| 51 | "settings", |
| 52 | type=argparse.FileType("r"), |
| 53 | help="YAML ansible inventory file w/NetBox API token", |
| 54 | ) |
| 55 | |
| 56 | parser.add_argument( |
| 57 | "--debug", action="store_true", help="Print additional debugging information" |
| 58 | ) |
| 59 | |
| 60 | return parser.parse_args() |
| 61 | |
| 62 | |
| 63 | def json_api_get( |
| 64 | url, |
| 65 | headers, |
| 66 | data=None, |
| 67 | trim_prefix=False, |
| 68 | allow_failure=False, |
| 69 | validate_certs=False, |
| 70 | ): |
| 71 | """ |
| 72 | Call JSON API endpoint, return data as a dict |
| 73 | """ |
| 74 | |
| 75 | logger.debug("json_api_get url: %s", url) |
| 76 | |
| 77 | # if data included, encode it as JSON |
| 78 | if data: |
| 79 | data_enc = str(json.dumps(data)).encode("utf-8") |
| 80 | |
| 81 | request = urllib.request.Request(url, data=data_enc, method="POST") |
| 82 | request.add_header("Content-Type", "application/json; charset=UTF-8") |
| 83 | else: |
| 84 | request = urllib.request.Request(url) |
| 85 | |
| 86 | # add headers tuples |
| 87 | for header in headers: |
| 88 | request.add_header(*header) |
| 89 | |
| 90 | try: |
| 91 | |
| 92 | if validate_certs: |
| 93 | response = urllib.request.urlopen(request) |
| 94 | |
| 95 | else: |
| 96 | ctx = ssl.create_default_context() |
| 97 | ctx.check_hostname = False |
| 98 | ctx.verify_mode = ssl.CERT_NONE |
| 99 | |
| 100 | response = urllib.request.urlopen(request, context=ctx) |
| 101 | |
| 102 | except urllib.error.HTTPError: |
| 103 | # asking for data that doesn't exist results in a 404, just return nothing |
| 104 | if allow_failure: |
| 105 | return None |
| 106 | logger.exception("Server encountered an HTTPError at URL: '%s'", url) |
| 107 | except urllib.error.URLError: |
| 108 | logger.exception("An URLError occurred at URL: '%s'", url) |
| 109 | else: |
| 110 | # docs: https://docs.python.org/3/library/json.html |
| 111 | jsondata = response.read() |
| 112 | logger.debug("API response: %s", jsondata) |
| 113 | |
| 114 | try: |
| 115 | data = json.loads(jsondata) |
| 116 | except json.decoder.JSONDecodeError: |
| 117 | # allow return of no data |
| 118 | if allow_failure: |
| 119 | return None |
| 120 | logger.exception("Unable to decode JSON") |
| 121 | else: |
| 122 | logger.debug("JSON decoded: %s", data) |
| 123 | |
| 124 | return data |
| 125 | |
| 126 | |
| 127 | def create_dns_zone(extension, devs): |
| 128 | # Checks for dns entries |
| 129 | |
| 130 | a_recs = {} # PTR records created by inverting this |
| 131 | cname_recs = {} |
| 132 | srv_recs = {} |
| 133 | ns_recs = [] |
| 134 | txt_recs = {} |
| 135 | |
| 136 | # scan through devs and look for dns_name, if not, make from name and |
| 137 | # extension |
| 138 | for name, value in devs.items(): |
| 139 | |
| 140 | # add DNS entries for every DHCP host if there's a DHCP range |
| 141 | # DHCP addresses are of the form dhcp###.extension |
| 142 | if name == "prefix_dhcp": |
| 143 | for ip in netaddr.IPNetwork(value["dhcp_range"]).iter_hosts(): |
| 144 | a_recs["dhcp%03d" % (ip.words[3])] = str(ip) |
| 145 | |
| 146 | continue |
| 147 | |
| 148 | # require DNS names to only use ASCII characters (alphanumeric, lowercase, with dash/period) |
| 149 | # _'s are used in SRV/TXT records, but in general use aren't recommended |
| 150 | dns_name = re.sub("[^a-z0-9.-]", "-", name, 0, re.ASCII) |
| 151 | |
| 152 | # Add as an A record (and inverse, PTR record), only if it's a new name |
| 153 | if dns_name not in a_recs: |
| 154 | a_recs[dns_name] = value["ip4"] |
| 155 | else: |
| 156 | # most likely a data entry error |
| 157 | logger.warning( |
| 158 | "Duplicate DNS name '%s' for devices at IP: '%s' and '%s', ignoring", |
| 159 | dns_name, |
| 160 | a_recs[dns_name], |
| 161 | value["ip4"], |
| 162 | ) |
| 163 | continue |
| 164 | |
| 165 | # if a DNS name is given as a part of the IP address, it's viewed as a CNAME |
| 166 | if value["dns_name"]: |
| 167 | |
| 168 | if re.search("%s$" % extension, value["dns_name"]): |
| 169 | |
| 170 | # strip off the extension, and add as a CNAME |
| 171 | dns_cname = value["dns_name"].split(".%s" % extension)[0] |
| 172 | |
| 173 | elif "." in value["dns_name"]: |
| 174 | logger.warning( |
| 175 | "Device '%s' has a IP assigned DNS name '%s' outside the prefix extension: '%s', ignoring", |
| 176 | name, |
| 177 | value["dns_name"], |
| 178 | extension, |
| 179 | ) |
| 180 | continue |
| 181 | |
| 182 | else: |
| 183 | dns_cname = value["dns_name"] |
| 184 | |
| 185 | if dns_cname == dns_name: |
| 186 | logger.warning( |
| 187 | "DNS Name field '%s' is identical to device name '%s', ignoring", |
| 188 | value["dns_name"], |
| 189 | dns_name, |
| 190 | ) |
| 191 | else: |
| 192 | cname_recs[dns_cname] = "%s.%s." % (dns_name, extension) |
| 193 | |
| 194 | # Add services as cnames, and possibly ns records |
| 195 | for svc in value["services"]: |
| 196 | |
| 197 | # only add service if it uses the IP of the host |
| 198 | if value["ip4"] in svc["ip4s"]: |
| 199 | cname_recs[svc["name"]] = "%s.%s." % (dns_name, extension) |
| 200 | |
| 201 | if svc["port"] == 53 and svc["protocol"] == "udp": |
| 202 | ns_recs.append("%s.%s." % (dns_name, extension)) |
| 203 | |
| 204 | return { |
| 205 | "a": a_recs, |
| 206 | "cname": cname_recs, |
| 207 | "ns": ns_recs, |
| 208 | "srv": srv_recs, |
| 209 | "txt": txt_recs, |
| 210 | } |
| 211 | |
| 212 | |
| 213 | def create_dhcp_subnet(prefix, prefix_search, devs): |
| 214 | # makes DHCP subnet information |
| 215 | |
| 216 | subnet = {} |
| 217 | |
| 218 | subnet["subnet"] = prefix |
| 219 | subnet["dns_search"] = [prefix_search] |
| 220 | |
| 221 | hosts = [] |
| 222 | dns_servers = [] |
| 223 | |
| 224 | for name, value in devs.items(): |
| 225 | |
| 226 | # handle a DHCP range |
| 227 | if name == "prefix_dhcp": |
| 228 | subnet["range"] = value["dhcp_range"] |
| 229 | continue |
| 230 | |
| 231 | # has a MAC address, and it's not null |
| 232 | if "macaddr" in value and value["macaddr"]: |
| 233 | |
| 234 | hosts.append( |
| 235 | { |
| 236 | "name": name, |
| 237 | "ip_addr": value["ip4"], |
| 238 | "mac_addr": value["macaddr"].lower(), |
| 239 | } |
| 240 | ) |
| 241 | |
| 242 | # Add dns based on service entries |
| 243 | if "services" in value: |
| 244 | for svc in value["services"]: |
| 245 | |
| 246 | # add DNS server |
| 247 | if svc["port"] == 53 and svc["protocol"] == "udp": |
| 248 | dns_servers.append(value["ip4"]) |
| 249 | |
| 250 | # add tftp server |
| 251 | if svc["port"] == 69 and svc["protocol"] == "udp": |
| 252 | subnet["tftpd_server"] = value["ip4"] |
| 253 | |
| 254 | subnet["hosts"] = hosts |
| 255 | subnet["dns_servers"] = dns_servers |
| 256 | |
| 257 | return subnet |
| 258 | |
| 259 | |
| 260 | def find_dhcpd_interface(prefix, devs): |
| 261 | # DHCPd interface is first usable IP in range |
| 262 | |
| 263 | first_ip = str(netaddr.IPAddress(netaddr.IPNetwork(prefix).first + 1)) |
| 264 | |
| 265 | for name, value in devs.items(): |
| 266 | if value["ip4"] == first_ip: |
| 267 | return value["iface"] |
| 268 | |
| 269 | |
| 270 | def get_device_services(device_id, filters=""): |
| 271 | |
| 272 | if device_id in device_services_cache: |
| 273 | return device_services_cache[device_id] |
| 274 | |
| 275 | # get services info |
| 276 | url = "%s%s" % ( |
| 277 | settings["api_endpoint"], |
| 278 | "api/ipam/services/?device_id=%s%s" % (device_id, filters), |
| 279 | ) |
| 280 | |
| 281 | raw_svcs = json_api_get(url, headers, validate_certs=settings["validate_certs"]) |
| 282 | |
| 283 | services = [] |
| 284 | |
| 285 | for rsvc in raw_svcs["results"]: |
| 286 | |
| 287 | svc = {} |
| 288 | |
| 289 | svc["name"] = rsvc["name"] |
| 290 | svc["description"] = rsvc["description"] |
| 291 | svc["port"] = rsvc["port"] |
| 292 | svc["protocol"] = rsvc["protocol"]["value"] |
| 293 | svc["ip4s"] = [] |
| 294 | |
| 295 | for ip in rsvc["ipaddresses"]: |
| 296 | svc["ip4s"].append(str(netaddr.IPNetwork(ip["address"]).ip)) |
| 297 | |
| 298 | services.append(svc) |
| 299 | |
| 300 | device_services_cache[device_id] = services |
| 301 | return services |
| 302 | |
| 303 | |
| 304 | def get_interface_mac_addr(interface_id): |
| 305 | # return a mac addres, or None if undefined |
| 306 | if interface_id in interface_mac_cache: |
| 307 | return interface_mac_cache[interface_id] |
| 308 | |
| 309 | # get the interface info |
| 310 | url = "%s%s" % (settings["api_endpoint"], "api/dcim/interfaces/%s/" % interface_id) |
| 311 | |
| 312 | iface = json_api_get(url, headers, validate_certs=settings["validate_certs"]) |
| 313 | |
| 314 | if iface["mac_address"]: |
| 315 | interface_mac_cache[interface_id] = iface["mac_address"] |
| 316 | return iface["mac_address"] |
| 317 | |
| 318 | interface_mac_cache[interface_id] = None |
| 319 | return None |
| 320 | |
| 321 | |
| 322 | def get_device_interfaces(device_id, filters=""): |
| 323 | |
| 324 | if device_id in device_interface_cache: |
| 325 | return device_interface_cache[device_id] |
| 326 | |
| 327 | url = "%s%s" % ( |
| 328 | settings["api_endpoint"], |
| 329 | "api/dcim/interfaces/?device_id=%s%s&mgmt_only=true" % (device_id, filters), |
| 330 | ) |
| 331 | |
| 332 | logger.debug("raw_ifaces_url: %s", url) |
| 333 | |
| 334 | raw_ifaces = json_api_get(url, headers, validate_certs=settings["validate_certs"]) |
| 335 | |
| 336 | logger.debug("raw_ifaces: %s", raw_ifaces) |
| 337 | |
| 338 | ifaces = [] |
| 339 | |
| 340 | for raw_iface in raw_ifaces["results"]: |
| 341 | |
| 342 | iface = {} |
| 343 | |
| 344 | iface["name"] = raw_iface["name"] |
| 345 | iface["macaddr"] = raw_iface["mac_address"] |
| 346 | iface["mgmt_only"] = raw_iface["mgmt_only"] |
| 347 | iface["description"] = raw_iface["description"] |
| 348 | |
| 349 | if raw_iface["count_ipaddresses"]: |
| 350 | url = "%s%s" % ( |
| 351 | settings["api_endpoint"], |
| 352 | "api/ipam/ip-addresses/?interface_id=%s" % raw_iface["id"], |
| 353 | ) |
| 354 | |
| 355 | raw_ip = json_api_get( |
| 356 | url, headers, validate_certs=settings["validate_certs"] |
| 357 | ) |
| 358 | |
| 359 | iface["ip4"] = str(netaddr.IPNetwork(raw_ip["results"][0]["address"]).ip) |
| 360 | |
| 361 | ifaces.append(iface) |
| 362 | |
| 363 | device_interface_cache[device_id] = ifaces |
| 364 | return ifaces |
| 365 | |
| 366 | |
| 367 | def get_prefix_devices(prefix, filters=""): |
| 368 | |
| 369 | # get all devices in a prefix |
| 370 | url = "%s%s" % ( |
| 371 | settings["api_endpoint"], |
| 372 | "api/ipam/ip-addresses/?parent=%s%s" % (prefix, filters), |
| 373 | ) |
| 374 | |
| 375 | raw_ips = json_api_get(url, headers, validate_certs=settings["validate_certs"]) |
| 376 | |
| 377 | logger.debug("raw_ips: %s", raw_ips) |
| 378 | |
| 379 | devs = {} |
| 380 | |
| 381 | # iterate by IP, sorted |
| 382 | for ip in sorted(raw_ips["results"], key=lambda k: k["address"]): |
| 383 | |
| 384 | logger.debug("ip: %s", ip) |
| 385 | |
| 386 | # if it's a DHCP range, add that range to the dev list as prefix_dhcp |
| 387 | if ip["status"]["value"] == "dhcp": |
| 388 | devs["prefix_dhcp"] = {"dhcp_range": ip["address"]} |
| 389 | continue |
| 390 | |
| 391 | dev = {} |
| 392 | |
| 393 | dev["ip4"] = str(netaddr.IPNetwork(ip["address"]).ip) |
| 394 | dev["macaddr"] = get_interface_mac_addr(ip["assigned_object"]["id"]) |
| 395 | |
| 396 | ifaces = get_device_interfaces(ip["assigned_object"]["device"]["id"]) |
| 397 | |
| 398 | if ifaces and dev["ip4"] == ifaces[0]["ip4"]: # this is a mgmt IP |
| 399 | devname = "%s-%s" % ( |
| 400 | ip["assigned_object"]["device"]["name"].lower().split(".")[0], |
| 401 | ifaces[0]["name"], |
| 402 | ) |
| 403 | dev["iface"] = ip["assigned_object"]["name"] |
| 404 | dev["dns_name"] = "" |
| 405 | dev["services"] = [] |
| 406 | |
| 407 | else: # this is a primary IP |
| 408 | |
| 409 | name = ip["assigned_object"]["device"]["name"] |
| 410 | devname = name.lower().split(".")[0] |
| 411 | |
| 412 | dev["iface"] = ip["assigned_object"]["name"] |
| 413 | dev["dns_name"] = ip["dns_name"] if "dns_name" in ip else "None" |
| 414 | dev["services"] = get_device_services(ip["assigned_object"]["device"]["id"]) |
| 415 | |
| 416 | # fix multihomed devices in same IP range |
| 417 | # FIXME: Does not handle > 2 connections properly |
| 418 | if devname in devs: |
| 419 | devs["%s-1" % devname] = devs.pop(devname) |
| 420 | devs["%s-2" % devname] = dev |
| 421 | else: |
| 422 | devs[devname] = dev |
| 423 | |
| 424 | return devs |
| 425 | |
| 426 | |
| 427 | def get_prefix_data(prefix): |
| 428 | |
| 429 | # get all devices in a prefix |
| 430 | url = "%s%s" % (settings["api_endpoint"], "api/ipam/prefixes/?prefix=%s" % prefix) |
| 431 | |
| 432 | raw_prefix = json_api_get(url, headers, validate_certs=settings["validate_certs"]) |
| 433 | |
| 434 | logger.debug("raw_prefix: %s", raw_prefix) |
| 435 | |
| 436 | return raw_prefix["results"][0] |
| 437 | |
| 438 | |
| 439 | # main function that calls other functions |
| 440 | if __name__ == "__main__": |
| 441 | |
| 442 | args = parse_nb_args() |
| 443 | |
| 444 | # only print log messages if debugging |
| 445 | if args.debug: |
| 446 | logger.setLevel(logging.DEBUG) |
| 447 | else: |
| 448 | logger.setLevel(logging.INFO) |
| 449 | |
| 450 | # load settings from yaml file |
| 451 | settings = yaml.safe_load(args.settings.read()) |
| 452 | |
| 453 | yaml_out = {} |
| 454 | |
| 455 | # load default config |
| 456 | with open( |
| 457 | os.path.join( |
| 458 | os.path.dirname(os.path.realpath(__file__)), "base_edgeconfig.yaml" |
| 459 | ) |
| 460 | ) as defconfig: |
| 461 | yaml_out = yaml.safe_load(defconfig) |
| 462 | |
| 463 | logger.debug("settings: %s" % settings) |
| 464 | |
| 465 | # global, so this isn't run multiple times |
| 466 | headers = [ |
| 467 | ("Authorization", "Token %s" % settings["token"]), |
| 468 | ] |
| 469 | |
| 470 | # create structure from extracted data |
| 471 | dns_zones = {} |
| 472 | dns_rev_zones = {} |
| 473 | dhcpd_subnets = [] |
| 474 | dhcpd_interfaces = [] |
| 475 | devs_per_prefix = {} |
| 476 | |
| 477 | for prefix in settings["ip_prefixes"]: |
| 478 | |
| 479 | prefix_data = get_prefix_data(prefix) |
| 480 | |
| 481 | prefix_domain_extension = prefix_data["description"] |
| 482 | |
| 483 | devs = get_prefix_devices(prefix) |
| 484 | |
| 485 | devs_per_prefix[prefix] = devs |
| 486 | |
| 487 | dns_zones[prefix_domain_extension] = create_dns_zone( |
| 488 | prefix_domain_extension, devs |
| 489 | ) |
| 490 | |
| 491 | dns_zones[prefix_domain_extension]["ip_range"] = prefix |
| 492 | |
| 493 | dhcpd_subnets.append(create_dhcp_subnet(prefix, prefix_domain_extension, devs)) |
| 494 | |
| 495 | dhcpd_if = find_dhcpd_interface(prefix, devs) |
| 496 | |
| 497 | if dhcpd_if not in dhcpd_interfaces: |
| 498 | dhcpd_interfaces.append(dhcpd_if) |
| 499 | |
| 500 | yaml_out.update( |
| 501 | { |
| 502 | "dns_zones": dns_zones, |
| 503 | "dns_rev_zones": dns_rev_zones, |
| 504 | "dhcpd_subnets": dhcpd_subnets, |
| 505 | "dhcpd_interfaces": dhcpd_interfaces, |
| 506 | # "devs_per_prefix": devs_per_prefix, |
| 507 | } |
| 508 | ) |
| 509 | |
| 510 | print(yaml.safe_dump(yaml_out, indent=2)) |