179 lines
7.4 KiB
Python
179 lines
7.4 KiB
Python
import copy
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
|
|
import yaml
|
|
|
|
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
CHARTS = os.path.join(REPO, ".rmk-charts")
|
|
OUT = os.path.join(REPO, "rmk", "infrastructure")
|
|
WORK = os.path.join(REPO, ".rmk-render", "work")
|
|
|
|
COMPONENTS = {
|
|
# component: (chart tgz, overlay patch file, [extra plain yaml files])
|
|
"camunda": ("camunda-contour-11.0.14.tgz", "camunda.yaml",
|
|
["keycloak-krb5.yaml", "uralkali-ca.yaml", "ldap-debug/pod.yaml"]),
|
|
"istio-base": ("istio-base-contour-1.24.0.tgz", None, []),
|
|
"istio-config": ("istio-config-contour-0.1.0.tgz", "istio-config.yaml",
|
|
["minio-serviceentry.yaml", "zitadel-jwks-serviceentry.yaml"]),
|
|
"istio-gateway": ("istio-gateway-contour-1.24.0.tgz", "istio-gateway.yaml", []),
|
|
"istio-pilot": ("istiod-contour-1.24.0.tgz", "istio-pilot.yaml", []),
|
|
"kafka": ("kafka-contour-0.1.15.tgz", "kafka.yaml", ["kafka-scram-users-job.yaml"]),
|
|
"rabbitmq": ("rabbitmq-contour-15.2.4.tgz", "rabbitmq.yaml", []),
|
|
"superset": ("superset-prod-0.13.3.tgz", "superset.yaml", []),
|
|
"trino": ("trino-prod-0.33.0.tgz", "trino.yaml", []),
|
|
"vault": ("vault-contour-0.2.3.tgz", "vault.yaml", []),
|
|
"zitadel": ("idp-contour-4.12.13.tgz", "zitadel.yaml", ["uralkali-ca.yaml"]),
|
|
}
|
|
|
|
NAMESPACE_PATCH = {"superset": "superset-namespace.yaml", "trino": "trino-namespace.yaml"}
|
|
|
|
|
|
def load(p):
|
|
with open(p, encoding="utf-8") as f:
|
|
return yaml.safe_load(f)
|
|
|
|
|
|
def sm_merge(base, overlay):
|
|
"""Approximate kustomize strategic merge: dicts recursive, lists of dicts
|
|
merged by 'name', everything else replaced."""
|
|
if isinstance(base, dict) and isinstance(overlay, dict):
|
|
out = copy.deepcopy(base)
|
|
for k, v in overlay.items():
|
|
out[k] = sm_merge(out[k], v) if k in out else copy.deepcopy(v)
|
|
return out
|
|
if isinstance(base, list) and isinstance(overlay, list):
|
|
if all(isinstance(i, dict) and "name" in i for i in base + overlay) and base and overlay:
|
|
out = copy.deepcopy(base)
|
|
idx = {i["name"]: n for n, i in enumerate(out)}
|
|
for item in overlay:
|
|
if item["name"] in idx:
|
|
out[idx[item["name"]]] = sm_merge(out[idx[item["name"]]], item)
|
|
else:
|
|
out.append(copy.deepcopy(item))
|
|
return out
|
|
return copy.deepcopy(overlay)
|
|
return copy.deepcopy(overlay)
|
|
|
|
|
|
def run(cmd, **kw):
|
|
r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", **kw)
|
|
if r.returncode != 0:
|
|
raise RuntimeError(f"FAILED {' '.join(cmd)}\n{r.stdout}\n{r.stderr}")
|
|
return r.stdout
|
|
|
|
|
|
def write_docs(yaml_text, outdir, prefix_note=""):
|
|
os.makedirs(outdir, exist_ok=True)
|
|
written = []
|
|
seen = {}
|
|
for doc in yaml.safe_load_all(yaml_text):
|
|
if not doc or not isinstance(doc, dict) or "kind" not in doc:
|
|
continue
|
|
kind = doc["kind"].lower()
|
|
name = doc.get("metadata", {}).get("name", "unnamed")
|
|
fname = f"{kind}-{name}.yaml"
|
|
fname = re.sub(r"[^A-Za-z0-9_.-]", "-", fname)
|
|
if fname in seen:
|
|
ns = doc.get("metadata", {}).get("namespace")
|
|
if ns:
|
|
fname = f"{kind}-{ns}-{name}.yaml"
|
|
fname = re.sub(r"[^A-Za-z0-9_.-]", "-", fname)
|
|
if fname in seen:
|
|
seen[fname] += 1
|
|
fname = fname.replace(".yaml", f"-{seen[fname]}.yaml")
|
|
seen[fname] = seen.get(fname, 0) + 1
|
|
with open(os.path.join(outdir, fname), "w", encoding="utf-8", newline="\n") as f:
|
|
f.write(yaml.safe_dump(doc, allow_unicode=True, sort_keys=False, width=4096))
|
|
written.append(fname)
|
|
return written
|
|
|
|
|
|
def main():
|
|
shutil.rmtree(WORK, ignore_errors=True)
|
|
os.makedirs(WORK, exist_ok=True)
|
|
summary = {}
|
|
for comp, (tgz, patch_file, extras) in COMPONENTS.items():
|
|
cdir = os.path.join(REPO, "infrastructure", comp)
|
|
hr = load(os.path.join(cdir, "base", "helmrelease.yaml"))
|
|
overlay = None
|
|
if patch_file:
|
|
overlay = load(os.path.join(cdir, "uralkal", patch_file))
|
|
hr = sm_merge(hr, overlay)
|
|
spec = hr["spec"]
|
|
name = spec.get("releaseName") or hr["metadata"]["name"]
|
|
ns = hr["metadata"]["namespace"]
|
|
values = spec.get("values", {})
|
|
wdir = os.path.join(WORK, comp)
|
|
os.makedirs(wdir, exist_ok=True)
|
|
vfile = os.path.join(wdir, "values.yaml")
|
|
with open(vfile, "w", encoding="utf-8", newline="\n") as f:
|
|
yaml.safe_dump(values, f, allow_unicode=True, sort_keys=False, width=4096)
|
|
|
|
chart = os.path.join(CHARTS, tgz)
|
|
rendered = run(["helm", "template", name, chart, "-n", ns,
|
|
"-f", vfile, "--include-crds", "--kube-version", "1.30.0"])
|
|
|
|
# apply postRenderers (JSON6902 patches via kubectl kustomize)
|
|
prs = spec.get("postRenderers", [])
|
|
patches = []
|
|
for pr in prs:
|
|
for p in pr.get("kustomize", {}).get("patches", []):
|
|
patches.append({"target": p["target"], "patch": p["patch"]})
|
|
if patches:
|
|
with open(os.path.join(wdir, "rendered.yaml"), "w", encoding="utf-8", newline="\n") as f:
|
|
f.write(rendered)
|
|
kust = {"apiVersion": "kustomize.config.k8s.io/v1beta1",
|
|
"kind": "Kustomization",
|
|
"resources": ["rendered.yaml"],
|
|
"patches": patches}
|
|
with open(os.path.join(wdir, "kustomization.yaml"), "w", encoding="utf-8", newline="\n") as f:
|
|
yaml.safe_dump(kust, f, sort_keys=False)
|
|
rendered = run(["kubectl", "kustomize", wdir])
|
|
|
|
outdir = os.path.join(OUT, comp)
|
|
shutil.rmtree(outdir, ignore_errors=True)
|
|
files = write_docs(rendered, outdir)
|
|
|
|
# base namespace
|
|
nsfile = os.path.join(cdir, "base", "namespace.yaml")
|
|
if os.path.exists(nsfile):
|
|
nsdocs = [d for d in yaml.safe_load_all(open(nsfile, encoding="utf-8")) if d]
|
|
nspatch = NAMESPACE_PATCH.get(comp)
|
|
if nspatch:
|
|
nsdocs = [sm_merge(d, load(os.path.join(cdir, "uralkal", nspatch)))
|
|
if d.get("kind") == "Namespace" else d for d in nsdocs]
|
|
for d in nsdocs:
|
|
fname = re.sub(r"[^A-Za-z0-9_.-]", "-",
|
|
f"{d['kind'].lower()}-{d['metadata']['name']}.yaml")
|
|
with open(os.path.join(outdir, fname), "w", encoding="utf-8", newline="\n") as f:
|
|
yaml.safe_dump(d, f, allow_unicode=True, sort_keys=False)
|
|
files.append(fname)
|
|
|
|
# extra plain resources from overlay
|
|
for extra in extras:
|
|
src = os.path.join(cdir, "uralkal", extra)
|
|
if not os.path.exists(src):
|
|
continue
|
|
for doc in yaml.safe_load_all(open(src, encoding="utf-8")):
|
|
if not doc:
|
|
continue
|
|
fname = re.sub(r"[^A-Za-z0-9_.-]", "-",
|
|
f"{doc['kind'].lower()}-{doc['metadata']['name']}.yaml")
|
|
with open(os.path.join(outdir, fname), "w", encoding="utf-8", newline="\n") as f:
|
|
yaml.safe_dump(doc, f, allow_unicode=True, sort_keys=False, width=4096)
|
|
files.append(fname)
|
|
|
|
summary[comp] = files
|
|
print(f"[{comp}] {len(files)} files")
|
|
|
|
print("\nDONE")
|
|
return summary
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|