Rework cluster into v2: section-based worker sync and App Gateway on workers

This commit is contained in:
Eduardo Silva
2026-11-20 11:56:30 -03:00
parent dee270695d
commit 7468cdf623
41 changed files with 2766 additions and 1014 deletions
+50 -10
View File
@@ -7,16 +7,20 @@ PYTHON="python3"
JSON_DIR="${JSON_DIR:-/caddy_json_export}"
CADDYFILE_PATH="${CADDYFILE_PATH:-/etc/caddy/Caddyfile}"
CADDY_PID=""
CLUSTER_NODE="${CLUSTER_NODE:-false}"
echo "==> Generating wireguard_webadmin.json..."
"$PYTHON" "${SCRIPT_DIR}/export_wireguard_webadmin_config.py"
# The WireGuard WebAdmin interface is only published by the primary server
if [ "$CLUSTER_NODE" != "true" ]; then
echo "==> Generating wireguard_webadmin.json..."
"$PYTHON" "${SCRIPT_DIR}/export_wireguard_webadmin_config.py"
fi
generate_caddyfile() {
"$PYTHON" "${SCRIPT_DIR}/process_config.py"
"$PYTHON" "${SCRIPT_DIR}/process_config.py" >/dev/null
# Validation output is not printed because provider errors may include credentials
if ! caddy validate --config "$CADDYFILE_PATH" --adapter caddyfile >/dev/null 2>&1; then
echo "Warning: generated Caddyfile is invalid, regenerating with DNS challenge disabled. Check the DNS credentials."
DISABLE_DNS_CHALLENGE=1 "$PYTHON" "${SCRIPT_DIR}/process_config.py"
DISABLE_DNS_CHALLENGE=1 "$PYTHON" "${SCRIPT_DIR}/process_config.py" >/dev/null
fi
}
@@ -42,27 +46,63 @@ stop_caddy() {
echo "==> Processing config files..."
generate_caddyfile
sync_tls_state >/dev/null
# Nothing is cached yet, so hosts left on a fallback certificate get a new ACME attempt
"$PYTHON" "${SCRIPT_DIR}/process_config.py" --reset-fallback-certificates
echo "==> Starting Caddy..."
start_caddy
if [ "$CLUSTER_NODE" != "true" ]; then
# Certificates used by cluster workers are exported as soon as they are issued or renewed
(
while true; do
sleep 60
"$PYTHON" "${SCRIPT_DIR}/process_config.py" --export-certificates || true
done
) &
fi
sleep 2
caddyfile_checksum() {
sha256sum "$CADDYFILE_PATH" 2>/dev/null | cut -d ' ' -f 1
}
APPLIED_CADDYFILE="$(caddyfile_checksum)"
echo "==> Watching ${JSON_DIR} for config changes..."
while true; do
inotifywait -qq -e close_write,moved_to,create "${JSON_DIR}/" --include '.*\.json$' 2>/dev/null || true
# The timeout also picks up changes written before the watch started or missed while reloading
inotifywait -qq -t 60 -e close_write,moved_to,create "${JSON_DIR}/" --include '.*\.json$' 2>/dev/null || true
sleep 1
echo "==> Config change detected, reprocessing..."
# The container that owns this network namespace was restarted: exit so Docker restarts Caddy and it
# joins the new namespace (otherwise it keeps serving from a namespace without published ports)
if [ -f "${JSON_DIR}/.netns_owner" ] && [ "$(cat "${JSON_DIR}/.netns_owner")" != "$(readlink /proc/self/ns/net)" ]; then
echo "Network namespace owner changed, restarting..."
stop_caddy
exit 1
fi
generate_caddyfile
if [ "$(sync_tls_state)" = "restart" ]; then
if ! kill -0 "$CADDY_PID" 2>/dev/null; then
echo "==> Caddy is not running, starting it again..."
sync_tls_state >/dev/null
start_caddy
APPLIED_CADDYFILE="$(caddyfile_checksum)"
elif [ "$(sync_tls_state)" = "restart" ]; then
# A reload keeps previously issued certificates cached in memory
echo "==> Certificate settings changed, restarting Caddy..."
stop_caddy
start_caddy
else
echo "==> Reloading Caddy..."
caddy reload --config "$CADDYFILE_PATH" --adapter caddyfile 2>/dev/null || echo "Warning: Caddy reload failed, will retry on next change."
APPLIED_CADDYFILE="$(caddyfile_checksum)"
elif [ "$(caddyfile_checksum)" != "$APPLIED_CADDYFILE" ]; then
echo "==> Config change detected, reloading Caddy..."
if caddy reload --config "$CADDYFILE_PATH" --adapter caddyfile 2>/dev/null; then
APPLIED_CADDYFILE="$(caddyfile_checksum)"
else
echo "Warning: Caddy reload failed, will retry on next change."
fi
fi
done
+171 -17
View File
@@ -36,6 +36,10 @@ TLS_STATE_PATH = os.path.join(CADDY_DATA_DIR, "wireguard_webadmin_tls_state.json
TLS_STATE_PENDING_PATH = f"{CADDYFILE_PATH}.tls_state.json"
# Set by entrypoint.sh when the generated Caddyfile fails validation
DISABLE_DNS_CHALLENGE = os.environ.get("DISABLE_DNS_CHALLENGE", "") == "1"
# Cluster nodes never request ACME certificates: they use the ones exported by the primary server
CLUSTER_NODE = os.environ.get("CLUSTER_NODE", "").lower() == "true"
NODE_CERTIFICATES_DIR = os.environ.get("NODE_CERTIFICATES_DIR", "/caddy_certificates")
CERTIFICATE_EXPORT_DIR = os.environ.get("CERTIFICATE_EXPORT_DIR", "/caddy_cert_export")
AUTH_IDENTITY_HEADERS = (
"X-Auth-User",
"X-Auth-Email",
@@ -92,12 +96,30 @@ def _safe_identifier(val: str) -> str:
return re.sub(r"[^A-Za-z0-9_]", "", str(val))
def get_node_host_tls(host_tls):
"""
TLS settings of a host on a cluster node: the certificate exported by the primary server, the internal CA
as fallback, or None when there is no certificate yet and the fallback is disabled.
"""
certificate_type = host_tls.get("certificate_type", DEFAULT_CERTIFICATE_TYPE)
certificate_fallback = host_tls.get("certificate_fallback", True) is not False
certificate_file = re.sub(r"[^a-f0-9]", "", str(host_tls.get("certificate_file", "")))
if certificate_type in ACME_CERTIFICATE_TYPES and certificate_file:
return "certificate_file", certificate_file, certificate_fallback
if certificate_type == "self_signed" or certificate_fallback:
return "self_signed", None, True
return None
def get_host_tls(host, tls_data):
"""
Return (certificate_type, dns_credential_name, certificate_fallback) for a host.
Hosts not listed use the HTTP challenge with fallback.
Hosts not listed use the HTTP challenge with fallback. On cluster nodes the second item is the
certificate file name, and None is returned for hosts that must not be served.
"""
host_tls = tls_data.get("hosts", {}).get(host.lower(), {})
if CLUSTER_NODE:
return get_node_host_tls(host_tls)
certificate_type = host_tls.get("certificate_type", DEFAULT_CERTIFICATE_TYPE)
if certificate_type not in CERTIFICATE_TYPES:
certificate_type = DEFAULT_CERTIFICATE_TYPE
@@ -117,15 +139,29 @@ def group_hosts_by_tls(hosts, tls_data):
"""Hosts sharing the same certificate settings are served by the same site block."""
groups = {}
for host in hosts:
groups.setdefault(get_host_tls(host, tls_data), []).append(host)
host_tls = get_host_tls(host, tls_data)
if host_tls is not None:
groups.setdefault(host_tls, []).append(host)
return groups.items()
def get_certificate_only_hosts(apps, tls_data):
"""Hosts the primary server only manages certificates for, because their application is served by workers."""
if CLUSTER_NODE:
return []
served_hosts = {host.lower() for app in apps for host in app.get("hosts", [])}
return [
host for host, host_tls in tls_data.get("hosts", {}).items()
if host_tls.get("certificate_only") and host not in served_hosts
]
def build_caddyfile(apps, auth_policies, routes, tls_data=None):
tls_data = tls_data or {}
policies = auth_policies.get("policies", {}) if auth_policies else {}
route_entries = routes.get("entries", {}) if routes else {}
lines = []
# Caddy refuses an empty Caddyfile, which happens on cluster nodes without applications
lines = ["# Generated by process_config.py. Do not edit.", ""]
def get_policy_type(policy_name):
if policy_name and policy_name in policies:
@@ -144,6 +180,12 @@ def build_caddyfile(apps, auth_policies, routes, tls_data=None):
lines.append("")
return
if certificate_type == "certificate_file":
certificate_path = os.path.join(NODE_CERTIFICATES_DIR, dns_credential)
lines.append(f" tls {certificate_path}.crt {certificate_path}.key")
lines.append("")
return
lines.append(" tls {")
if certificate_type == "dns_challenge":
dns_credential_data = tls_data["dns_credentials"][dns_credential]
@@ -299,6 +341,15 @@ def build_caddyfile(apps, auth_policies, routes, tls_data=None):
for (certificate_type, dns_credential, certificate_fallback), group_hosts in group_hosts_by_tls(hosts, tls_data):
emit_site_block(app, group_hosts, certificate_type, dns_credential, certificate_fallback)
certificate_only_hosts = get_certificate_only_hosts(apps, tls_data)
for (certificate_type, dns_credential, certificate_fallback), group_hosts in group_hosts_by_tls(certificate_only_hosts, tls_data):
# Keeps the certificate managed for cluster workers; the application is not published here
lines.append(f"{', '.join(_safe_value(host) for host in group_hosts)} {{")
emit_tls(certificate_type, dns_credential, certificate_fallback)
lines.append(" respond 404")
lines.append("}")
lines.append("")
return "\n".join(lines)
@@ -306,19 +357,21 @@ def build_tls_state(apps, tls_data):
"""Map each host to a fingerprint of the certificate settings used in the generated Caddyfile."""
tls_data = tls_data or {}
tls_state = {}
for app in apps:
if not app.get("hosts") or not app.get("upstream"):
hosts = [host for app in apps if app.get("upstream") for host in app.get("hosts", [])]
hosts += get_certificate_only_hosts(apps, tls_data)
for host in hosts:
host_tls = get_host_tls(host, tls_data)
if host_tls is None:
continue
for host in app["hosts"]:
certificate_type, dns_credential, certificate_fallback = get_host_tls(host, tls_data)
credential_hash = ""
if dns_credential:
credential_data = json.dumps(tls_data["dns_credentials"][dns_credential], sort_keys=True)
credential_hash = hashlib.sha256(credential_data.encode()).hexdigest()
certificate_generation = tls_data.get("hosts", {}).get(host.lower(), {}).get("certificate_generation", 0)
tls_state[host.lower()] = [
certificate_type, dns_credential or "", credential_hash, certificate_fallback, certificate_generation
]
certificate_type, certificate_reference, certificate_fallback = host_tls
credential_hash = ""
if certificate_type == "dns_challenge":
credential_data = json.dumps(tls_data["dns_credentials"][certificate_reference], sort_keys=True)
credential_hash = hashlib.sha256(credential_data.encode()).hexdigest()
certificate_generation = tls_data.get("hosts", {}).get(host.lower(), {}).get("certificate_generation", 0)
tls_state[host.lower()] = [
certificate_type, certificate_reference or "", credential_hash, certificate_fallback, certificate_generation
]
return tls_state
@@ -363,9 +416,22 @@ def sync_tls_state():
restart_required = False
if applied_state is not None:
for host, host_state in pending_state.items():
if applied_state.get(host) in (None, host_state):
previous_host_state = applied_state.get(host)
if previous_host_state == host_state or "/" in host or host in ("", ".", ".."):
continue
if "/" in host or host in ("", ".", ".."):
# A new host normally has nothing cached, unless a fallback certificate was left by an earlier use
# of the same hostname (e.g. removed from one application and added to another)
if previous_host_state is None and not os.path.isdir(
os.path.join(CERTIFICATES_DIR, INTERNAL_ISSUER_DIR_NAME, host)
):
continue
if CLUSTER_NODE:
# Certificates received from the primary server replace cached ones only after a restart
if host_state[0] == "certificate_file":
fallback_certificate_dir = os.path.join(CERTIFICATES_DIR, INTERNAL_ISSUER_DIR_NAME, host)
if os.path.isdir(fallback_certificate_dir):
shutil.rmtree(fallback_certificate_dir)
restart_required = True
continue
if host_state[0] not in ACME_CERTIFICATE_TYPES:
# A cached ACME certificate would keep being served instead of the self-signed one
@@ -386,6 +452,90 @@ def sync_tls_state():
print("restart")
def reset_fallback_certificates():
"""
Remove fallback certificates of ACME hosts before Caddy starts, so the ACME certificate is requested again
on every start instead of only on the next renewal. If the request fails, the fallback is issued again.
"""
pending_state = _read_json(TLS_STATE_PENDING_PATH) or {}
for host, host_state in pending_state.items():
if host_state[0] not in ACME_CERTIFICATE_TYPES or "/" in host or host in ("", ".", ".."):
continue
fallback_certificate_dir = os.path.join(CERTIFICATES_DIR, INTERNAL_ISSUER_DIR_NAME, host)
if os.path.isdir(fallback_certificate_dir):
shutil.rmtree(fallback_certificate_dir)
print(f"Removed fallback certificate for {host}", file=sys.stderr)
def find_acme_certificate(host):
"""Return (certificate_path, key_path) of the newest ACME certificate stored by Caddy for a host."""
candidates = []
if os.path.isdir(CERTIFICATES_DIR):
for issuer_dir_name in os.listdir(CERTIFICATES_DIR):
if issuer_dir_name == INTERNAL_ISSUER_DIR_NAME:
continue
certificate_path = os.path.join(CERTIFICATES_DIR, issuer_dir_name, host, f"{host}.crt")
key_path = os.path.join(CERTIFICATES_DIR, issuer_dir_name, host, f"{host}.key")
if os.path.isfile(certificate_path) and os.path.isfile(key_path):
candidates.append((os.path.getmtime(certificate_path), certificate_path, key_path))
if not candidates:
return None, None
newest = max(candidates)
return newest[1], newest[2]
def _copy_if_changed(source_path, destination_path):
with open(source_path, "r", encoding="utf-8") as source_file:
content = source_file.read()
if _read_text(destination_path) == content:
return False
temp_path = f"{destination_path}.tmp"
with open(temp_path, "w", encoding="utf-8") as destination_file:
destination_file.write(content)
os.chmod(temp_path, 0o600)
os.replace(temp_path, destination_path)
return True
def _read_text(filepath):
try:
with open(filepath, "r", encoding="utf-8") as text_file:
return text_file.read()
except OSError:
return None
def export_certificates():
"""
Copy the ACME certificates of hosts served by cluster workers to CERTIFICATE_EXPORT_DIR, where Django reads
them to distribute to the workers. Fallback certificates from the internal CA are never exported.
"""
if CLUSTER_NODE or not os.path.isdir(CERTIFICATE_EXPORT_DIR):
return
tls_data = load_json("tls.json") or {}
export_hosts = {
host for host, host_tls in tls_data.get("hosts", {}).items()
if host_tls.get("export_certificate") and "/" not in host and host not in ("", ".", "..")
}
for host in sorted(export_hosts):
certificate_path, key_path = find_acme_certificate(host)
if not certificate_path:
continue
host_export_dir = os.path.join(CERTIFICATE_EXPORT_DIR, host)
os.makedirs(host_export_dir, exist_ok=True)
key_changed = _copy_if_changed(key_path, os.path.join(host_export_dir, "certificate.key"))
certificate_changed = _copy_if_changed(certificate_path, os.path.join(host_export_dir, "certificate.crt"))
if certificate_changed or key_changed:
print(f"Exported certificate for {host}")
for host in os.listdir(CERTIFICATE_EXPORT_DIR):
host_export_dir = os.path.join(CERTIFICATE_EXPORT_DIR, host)
if host not in export_hosts and os.path.isdir(host_export_dir):
shutil.rmtree(host_export_dir)
print(f"Removed exported certificate for {host}")
def main():
apps = collect_all_applications()
auth_policies = load_json("auth_policies.json")
@@ -403,5 +553,9 @@ def main():
if __name__ == "__main__":
if "--sync-tls-state" in sys.argv:
sync_tls_state()
elif "--export-certificates" in sys.argv:
export_certificates()
elif "--reset-fallback-certificates" in sys.argv:
reset_fallback_certificates()
else:
main()