def handle_mqtt_message( client: mqtt_client.Client, userdata: bytes, message: mqtt_client.MQTTMessage ) -> None: """Prints message contents.""" # TODO(ruairi): Clarify current usage of this function. logger.debug( f"MQTT message received on {message.topic}: {message.payload.decode()}" )
def handle_mqtt_connect( client: mqtt_client.Client, userdata: bytes, flags: Any, rc: Any ) -> None: """Prints status of connect message.""" # TODO(ruairi): Clarify current usage of this function. logger.debug( "MQTT connected to {}:{}".format( app.config["MQTT_BROKER_URL"], app.config["MQTT_BROKER_PORT"] ) )
def on_connect(client: mqtt.Client, userdata: Any, flags, rc) -> None: """Handles MQTT connect and subscribes to topics on connect Arguments: client: the client instance for this callback. userdata: the private user data. flags: The MQTT flags. rc: The MQTT rc. """ logger.debug("Connected with result code " + str(rc)) domains = load_config().get("domains") # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. for domain in domains: topic = f"wireguard/{domain}/+" logger.info(f"Subscribing to topic {topic}") client.subscribe(topic)
def on_message(client: mqtt.Client, userdata: Any, message: mqtt.MQTTMessage) -> None: """Processes messages from MQTT and forwards them to netlink. Arguments: client: the client instance for this callback. userdata: the private user data. message: The MQTT message. """ # TODO(ruairi): Check bounds and raise exception here. logger.debug("Got message %s from MTQQ", message) domain_prefix = load_config().get("domain_prefix") domain = re.search(r"/.*" + domain_prefix + "(\w+)/", message.topic) if not domain: raise ValueError("Could not find a match for %s on %s", domain_prefix, message.topic) domain = domain.group(1) logger.debug("Found domain %s", domain) client = WireGuardClient( public_key=str(message.payload.decode("utf-8")), domain=domain, remove=False, ) logger.info( f"Received create message for key {client.public_key} on domain {domain} with lladdr {client.lladdr}" ) # TODO(ruairi): Verify return type here. logger.debug(link_handler(client))
def wg_flush_stale_peers(domain: str) -> List[Dict]: """Removes stale peers. Arguments: domain: The domain to detect peers on. Returns: The peers which we can remove. """ logger.info("Searching for stale clients for %s", domain) stale_clients = [ stale_client for stale_client in find_stale_wireguard_clients("wg-" + domain) ] logger.debug("Found stale clients: %s", stale_clients) logger.info("Searching for stale WireGuard clients.") stale_wireguard_clients = [ WireGuardClient(public_key=stale_client, domain=domain, remove=True) for stale_client in stale_clients ] logger.debug("Found stable WireGuard clients: %s", stale_wireguard_clients) logger.info("Processing clients.") link_handled = [ link_handler(stale_client) for stale_client in stale_wireguard_clients ] logger.debug("Handled the following clients: %s", link_handled) return link_handled
def clean_up_worker(domains: List[Text]) -> None: """Wraps flush_workers in a thread for all given domains. Arguments: domains: list of domains. """ logger.debug("Cleaning up the following domains: %s", domains) prefix = config.load_config().get("domain_prefix") for domain in domains: logger.info("Scheduling cleanup task for %s, ", domain) try: cleaned_domain = domain.split(prefix)[1] except IndexError: logger.error( "Cannot strip domain with prefix %s from passed value %s. Skipping cleanup operation", prefix, domain, ) continue thread = threading.Thread(target=flush_workers, args=(cleaned_domain, )) thread.start()
def link_handler(client: WireGuardClient) -> Dict: """Updates fdb, route and WireGuard peers tables for a given WireGuard peer. Arguments: client: A WireGuard peer to manipulate. Returns: The outcome of each operation. """ results = dict() # Updates WireGuard peers. results.update({"Wireguard": update_wireguard_peer(client)}) logger.debug("Handling links for %s", client) try: # Updates routes to the WireGuard Peer. results.update({"Route": route_handler(client)}) logger.info("Updated route for %s", client) except Exception as e: # TODO(ruairi): re-raise exception here. logger.error("Failed to update route for %s (%s)", client, e) results.update({"Route": e}) # Updates WireGuard FDB. results.update({"Bridge FDB": bridge_fdb_handler(client)}) logger.debug("Updated Bridge FDB for %s", client) return results