From e13ef93836f77e5bcf1e23b8a46dae77cda2773f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lauri=20V=C3=B5sandi?= Date: Sat, 24 Sep 2022 08:43:25 +0300 Subject: [PATCH] Add replica support --- bind-sidecar.py | 46 +++++++++++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/bind-sidecar.py b/bind-sidecar.py index f23204b..6c95b10 100755 --- a/bind-sidecar.py +++ b/bind-sidecar.py @@ -1,13 +1,19 @@ #!/usr/bin/env python3 +import argparse import asyncio import ecs_logging import logging import os -import sys +import signal +import socket from kubernetes_asyncio.client.api_client import ApiClient from kubernetes_asyncio import client, config, watch from time import time +parser = argparse.ArgumentParser() +parser.add_argument("--replica", action="store_true") +args = parser.parse_args() + # Get the Logger logger = logging.getLogger() logger.setLevel(logging.INFO) @@ -17,14 +23,6 @@ handler = logging.StreamHandler() handler.setFormatter(ecs_logging.StdlibFormatter()) logger.addHandler(handler) -ZONEFILE_TEMPLATE = """ -@ IN SOA ns1.%(zone)s. hostmaster.%(zone)s. (2022060820 300 300 300 300) - NS ns1.%(zone)s. -ns1 A %(ip)s -""" - -_, ip = sys.argv - PATH_CONFIG = "/var/bind/bind.conf" PATH_ZONEFILE = "/var/bind/db.%s" @@ -32,11 +30,21 @@ active_zones = set() def update_config(): + master = socket.gethostbyname("bind-primary") with open(PATH_CONFIG + ".part", "w") as fh: for zone in active_zones: path = PATH_ZONEFILE % zone - fh.write("zone \"%s\" { type master; file \"%s\"; };\n" % (zone, path)) + if args.replica: + fh.write("zone \"%s\" { type slave; masters { %s key zone-transfer; }; };\n" % (zone, master)) + else: + fh.write("zone \"%s\" { type master; file \"%s\"; };\n" % (zone, path)) os.rename(PATH_CONFIG + ".part", PATH_CONFIG) + logger.debug("File %s updated", PATH_CONFIG) + try: + with open("/var/bind/named.pid") as fh: + os.kill(int(fh.read()), signal.SIGHUP) + except FileNotFoundError: + logger.warn("File /var/bind/named.pid not found, assuming Bind not running yet") async def update_loop(v1, apps_api, api_instance, revision): @@ -50,15 +58,15 @@ async def update_loop(v1, apps_api, api_instance, revision): if event["type"] == "ADDED": zone = event["object"]["metadata"]["name"] active_zones.add(zone) - path = PATH_ZONEFILE % zone - logger.info("Adding zone: %s", zone) - if not os.path.exists(path): - with open(path + ".part", "w") as fh: - fh.write(ZONEFILE_TEMPLATE % { - "ip": ip, - "zone": zone - }) - os.rename(path + ".part", path) + if not args.replica: + path = PATH_ZONEFILE % zone + logger.info("Adding zone: %s", zone) + if not os.path.exists(path): + with open(path + ".part", "w") as fh: + fh.write("@ IN SOA ns1.%(zone)s. hostmaster.%(zone)s. (1 300 300 300 300)\n" % locals()) + fh.write(" NS ns1.%(zone)s.\n" % locals()) + fh.write("ns1 A 127.0.0.1\n") + os.rename(path + ".part", path) update_config() elif event["type"] == "DELETED": logger.info("Removing zone: %s", zone)