1
Fork 0

Extract traefik rule parsing to separate method

This commit is contained in:
Jake Howard 2023-08-24 21:49:26 +01:00
parent f4dd0870c0
commit e8a8cd1dce
Signed by: jake
GPG key ID: 57AFB45680EDD477

View file

@ -1,6 +1,7 @@
import requests import requests
from typing import NamedTuple from typing import NamedTuple
import re import re
import sys
TRAEFIK_HOST_RE = re.compile(r"Host\(`([a-z0-9\.-]+)`\)") TRAEFIK_HOST_RE = re.compile(r"Host\(`([a-z0-9\.-]+)`\)")
@ -10,18 +11,26 @@ class Route(NamedTuple):
hostname: str hostname: str
def parse_traefik_rule(rule: str) -> list[str]:
if "Host(" not in rule:
return []
return TRAEFIK_HOST_RE.findall(rule)
def get_traefik_routes(traefik_host: str, traefik_route: str): def get_traefik_routes(traefik_host: str, traefik_route: str):
api_response = requests.get(f"{traefik_host}/api/http/routers").json() api_response = requests.get(f"{traefik_host}/api/http/routers").json()
routes = set() routes = set()
for router in api_response: for router in api_response:
if "Host(" not in router["rule"]: hosts = parse_traefik_rule(router["rule"])
continue
hosts = TRAEFIK_HOST_RE.findall(router["rule"])
if not hosts: if not hosts:
raise ValueError(f"Failed to find host for {router['rule']}") print(f"Failed to find host for {router['rule']}", file=sys.stderr)
continue
if len(hosts) > 1:
print(f"WARNING: Found multiple hosts for rule: {router['rule']}", file=sys.stderr)
routes.add(Route( routes.add(Route(
router["service"], router["service"],