From fdfd615fd9dd9a6c93e42ce459206e36a2e7faf1 Mon Sep 17 00:00:00 2001 From: claude Date: Tue, 27 Oct 2026 10:26:36 +0000 Subject: [PATCH] Add gateway install/status, ingress host routing and delete-app --purge - gateway install/upgrade renders an HA gateway (2 replicas, RollingUpdate, PDB, hostname spread, downward-API namespace, RWX /opt/apps on the platform class); a Helm-managed gateway is recorded and left alone - gateway status shows which apps run on which replica - ingress add-host/remove-host/list: one Ingress per host or wildcard, TLS from a Secret or a cert-manager ClusterIssuer (wildcards require DNS-01), upstream-hash-by $host pinning; hosts stored in the platform ConfigMap - apply skips the per-app Ingress when routed hosts already cover the app in the gateway's namespace and no OAuth is used; per-app Ingresses also pin by host - status, logs and binary updates reach every gateway replica - delete-app --purge [--drop-database]; Postgres drops only databases whose owner comment matches; apply records database_engine for later cleanup --- README.md | 22 ++ cmd/zero-scale-ctl/cli_test.go | 105 ++++++++ cmd/zero-scale-ctl/gateway.go | 372 +++++++++++++++++++++++++++++ cmd/zero-scale-ctl/k8s.go | 1 + cmd/zero-scale-ctl/lifecycle.go | 155 ++++++++++++ cmd/zero-scale-ctl/main.go | 87 ++++--- cmd/zero-scale-ctl/platform.go | 2 +- cmd/zero-scale-ctl/storage.go | 6 +- internal/platform/config.go | 24 +- internal/platform/detect.go | 8 + internal/platform/gateway.go | 330 +++++++++++++++++++++++++ internal/platform/gateway_test.go | 103 ++++++++ internal/platform/platform_test.go | 1 + internal/runner/systemd.go | 2 +- 14 files changed, 1168 insertions(+), 50 deletions(-) create mode 100644 cmd/zero-scale-ctl/gateway.go create mode 100644 cmd/zero-scale-ctl/lifecycle.go create mode 100644 internal/platform/gateway.go create mode 100644 internal/platform/gateway_test.go diff --git a/README.md b/README.md index 55cc881..e4b6091 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,28 @@ zero-scale-ctl install postgres --cluster-only --namespace databases --name pg-m Both commands update the `zero-scale-platform` ConfigMap when they finish. Longhorn needs `open-iscsi` and `nfs-common` on every node; if `longhornctl` is on PATH, the plan runs `longhornctl check preflight` first. +### Deploy the Gateway and Route Hosts +```bash +# HA gateway: 2 replicas, PodDisruptionBudget, spread across nodes, /opt/apps on the platform RWX class. +# A gateway already managed by Helm is detected, recorded and left alone. +zero-scale-ctl gateway install --image registry.example.com/systemd-runner:1.2.0 --yes +zero-scale-ctl gateway status # replicas, volume, which apps run on which replica + +# Route individual hosts or a wildcard to the gateway (each host sticks to one replica via upstream-hash-by) +zero-scale-ctl ingress add-host '*.apps.example.com' --issuer letsencrypt-dns # wildcard needs a DNS-01 issuer +zero-scale-ctl ingress add-host status.example.com --tls-secret status-tls +zero-scale-ctl ingress list +``` +When every hostname of an app is covered by a routed host, `apply` skips the per-app Ingress (unless the app uses +OAuth, which needs its own annotations). + +### Remove an Application +```bash +zero-scale-ctl delete-app fdm # ConfigMap only (previous behaviour) +zero-scale-ctl delete-app fdm --purge # + Ingress, Secrets, host entries, OAuth routes; stops it on every replica +zero-scale-ctl delete-app fdm --purge --drop-database # + drops its database and user +``` + ### Deploy an Application ```bash # Reconcile an app from a simple declarative config file diff --git a/cmd/zero-scale-ctl/cli_test.go b/cmd/zero-scale-ctl/cli_test.go index 2056e16..e1bbcdf 100644 --- a/cmd/zero-scale-ctl/cli_test.go +++ b/cmd/zero-scale-ctl/cli_test.go @@ -160,3 +160,108 @@ func TestInstallPostgresAppliesAndRecords(t *testing.T) { t.Errorf("operator already present, should not be reinstalled:\n%s", got) } } + +const platformCM = `{"data":{"version":"1","storage.blockClass":"longhorn","storage.rwxClass":"longhorn","gateway.namespace":"zero-scale-system","gateway.service":"zero-scale-gateway","ingress.class":"nginx"}}` + +func mutatingCalls(log string) []string { + var out []string + for _, line := range strings.Split(log, "\n") { + if strings.HasPrefix(line, "kubectl ") && !strings.HasPrefix(line, "kubectl get ") { + out = append(out, line) + } + } + return out +} + +func TestGatewayInstallDryRunAndHelmGuard(t *testing.T) { + log := fakeKubectl(t, ` "get configmap zero-scale-platform -n zero-scale-system -o json") echo '`+platformCM+`' ;;`) + if err := runGateway([]string{"install", "--image", "reg/zs:1"}); err != nil { + t.Fatal(err) + } + if m := mutatingCalls(readLog(t, log)); len(m) != 0 { + t.Errorf("dry run changed things: %v", m) + } + + helmDeploy := `{"metadata":{"labels":{"app.kubernetes.io/managed-by":"Helm"}}}` + log = fakeKubectl(t, ` "get configmap zero-scale-platform -n zero-scale-system -o json") echo '`+platformCM+`' ;; + "get deployment zero-scale-gateway -n zero-scale-system -o json") echo '`+helmDeploy+`' ;;`) + if err := runGateway([]string{"install", "--image", "reg/zs:1", "--yes"}); err != nil { + t.Fatal(err) + } + got := readLog(t, log) + if strings.Contains(got, "kind: Deployment") { + t.Error("must not touch a Helm-managed gateway") + } + if !strings.Contains(got, `gateway.managedBy: "Helm"`) { + t.Errorf("Helm gateway not recorded:\n%s", got) + } +} + +func TestIngressAddHost(t *testing.T) { + httpOnly := `{"spec":{"acme":{"solvers":[{"http01":{}}]}}}` + log := fakeKubectl(t, ` "get configmap zero-scale-platform -n zero-scale-system -o json") echo '`+platformCM+`' ;; + "get clusterissuer le-http -o json") echo '`+httpOnly+`' ;;`) + if err := runIngress([]string{"add-host", "*.apps.example.com", "--issuer", "le-http"}); err == nil || !strings.Contains(err.Error(), "DNS-01") { + t.Fatalf("expected DNS-01 refusal, got %v", err) + } + if err := runIngress([]string{"add-host", "--tls-secret", "wildcard-tls", "*.apps.example.com"}); err != nil { + t.Fatal(err) + } + got := readLog(t, log) + for _, want := range []string{ + "name: zero-scale-wildcard-apps-example-com", + "secretName: wildcard-tls", + "ingressClassName: nginx", + `ingress.hosts: "*.apps.example.com"`, + `ingress.tls: "*.apps.example.com=secret:wildcard-tls"`, + } { + if !strings.Contains(got, want) { + t.Errorf("missing %q:\n%s", want, got) + } + } +} + +func TestApplySkipsIngressWhenWildcardCovers(t *testing.T) { + cm := `{"data":{"version":"1","gateway.namespace":"zero-scale-system","ingress.hosts":"*.apps.example.com"}}` + fakeKubectl(t, ` "get configmap zero-scale-platform -n zero-scale-system -o json") echo '`+cm+`' ;;`) + if !hostsCoveredByRoutes([]string{"fdm.apps.example.com"}, "zero-scale-system") { + t.Error("wildcard should cover the app host") + } + if hostsCoveredByRoutes([]string{"fdm.apps.example.com", "fdm.other.com"}, "zero-scale-system") { + t.Error("one uncovered host means a per-app Ingress is needed") + } + if hostsCoveredByRoutes([]string{"fdm.apps.example.com"}, "qa") { + t.Error("routes point at the platform gateway, not another namespace's") + } +} + +func TestDeleteAppPurge(t *testing.T) { + appCM := `{"data":{"host":"fdm.ffxm.cc","hosts":"fdm.ffxm.cc,fleet.example.com","database_engine":"postgres"}}` + cnpg := `{"data":{"version":"1","postgres.operator":"cnpg","postgres.cluster":"cnpg-system/ha-postgres","postgres.rwService":"ha-postgres-rw.cnpg-system.svc.cluster.local:5432"}}` + log := fakeKubectl(t, ` "get configmap zero-scale-app-fdm -n default -o json") echo '`+appCM+`' ;; + "get configmap zero-scale-platform -n zero-scale-system -o json") echo '`+cnpg+`' ;; + "get pods -n default -l app=zero-scale-gateway --field-selector=status.phase=Running -o jsonpath={.items[*].metadata.name}") printf 'gw-a gw-b' ;; + "get pods -n default -l app=zero-scale-gateway --field-selector=status.phase=Running -o jsonpath={.items[0].metadata.name}") printf gw-a ;; + "get pods -n cnpg-system -l cnpg.io/cluster=ha-postgres,cnpg.io/instanceRole=primary "*) printf ha-postgres-1 ;; + "exec gw-"*|"delete "*) exit 0 ;;`) + if err := runDeleteApp([]string{"fdm", "--drop-database"}, "default"); err == nil { + t.Error("--drop-database without --purge must fail") + } + if err := runDeleteApp([]string{"fdm", "--purge", "--drop-database"}, "default"); err != nil { + t.Fatal(err) + } + got := readLog(t, log) + for _, want := range []string{ + "exec gw-a -n default -c systemd-runner -- systemctl stop app-fdm.ffxm.cc.service", + "exec gw-b -n default -c systemd-runner -- systemctl stop app-fdm.ffxm.cc.service", + "rm -f /opt/apps/fleet.example.com", + "DROP DATABASE %I WITH (FORCE)", + "delete ingress zero-scale-fdm -n default", + "delete secret fdm-db-secret -n default", + "delete configmap zero-scale-app-fdm -n default", + } { + if !strings.Contains(got, want) { + t.Errorf("missing %q:\n%s", want, got) + } + } +} diff --git a/cmd/zero-scale-ctl/gateway.go b/cmd/zero-scale-ctl/gateway.go new file mode 100644 index 0000000..9aee821 --- /dev/null +++ b/cmd/zero-scale-ctl/gateway.go @@ -0,0 +1,372 @@ +package main + +import ( + "encoding/json" + "flag" + "fmt" + "os" + "strings" + + "git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/platform" +) + +// GetGatewayPods lists every running gateway pod in namespace. +func GetGatewayPods(namespace string) ([]string, error) { + for _, label := range []string{"app=zero-scale-gateway", "app.kubernetes.io/name=zero-scale-platform"} { + out, err := RunKubectl([]string{"get", "pods", "-n", namespace, "-l", label, + "--field-selector=status.phase=Running", "-o", "jsonpath={.items[*].metadata.name}"}, "") + if pods := strings.Fields(out); err == nil && len(pods) > 0 { + return pods, nil + } + } + _, err := GetGatewayPod(namespace) // same lookup, with the remediation message + return nil, err +} + +// forEachGatewayPod runs fn for every gateway replica, printing an error if there are none. +func forEachGatewayPod(namespace string, fn func(pod string)) { + pods, err := GetGatewayPods(namespace) + if err != nil { + fmt.Fprintf(os.Stderr, "ERROR: %v\n", err) + os.Exit(1) + } + for _, pod := range pods { + fn(pod) + } +} + +// stopAppEverywhere stops an app's unit on every gateway replica. +func stopAppEverywhere(host, namespace string) { + pods, _ := GetGatewayPods(namespace) + for _, pod := range pods { + _, _ = ExecPod(pod, namespace, "systemd-runner", []string{"systemctl", "stop", fmt.Sprintf("app-%s.service", host)}, "") + } +} + +// ---------------------------------------------------------------- gateway + +func runGateway(args []string) error { + if len(args) < 1 { + return fmt.Errorf("usage: zero-scale-ctl gateway install|upgrade|status [options]") + } + switch args[0] { + case "install", "upgrade": + return gatewayInstall(args[0], args[1:]) + case "status": + return gatewayStatus(args[1:]) + } + return fmt.Errorf("unknown gateway command %q", args[0]) +} + +type deployment struct { + Metadata struct { + Labels map[string]string `json:"labels"` + } `json:"metadata"` +} + +func existingGatewayManager(ns string) (string, bool) { + out, err := RunKubectl([]string{"get", "deployment", "zero-scale-gateway", "-n", ns, "-o", "json"}, "") + if err != nil { + return "", false + } + var d deployment + _ = json.Unmarshal([]byte(out), &d) + return d.Metadata.Labels["app.kubernetes.io/managed-by"], true +} + +func gatewayInstall(verb string, args []string) error { + fs := flag.NewFlagSet("gateway "+verb, flag.ExitOnError) + ns := fs.String("namespace", platform.DefaultNamespace, "Namespace for the gateway") + image := fs.String("image", "", "Gateway image (required)") + replicas := fs.Int("replicas", 2, "Gateway replicas") + rwx := fs.String("rwx-class", "", "RWX StorageClass for /opt/apps (default: storage.rwxClass from the platform config)") + size := fs.String("volume-size", "5Gi", "Size of the /opt/apps volume") + idle := fs.String("idle-timeout", "60s", "Default idle time before an app scales to zero") + yes := fs.Bool("yes", false, "Apply (otherwise only print the manifests)") + _ = fs.Parse(args) + + p, err := loadPlatform() + if err != nil { + return err + } + if manager, exists := existingGatewayManager(*ns); exists { + if manager == "Helm" { + fmt.Printf("==> A Helm-managed gateway already runs in '%s'; leaving it alone. Upgrade it with Helm.\n", *ns) + if !*yes { + return nil + } + return updatePlatform(func(c *platform.Config) { + c.Gateway = platform.GatewayConfig{Namespace: *ns, Service: "zero-scale-gateway", ManagedBy: "Helm"} + }) + } + if verb == "install" { + fmt.Printf("==> A gateway already exists in '%s'; this will update it in place.\n", *ns) + } + } else if verb == "upgrade" { + return fmt.Errorf("no gateway in namespace '%s'; use 'zero-scale-ctl gateway install'", *ns) + } + + rwxClass := *rwx + if rwxClass == "" && p != nil { + rwxClass = p.Storage.RWXClass + } + manifest, err := platform.GatewayManifest(platform.GatewayOptions{ + Namespace: *ns, Image: *image, Replicas: *replicas, RWXClass: rwxClass, VolumeSize: *size, IdleTimeout: *idle, + }) + if err != nil { + return err + } + steps := []platform.Step{ + {Title: "Gateway ServiceAccount, RBAC, /opt/apps PVC, Deployment, Service and PodDisruptionBudget", Manifest: manifest}, + {Title: "Wait for the rollout", Command: []string{"kubectl", "-n", *ns, "rollout", "status", "deployment/zero-scale-gateway", "--timeout=5m"}}, + } + if *replicas < 2 { + fmt.Println("⚠️ fewer than 2 replicas: the gateway is a single point of failure") + } + if err := ensureNamespaceStep(*ns, *yes); err != nil { + return err + } + if err := executePlan(steps, *yes); err != nil || !*yes { + return err + } + return updatePlatform(func(c *platform.Config) { + c.Gateway = platform.GatewayConfig{Namespace: *ns, Service: "zero-scale-gateway", ManagedBy: "zero-scale-ctl"} + }) +} + +func ensureNamespaceStep(ns string, apply bool) error { + if !apply { + return nil + } + return ensureNamespace(ns) +} + +func gatewayStatus(args []string) error { + fs := flag.NewFlagSet("gateway status", flag.ExitOnError) + ns := fs.String("namespace", "", "Gateway namespace (default: from the platform config)") + _ = fs.Parse(args) + namespace := *ns + if namespace == "" { + if p, _ := loadPlatform(); p != nil && p.Gateway.Namespace != "" { + namespace = p.Gateway.Namespace + } else { + namespace = platform.DefaultNamespace + } + } + out, err := RunKubectl([]string{"get", "deployment,pvc,pdb", "-n", namespace, "-l", "app=zero-scale-gateway"}, "") + if err != nil { + return err + } + fmt.Print(out) + pods, err := GetGatewayPods(namespace) + if err != nil { + return err + } + fmt.Println("\n==> Running apps per replica") + for _, pod := range pods { + units, _ := ExecPod(pod, namespace, "systemd-runner", []string{"systemctl", "list-units", "--type=service", + "--state=running", "--no-legend", "--no-pager", "app-*.service"}, "") + var apps []string + for _, line := range strings.Split(units, "\n") { + if f := strings.Fields(line); len(f) > 0 { + apps = append(apps, strings.TrimSuffix(strings.TrimPrefix(f[0], "app-"), ".service")) + } + } + if len(apps) == 0 { + apps = []string{"(none, all scaled to zero)"} + } + fmt.Printf(" %s: %s\n", pod, strings.Join(apps, ", ")) + } + return nil +} + +// ---------------------------------------------------------------- ingress routes + +func runIngress(args []string) error { + if len(args) < 1 { + return fmt.Errorf("usage: zero-scale-ctl ingress add-host|remove-host|list ...") + } + switch args[0] { + case "add-host": + return ingressAddHost(args[1:]) + case "remove-host": + return ingressRemoveHost(args[1:]) + case "list": + return ingressList() + } + return fmt.Errorf("unknown ingress command %q", args[0]) +} + +func gatewayTarget(p *platform.Config) (ns, svc string, err error) { + if p == nil || p.Gateway.Namespace == "" { + return "", "", fmt.Errorf("no gateway recorded in the platform config; run 'zero-scale-ctl gateway install' or 'zero-scale-ctl init'") + } + svc = p.Gateway.Service + if svc == "" { + svc = "zero-scale-gateway" + } + return p.Gateway.Namespace, svc, nil +} + +// splitHostArgs lets value flags (--tls-secret S, --issuer I) come before or after the host. +func splitHostArgs(args []string) (host string, rest []string) { + for i := 0; i < len(args); i++ { + a := args[i] + if strings.HasPrefix(a, "-") { + rest = append(rest, a) + if !strings.Contains(a, "=") && i+1 < len(args) { + rest = append(rest, args[i+1]) + i++ + } + continue + } + if host == "" { + host = a + } else { + rest = append(rest, a) + } + } + return host, rest +} + +func ingressAddHost(args []string) error { + host, rest := splitHostArgs(args) + fs := flag.NewFlagSet("ingress add-host", flag.ExitOnError) + secret := fs.String("tls-secret", "", "Existing TLS Secret (in the gateway namespace) for this host") + issuer := fs.String("issuer", "", "cert-manager ClusterIssuer to request a certificate from") + _ = fs.Parse(rest) + host = strings.ToLower(strings.TrimSpace(host)) + if host == "" { + return fmt.Errorf("usage: zero-scale-ctl ingress add-host [--tls-secret S | --issuer I]") + } + if err := platform.ValidateHost(host); err != nil { + return err + } + if *secret != "" && *issuer != "" { + return fmt.Errorf("use either --tls-secret or --issuer, not both") + } + tls := "" + switch { + case *secret != "": + tls = "secret:" + *secret + case *issuer != "": + out, err := RunKubectl([]string{"get", "clusterissuer", *issuer, "-o", "json"}, "") + if err != nil { + return fmt.Errorf("ClusterIssuer %q not found: %w", *issuer, err) + } + if strings.HasPrefix(host, "*.") { + ok, err := platform.IssuerSupportsWildcard([]byte(out)) + if err != nil { + return err + } + if !ok { + return fmt.Errorf("ClusterIssuer %q is ACME without a DNS-01 solver; wildcard certificates need DNS-01", *issuer) + } + } + tls = "issuer:" + *issuer + } + + p, err := loadPlatform() + if err != nil { + return err + } + ns, svc, err := gatewayTarget(p) + if err != nil { + return err + } + manifest, err := platform.RouteManifest(host, ns, svc, resolveIngressClass(), tls) + if err != nil { + return err + } + if err := ApplyYAML(manifest, ns); err != nil { + return err + } + fmt.Printf("✅ %s routes to %s/%s (Ingress %s)\n", host, ns, svc, platform.RouteName(host)) + return updatePlatform(func(c *platform.Config) { + if !hasString(c.Ingress.Hosts, host) { + c.Ingress.Hosts = append(c.Ingress.Hosts, host) + } + if c.Ingress.TLS == nil { + c.Ingress.TLS = map[string]string{} + } + if tls == "" { + delete(c.Ingress.TLS, host) + } else { + c.Ingress.TLS[host] = tls + } + }) +} + +func ingressRemoveHost(args []string) error { + if len(args) < 1 { + return fmt.Errorf("usage: zero-scale-ctl ingress remove-host ") + } + host := strings.ToLower(strings.TrimSpace(args[0])) + p, err := loadPlatform() + if err != nil { + return err + } + ns, _, err := gatewayTarget(p) + if err != nil { + return err + } + if _, err := RunKubectl([]string{"delete", "ingress", platform.RouteName(host), "-n", ns, "--ignore-not-found"}, ""); err != nil { + return err + } + fmt.Printf("✅ Removed route for %s\n", host) + return updatePlatform(func(c *platform.Config) { + var keep []string + for _, h := range c.Ingress.Hosts { + if h != host { + keep = append(keep, h) + } + } + c.Ingress.Hosts = keep + delete(c.Ingress.TLS, host) + }) +} + +func ingressList() error { + p, err := loadPlatform() + if err != nil { + return err + } + if p == nil || len(p.Ingress.Hosts) == 0 { + fmt.Println("No hosts routed to the gateway. Add one with 'zero-scale-ctl ingress add-host '.") + return nil + } + ns, svc, _ := gatewayTarget(p) + fmt.Printf("==> Hosts routed to %s/%s\n", ns, svc) + for _, h := range p.Ingress.Hosts { + tls := p.Ingress.TLS[h] + if tls == "" { + tls = "no TLS at the ingress" + } + fmt.Printf(" %-40s %s\n", h, tls) + } + return nil +} + +func hasString(list []string, s string) bool { + for _, v := range list { + if v == s { + return true + } + } + return false +} + +// hostsCoveredByRoutes reports whether every host is served by a routed platform ingress host +// in the same namespace as this app's gateway. +func hostsCoveredByRoutes(hosts []string, namespace string) bool { + p, err := loadPlatform() + if err != nil || p == nil || len(p.Ingress.Hosts) == 0 || p.Gateway.Namespace != namespace { + return false + } + for _, h := range hosts { + if !platform.HostCovered(h, p.Ingress.Hosts) { + return false + } + } + return true +} diff --git a/cmd/zero-scale-ctl/k8s.go b/cmd/zero-scale-ctl/k8s.go index f1c9521..fb12bf4 100644 --- a/cmd/zero-scale-ctl/k8s.go +++ b/cmd/zero-scale-ctl/k8s.go @@ -162,6 +162,7 @@ metadata: b.WriteString(` annotations: nginx.ingress.kubernetes.io/ssl-redirect: "false" nginx.ingress.kubernetes.io/proxy-body-size: "50m" + nginx.ingress.kubernetes.io/upstream-hash-by: "$host" `) if oauthSetupName != "" { proxySvc := OAuthProxyServiceName(oauthSetupName) diff --git a/cmd/zero-scale-ctl/lifecycle.go b/cmd/zero-scale-ctl/lifecycle.go new file mode 100644 index 0000000..4eee146 --- /dev/null +++ b/cmd/zero-scale-ctl/lifecycle.go @@ -0,0 +1,155 @@ +package main + +import ( + "flag" + "fmt" + "strings" + + "git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/appname" + "git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/platform" +) + +func runDeleteApp(args []string, namespace string) error { + name, rest := splitHostArgs(args) + fs := flag.NewFlagSet("delete-app", flag.ExitOnError) + purge := fs.Bool("purge", false, "Also remove the Ingress, Secrets, DB config, host symlinks and OAuth routes, and stop the app on every replica") + dropDB := fs.Bool("drop-database", false, "With --purge: drop the app's database and user (Postgres only drops databases this tool created)") + _ = fs.Parse(rest) + if name == "" { + return fmt.Errorf("usage: zero-scale-ctl delete-app [--purge [--drop-database]]") + } + if *dropDB && !*purge { + return fmt.Errorf("--drop-database requires --purge") + } + + cmName := name + if !strings.HasPrefix(cmName, "zero-scale-app-") { + cmName = appname.ConfigMapName(name) + } + data, cmErr := GetConfigMapData(cmName, namespace) + appName := strings.TrimPrefix(cmName, "zero-scale-app-") + + if !*purge { + if cmErr != nil { + return fmt.Errorf("ConfigMap '%s' not found in namespace '%s'", cmName, namespace) + } + fmt.Printf("==> Deleting ConfigMap '%s' in namespace '%s'...\n", cmName, namespace) + if _, err := RunKubectl([]string{"delete", "configmap", cmName, "-n", namespace}, ""); err != nil { + return err + } + fmt.Println("Done. The Ingress, Secrets, database and binary were kept; use --purge to remove them.") + return nil + } + + hosts := appname.Hosts(data) + if len(hosts) == 0 && strings.Contains(name, ".") { + hosts = []string{strings.ToLower(name)} + } + fmt.Printf("==> Purging app '%s' (hosts %v) in namespace '%s'\n", appName, hosts, namespace) + del := func(kind, obj string) { + if _, err := RunKubectl([]string{"delete", kind, obj, "-n", namespace, "--ignore-not-found"}, ""); err != nil { + fmt.Printf("⚠️ deleting %s/%s: %v\n", kind, obj, err) + } else { + fmt.Printf("--> Deleted %s/%s\n", kind, obj) + } + } + + if len(hosts) > 0 { + stopAppEverywhere(hosts[0], namespace) + fmt.Printf("--> Stopped app-%s on every gateway replica\n", hosts[0]) + if pod, err := GetGatewayPod(namespace); err == nil { + for _, h := range hosts { + if err := platform.ValidateHost(h); err != nil { + continue + } + _, _ = ExecPod(pod, namespace, "systemd-runner", []string{"rm", "-f", "/opt/apps/" + h, "/opt/apps/" + h + ".type"}, "") + } + fmt.Println("--> Removed host entries from /opt/apps (the binary itself is kept; other apps may share it)") + } + } + + if *dropDB { + if err := dropAppDatabase(appName, hosts, data, namespace); err != nil { + return err + } + } + + if setup := data["oauth-setup"]; setup != "" && len(hosts) > 0 { + del("ingress", fmt.Sprintf("zero-scale-%s-oauth2", strings.Split(hosts[0], ".")[0])) + removeOAuthCallbacks(setup, hosts, namespace) + } + del("ingress", "zero-scale-"+appName) + del("secret", appName+"-db-secret") + del("configmap", appName+"-db-config") + del("configmap", cmName) + fmt.Println("✅ Purged.") + return nil +} + +func removeOAuthCallbacks(setup string, hosts []string, namespace string) { + cmName := OAuthSetupConfigMapName(setup) + cm, err := GetConfigMapData(cmName, namespace) + if err != nil { + return + } + drop := map[string]bool{} + for _, h := range hosts { + drop[fmt.Sprintf("https://%s/oauth2/callback", h)] = true + } + var keep []string + for _, u := range strings.Split(cm["redirect_uris"], ",") { + if u = strings.TrimSpace(u); u != "" && !drop[u] { + keep = append(keep, u) + } + } + cm["redirect_uris"] = strings.Join(keep, ",") + if err := CreateOrUpdateConfigMap(cmName, namespace, cm, map[string]string{"app.kubernetes.io/part-of": "zero-scale-platform"}); err == nil { + fmt.Printf("--> Removed %d redirect URI(s) from OAuth setup '%s' (also remove them at the provider)\n", len(hosts), setup) + } +} + +func dropAppDatabase(appName string, hosts []string, data map[string]string, namespace string) error { + if len(hosts) == 0 { + return fmt.Errorf("cannot drop the database: the app's hosts are unknown (ConfigMap missing)") + } + engine := data["database_engine"] + if engine == "" { + // Apps applied before database_engine was recorded: infer from the port. + if dbCM, err := GetConfigMapData(appName+"-db-config", namespace); err == nil { + engine = map[string]string{"5432": "postgres", "3306": "mysql"}[dbCM["DATABASE_PORT"]] + } + } + if engine == "" { + fmt.Println("--> No database recorded for this app; nothing to drop.") + return nil + } + if engine == "postgresql" { + engine = "postgres" + } + app := &AppConfig{Hostnames: hosts} + target, op, err := resolveDBTarget(engine, namespace) + if err != nil { + return err + } + switch engine { + case "postgres": + sql, err := platform.PostgresDropSQL(app.DBName(), app.DBUser(), app.Owner(namespace)) + if err != nil { + return err + } + if err := runPostgres(target, op, sql); err != nil { + return fmt.Errorf("dropping Postgres database: %w", err) + } + fmt.Printf("--> Dropped Postgres database %s and role %s on %s if this tool created them\n", app.DBName(), app.DBUser(), target.Ref()) + case "mysql": + sql, err := platform.MySQLDropSQL(app.DBName(), app.DBUser()) + if err != nil { + return err + } + if err := runMySQL(target, op, sql); err != nil { + return fmt.Errorf("dropping MySQL database: %w", err) + } + fmt.Printf("--> Dropped MySQL database %s and user %s on %s\n", app.DBName(), app.DBUser(), target.Ref()) + } + return nil +} diff --git a/cmd/zero-scale-ctl/main.go b/cmd/zero-scale-ctl/main.go index fe4df5f..8b25489 100644 --- a/cmd/zero-scale-ctl/main.go +++ b/cmd/zero-scale-ctl/main.go @@ -26,6 +26,13 @@ Platform setup: install postgres Install CloudNativePG and a 3-instance cluster on the HA storage class [--name ha-postgres] [--namespace cnpg-system] [--instances 3] [--size 10Gi] [--storage-class X] [--cluster-only] [--version V] + gateway install Deploy an HA gateway (replicas, PDB, spread, RBAC, RWX /opt/apps) [--image I] [--replicas 2] + [--namespace zero-scale-system] [--rwx-class X] [--idle-timeout 60s] [--yes] + gateway upgrade Same as install, for an existing zero-scale-ctl managed gateway + gateway status Replicas, volume and which apps are running on which replica + ingress add-host Route a host or wildcard to the gateway: [--tls-secret S | --issuer I] + ingress remove-host + ingress list Commands: apply Reconcile an app or redirect from a simple 10-line declarative config file @@ -33,7 +40,8 @@ Commands: status Inspect systemd service status of an app logs Fetch journalctl logs for an app unit list-apps List all registered zero-scale applications - delete-app Delete an application ConfigMap + delete-app Delete an application ConfigMap; --purge removes its Ingress, Secrets, host entries + and OAuth routes and stops it everywhere; --drop-database also drops its database upload-binary Upload a local binary directly to platform storage provision-db Provision schema and credentials on shared database operator @@ -101,17 +109,14 @@ func main() { os.Exit(1) } host := resolveAppHost(os.Args[2], namespace) - pod, err := GetGatewayPod(namespace) - if err != nil { - fmt.Fprintf(os.Stderr, "ERROR: %v\n", err) - os.Exit(1) - } unit := fmt.Sprintf("app-%s", host) - fmt.Printf("==> Checking status of '%s' in pod '%s' (%s)...\n", unit, pod, namespace) - statusCmd := exec.Command("kubectl", "exec", "-n", namespace, pod, "-c", "systemd-runner", "--", "systemctl", "status", unit) - statusCmd.Stdout = os.Stdout - statusCmd.Stderr = os.Stderr - _ = statusCmd.Run() + forEachGatewayPod(namespace, func(pod string) { + fmt.Printf("==> '%s' in pod '%s' (%s)\n", unit, pod, namespace) + statusCmd := exec.Command("kubectl", "exec", "-n", namespace, pod, "-c", "systemd-runner", "--", "systemctl", "status", "--no-pager", unit) + statusCmd.Stdout = os.Stdout + statusCmd.Stderr = os.Stderr + _ = statusCmd.Run() + }) case "logs": if len(os.Args) < 3 { @@ -123,17 +128,14 @@ func main() { if len(os.Args) >= 5 && (os.Args[3] == "-n" || os.Args[3] == "--lines") { lines = os.Args[4] } - pod, err := GetGatewayPod(namespace) - if err != nil { - fmt.Fprintf(os.Stderr, "ERROR: %v\n", err) - os.Exit(1) - } unit := fmt.Sprintf("app-%s", host) - fmt.Printf("==> Fetching last %s journal logs for '%s' in pod '%s'...\n", lines, unit, pod) - logCmd := exec.Command("kubectl", "exec", "-n", namespace, pod, "-c", "systemd-runner", "--", "journalctl", "-u", unit, "--no-pager", "-n", lines) - logCmd.Stdout = os.Stdout - logCmd.Stderr = os.Stderr - _ = logCmd.Run() + forEachGatewayPod(namespace, func(pod string) { + fmt.Printf("==> Last %s journal lines for '%s' in pod '%s'\n", lines, unit, pod) + logCmd := exec.Command("kubectl", "exec", "-n", namespace, pod, "-c", "systemd-runner", "--", "journalctl", "-u", unit, "--no-pager", "-n", lines) + logCmd.Stdout = os.Stdout + logCmd.Stderr = os.Stderr + _ = logCmd.Run() + }) case "list-apps": fmt.Printf("==> Configured Zero-Scale Applications in namespace '%s':\n", namespace) @@ -144,22 +146,10 @@ func main() { _ = listCmd.Run() case "delete-app": - if len(os.Args) < 3 { - fmt.Fprintln(os.Stderr, "Usage: zero-scale-ctl delete-app ") - os.Exit(1) - } - name := os.Args[2] - cmName := name - if !strings.HasPrefix(cmName, "zero-scale-app-") { - cmName = appname.ConfigMapName(name) - } - fmt.Printf("==> Deleting ConfigMap '%s' in namespace '%s'...\n", cmName, namespace) - _, err := RunKubectl([]string{"delete", "configmap", cmName, "-n", namespace}, "") - if err != nil { + if err := runDeleteApp(os.Args[2:], namespace); err != nil { fmt.Fprintf(os.Stderr, "ERROR: %v\n", err) os.Exit(1) } - fmt.Println("Done.") case "upload-binary": upFlags := flag.NewFlagSet("upload-binary", flag.ExitOnError) @@ -255,6 +245,18 @@ func main() { os.Exit(1) } + case "gateway": + if err := runGateway(os.Args[2:]); err != nil { + fmt.Fprintf(os.Stderr, "ERROR: %v\n", err) + os.Exit(1) + } + + case "ingress": + if err := runIngress(os.Args[2:]); err != nil { + fmt.Fprintf(os.Stderr, "ERROR: %v\n", err) + os.Exit(1) + } + case "install": if err := runInstall(os.Args[2:]); err != nil { fmt.Fprintf(os.Stderr, "ERROR: %v\n", err) @@ -363,6 +365,7 @@ func handleApply(configPath, expandPath, namespace string) error { cmData["idle-timeout"] = app.IdleTimeout } if app.Database != nil { + cmData["database_engine"] = strings.ToLower(app.Database.Engine) cmData["database_configmap"] = app.ConfigMapName() cmData["database_secret"] = app.SecretName() } else if len(app.Secrets) > 0 { @@ -455,12 +458,18 @@ func handleApply(configPath, expandPath, namespace string) error { } } - // Step D: Configure public Ingress for all hostnames - fmt.Printf("--> Step 4: Configuring public Ingress for %v...\n", app.Hostnames) + // Step D: Configure public Ingress, unless the gateway's routed hosts (ingress add-host, + // e.g. a wildcard) already cover every hostname and no OAuth annotations are needed. ingressName := fmt.Sprintf("zero-scale-%s", app.AppName()) - err = ApplyIngress(ingressName, namespace, "zero-scale-gateway", 80, app.Hostnames, oauthSetup) - if err != nil { - return fmt.Errorf("failed to apply ingress: %w", err) + if covered := hostsCoveredByRoutes(app.Hostnames, namespace); covered && oauthSetup == "" { + fmt.Printf("--> Step 4: %v already routed to the gateway by platform ingress hosts; no per-app Ingress needed.\n", app.Hostnames) + _, _ = RunKubectl([]string{"delete", "ingress", ingressName, "-n", namespace, "--ignore-not-found"}, "") + } else { + fmt.Printf("--> Step 4: Configuring public Ingress for %v...\n", app.Hostnames) + err = ApplyIngress(ingressName, namespace, "zero-scale-gateway", 80, app.Hostnames, oauthSetup) + if err != nil { + return fmt.Errorf("failed to apply ingress: %w", err) + } } // Step E: Optionally write out expanded single-file Kubernetes manifest diff --git a/cmd/zero-scale-ctl/platform.go b/cmd/zero-scale-ctl/platform.go index 762ae93..b7300bf 100644 --- a/cmd/zero-scale-ctl/platform.go +++ b/cmd/zero-scale-ctl/platform.go @@ -318,7 +318,7 @@ func runInit(args []string) error { } if current != nil { // Keep settings that detection does not own. - cfg.Ingress.Hosts, cfg.Ingress.TLSSecret = current.Ingress.Hosts, current.Ingress.TLSSecret + cfg.Ingress.Hosts, cfg.Ingress.TLS = current.Ingress.Hosts, current.Ingress.TLS if cfg.Gateway.Namespace == "" { cfg.Gateway = current.Gateway } diff --git a/cmd/zero-scale-ctl/storage.go b/cmd/zero-scale-ctl/storage.go index 3dbf0c2..80bf86c 100644 --- a/cmd/zero-scale-ctl/storage.go +++ b/cmd/zero-scale-ctl/storage.go @@ -128,10 +128,8 @@ func DeployBinary(app *AppConfig, namespace string) error { if err != nil { return fmt.Errorf("failed to chmod binary: %w", err) } - // Stop running transient unit if any so next request launches the updated binary - _, _ = ExecPod(pod, namespace, "systemd-runner", []string{ - "systemctl", "stop", fmt.Sprintf("app-%s.service", app.CanonicalHost()), - }, "") + // Stop the running unit on every gateway replica so the next request launches the updated binary + stopAppEverywhere(app.CanonicalHost(), namespace) fmt.Printf("--> Successfully deployed and set executable: %s\n", targetBinPath) } else { fmt.Printf("--> Binary '%s' is up to date on shared persistent volume (sha256: %s).\n", targetBinPath, localHash[:12]) diff --git a/internal/platform/config.go b/internal/platform/config.go index 554c1c6..679dc1b 100644 --- a/internal/platform/config.go +++ b/internal/platform/config.go @@ -47,9 +47,9 @@ type DBTarget struct { // IngressConfig is filled in by the gateway and ingress commands. type IngressConfig struct { - Class string - Hosts []string - TLSSecret string // namespace/name + Class string + Hosts []string // individual hosts and wildcards (*.apps.example.com) routed to the gateway + TLS map[string]string // host -> "secret:" or "issuer:" } // GatewayConfig records where the gateway runs and who manages it. @@ -105,7 +105,13 @@ func (c *Config) ToData() map[string]string { set("redis.service", c.Redis) set("ingress.class", c.Ingress.Class) set("ingress.hosts", strings.Join(c.Ingress.Hosts, ",")) - set("ingress.tlsSecret", c.Ingress.TLSSecret) + var tls []string + for _, h := range c.Ingress.Hosts { + if v := c.Ingress.TLS[h]; v != "" { + tls = append(tls, h+"="+v) + } + } + set("ingress.tls", strings.Join(tls, ",")) set("gateway.namespace", c.Gateway.Namespace) set("gateway.service", c.Gateway.Service) set("gateway.managedBy", c.Gateway.ManagedBy) @@ -120,7 +126,7 @@ func FromData(d map[string]string) (*Config, error) { c := &Config{ Storage: StorageConfig{BlockClass: d["storage.blockClass"], RWXClass: d["storage.rwxClass"]}, Redis: d["redis.service"], - Ingress: IngressConfig{Class: d["ingress.class"], TLSSecret: d["ingress.tlsSecret"]}, + Ingress: IngressConfig{Class: d["ingress.class"]}, Gateway: GatewayConfig{Namespace: d["gateway.namespace"], Service: d["gateway.service"], ManagedBy: d["gateway.managedBy"]}, } for _, h := range strings.Split(d["ingress.hosts"], ",") { @@ -128,6 +134,14 @@ func FromData(d map[string]string) (*Config, error) { c.Ingress.Hosts = append(c.Ingress.Hosts, h) } } + for _, pair := range strings.Split(d["ingress.tls"], ",") { + if h, v, ok := strings.Cut(strings.TrimSpace(pair), "="); ok && h != "" && v != "" { + if c.Ingress.TLS == nil { + c.Ingress.TLS = map[string]string{} + } + c.Ingress.TLS[h] = v + } + } for _, prefix := range []string{"postgres", "mysql"} { op := d[prefix+".operator"] if op == "" { diff --git a/internal/platform/detect.go b/internal/platform/detect.go index 9593bf4..0f23026 100644 --- a/internal/platform/detect.go +++ b/internal/platform/detect.go @@ -320,3 +320,11 @@ func gradeStorageClass(sc object) StorageClass { } return s } + +func parseObject(b []byte) (object, error) { + var o object + if err := json.Unmarshal(b, &o); err != nil { + return nil, err + } + return o, nil +} diff --git a/internal/platform/gateway.go b/internal/platform/gateway.go new file mode 100644 index 0000000..1d98532 --- /dev/null +++ b/internal/platform/gateway.go @@ -0,0 +1,330 @@ +package platform + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "regexp" + "strings" +) + +// GatewayOptions configure the gateway manifests. +type GatewayOptions struct { + Namespace string + Image string + Replicas int + RWXClass string + VolumeSize string + IdleTimeout string + ImagePullPol string +} + +// GatewayManifest renders the gateway's ServiceAccount, RBAC, PVC, Deployment, +// Service and PodDisruptionBudget. +func GatewayManifest(o GatewayOptions) (string, error) { + if o.Image == "" { + return "", fmt.Errorf("--image is required (the image built by 'make image', pushed to a registry the cluster can pull from)") + } + if o.Namespace == "" { + o.Namespace = DefaultNamespace + } + if o.Replicas == 0 { + o.Replicas = 2 + } + if o.VolumeSize == "" { + o.VolumeSize = "5Gi" + } + if o.IdleTimeout == "" { + o.IdleTimeout = "60s" + } + if o.ImagePullPol == "" { + o.ImagePullPol = "IfNotPresent" + } + if o.RWXClass == "" { + return "", fmt.Errorf("no RWX StorageClass for /opt/apps; run 'zero-scale-ctl init' or 'zero-scale-ctl install longhorn', or pass --rwx-class") + } + return fmt.Sprintf(`apiVersion: v1 +kind: ServiceAccount +metadata: + name: zero-scale-gateway + namespace: %[1]s + labels: + app: zero-scale-gateway + app.kubernetes.io/name: zero-scale-gateway + app.kubernetes.io/part-of: zero-scale-platform + app.kubernetes.io/managed-by: zero-scale-ctl +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: zero-scale-gateway-role + namespace: %[1]s + labels: + app: zero-scale-gateway + app.kubernetes.io/name: zero-scale-gateway + app.kubernetes.io/part-of: zero-scale-platform + app.kubernetes.io/managed-by: zero-scale-ctl +rules: + - apiGroups: [""] + resources: ["configmaps", "secrets", "pods"] + verbs: ["get", "list", "watch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: zero-scale-gateway-binding + namespace: %[1]s + labels: + app: zero-scale-gateway + app.kubernetes.io/name: zero-scale-gateway + app.kubernetes.io/part-of: zero-scale-platform + app.kubernetes.io/managed-by: zero-scale-ctl +subjects: + - kind: ServiceAccount + name: zero-scale-gateway + namespace: %[1]s +roleRef: + kind: Role + name: zero-scale-gateway-role + apiGroup: rbac.authorization.k8s.io +--- +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: zero-scale-binaries-pvc + namespace: %[1]s + labels: + app: zero-scale-gateway + app.kubernetes.io/name: zero-scale-gateway + app.kubernetes.io/part-of: zero-scale-platform + app.kubernetes.io/managed-by: zero-scale-ctl +spec: + accessModes: ["ReadWriteMany"] + storageClassName: %[4]s + resources: + requests: + storage: %[5]s +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: zero-scale-gateway + namespace: %[1]s + labels: + app: zero-scale-gateway + app.kubernetes.io/name: zero-scale-gateway + app.kubernetes.io/part-of: zero-scale-platform + app.kubernetes.io/managed-by: zero-scale-ctl +spec: + replicas: %[3]d + strategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 0 + maxSurge: 1 + selector: + matchLabels: + app: zero-scale-gateway + template: + metadata: + labels: + app: zero-scale-gateway + app.kubernetes.io/name: zero-scale-gateway + app.kubernetes.io/part-of: zero-scale-platform + app.kubernetes.io/managed-by: zero-scale-ctl + spec: + serviceAccountName: zero-scale-gateway + topologySpreadConstraints: + - maxSkew: 1 + topologyKey: kubernetes.io/hostname + whenUnsatisfiable: ScheduleAnyway + labelSelector: + matchLabels: + app: zero-scale-gateway + containers: + - name: systemd-runner + image: %[2]s + imagePullPolicy: %[7]s + ports: + - name: http + containerPort: 80 + env: + - name: POD_NAME + valueFrom: {fieldRef: {fieldPath: metadata.name}} + - name: POD_NAMESPACE + valueFrom: {fieldRef: {fieldPath: metadata.namespace}} + - name: IDLE_TIMEOUT + value: "%[6]s" + readinessProbe: + tcpSocket: {port: 80} + initialDelaySeconds: 5 + periodSeconds: 5 + securityContext: + privileged: true + volumeMounts: + - {name: run, mountPath: /run} + - {name: run-lock, mountPath: /run/lock} + - {name: apps-volume, mountPath: /opt/apps} + volumes: + - name: run + emptyDir: {medium: Memory} + - name: run-lock + emptyDir: {medium: Memory} + - name: apps-volume + persistentVolumeClaim: + claimName: zero-scale-binaries-pvc +--- +apiVersion: v1 +kind: Service +metadata: + name: zero-scale-gateway + namespace: %[1]s + labels: + app: zero-scale-gateway + app.kubernetes.io/name: zero-scale-gateway + app.kubernetes.io/part-of: zero-scale-platform + app.kubernetes.io/managed-by: zero-scale-ctl +spec: + selector: + app: zero-scale-gateway + ports: + - name: http + port: 80 + targetPort: 80 +--- +apiVersion: policy/v1 +kind: PodDisruptionBudget +metadata: + name: zero-scale-gateway + namespace: %[1]s + labels: + app: zero-scale-gateway + app.kubernetes.io/name: zero-scale-gateway + app.kubernetes.io/part-of: zero-scale-platform + app.kubernetes.io/managed-by: zero-scale-ctl +spec: + minAvailable: 1 + selector: + matchLabels: + app: zero-scale-gateway +`, o.Namespace, o.Image, o.Replicas, o.RWXClass, o.VolumeSize, o.IdleTimeout, o.ImagePullPol), nil +} + +var hostRe = regexp.MustCompile(`^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$`) + +// ValidateHost accepts example.com, app.example.com and *.apps.example.com. +func ValidateHost(h string) error { + if !hostRe.MatchString(h) { + return fmt.Errorf("invalid host %q (want app.example.com or *.apps.example.com)", h) + } + return nil +} + +// HostCovered reports whether host is served by one of the routed entries: +// an exact match, or a wildcard covering exactly one extra label. +func HostCovered(host string, routed []string) bool { + host = strings.ToLower(host) + for _, r := range routed { + r = strings.ToLower(r) + if r == host { + return true + } + if suffix, ok := strings.CutPrefix(r, "*."); ok { + if label, rest, found := strings.Cut(host, "."); found && label != "" && rest == suffix { + return true + } + } + } + return false +} + +// RouteName is the Ingress name for a routed host. +func RouteName(host string) string { + prefix := "zero-scale-host-" + if strings.HasPrefix(host, "*.") { + prefix = "zero-scale-wildcard-" + host = strings.TrimPrefix(host, "*.") + } + name := prefix + strings.ReplaceAll(host, ".", "-") + if len(name) > 63 { + name = name[:54] + "-" + sha8(host) + } + return strings.TrimRight(name, "-") +} + +// RouteManifest renders the Ingress that sends host to the gateway Service. +// tls is "", "secret:" or "issuer:". +func RouteManifest(host, namespace, service, class, tls string) (string, error) { + if err := ValidateHost(host); err != nil { + return "", err + } + name := RouteName(host) + var b strings.Builder + fmt.Fprintf(&b, `apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: %s + namespace: %s + labels: + app: zero-scale-gateway + app.kubernetes.io/part-of: zero-scale-platform + zero-scale-route: "true" + annotations: + zero-scale.io/host: %q + nginx.ingress.kubernetes.io/upstream-hash-by: "$host" + nginx.ingress.kubernetes.io/proxy-body-size: "50m" +`, name, namespace, host) + secret := "" + switch { + case strings.HasPrefix(tls, "issuer:"): + fmt.Fprintf(&b, " cert-manager.io/cluster-issuer: %q\n", strings.TrimPrefix(tls, "issuer:")) + secret = name + "-tls" + case strings.HasPrefix(tls, "secret:"): + secret = strings.TrimPrefix(tls, "secret:") + case tls != "": + return "", fmt.Errorf("tls must be secret: or issuer:, got %q", tls) + } + b.WriteString("spec:\n") + if class != "" { + fmt.Fprintf(&b, " ingressClassName: %s\n", class) + } + if secret != "" { + fmt.Fprintf(&b, " tls:\n - hosts: [%q]\n secretName: %s\n", host, secret) + } + fmt.Fprintf(&b, ` rules: + - host: %q + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: %s + port: + number: 80 +`, host, service) + return b.String(), nil +} + +// IssuerSupportsWildcard checks a cert-manager ClusterIssuer (JSON) can issue a +// wildcard certificate: non-ACME issuers can, ACME issuers need a DNS-01 solver. +func IssuerSupportsWildcard(issuerJSON []byte) (bool, error) { + items, err := parseObject(issuerJSON) + if err != nil { + return false, err + } + if items.get("spec", "acme") == nil { + return true, nil + } + for _, s := range items.list("spec", "acme", "solvers") { + if s.get("dns01") != nil { + return true, nil + } + } + return false, nil +} + +func sha8(s string) string { + h := sha256.Sum256([]byte(s)) + return hex.EncodeToString(h[:])[:8] +} diff --git a/internal/platform/gateway_test.go b/internal/platform/gateway_test.go new file mode 100644 index 0000000..5031d7b --- /dev/null +++ b/internal/platform/gateway_test.go @@ -0,0 +1,103 @@ +package platform + +import ( + "os" + "strings" + "testing" +) + +func TestGatewayManifest(t *testing.T) { + if _, err := GatewayManifest(GatewayOptions{RWXClass: "x"}); err == nil { + t.Error("image must be required") + } + if _, err := GatewayManifest(GatewayOptions{Image: "img"}); err == nil { + t.Error("RWX class must be required") + } + m, err := GatewayManifest(GatewayOptions{Namespace: "qa", Image: "registry/zs:1", RWXClass: "longhorn-ha-rwx"}) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "namespace: qa", "replicas: 2", "storageClassName: longhorn-ha-rwx", "image: registry/zs:1", + "kind: PodDisruptionBudget", "topologyKey: kubernetes.io/hostname", "fieldPath: metadata.namespace", + "app.kubernetes.io/managed-by: zero-scale-ctl", + } { + if !strings.Contains(m, want) { + t.Errorf("manifest missing %q", want) + } + } + if strings.Contains(m, "*labels") || strings.Contains(m, "&labels") { + t.Error("YAML anchors do not work across documents") + } + if os.Getenv("DUMP_MANIFESTS") != "" { + os.WriteFile(os.Getenv("DUMP_MANIFESTS")+"/gateway.yaml", []byte(m), 0644) + r, _ := RouteManifest("*.apps.example.com", "qa", "zero-scale-gateway", "nginx", "issuer:le-dns") + os.WriteFile(os.Getenv("DUMP_MANIFESTS")+"/route.yaml", []byte(r), 0644) + } +} + +func TestHostCovered(t *testing.T) { + routed := []string{"*.apps.example.com", "status.example.com"} + cases := map[string]bool{ + "fdm.apps.example.com": true, + "FDM.apps.example.com": true, + "a.b.apps.example.com": false, // wildcards cover one label only + "apps.example.com": false, + "status.example.com": true, + "other.example.com": false, + "fdm-qa.apps.example.com": true, + } + for h, want := range cases { + if got := HostCovered(h, routed); got != want { + t.Errorf("HostCovered(%q) = %v, want %v", h, got, want) + } + } +} + +func TestRouteManifest(t *testing.T) { + m, err := RouteManifest("*.apps.example.com", "zero-scale-system", "zero-scale-gateway", "nginx", "issuer:letsencrypt-dns") + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "name: zero-scale-wildcard-apps-example-com", + `cert-manager.io/cluster-issuer: "letsencrypt-dns"`, + `nginx.ingress.kubernetes.io/upstream-hash-by: "$host"`, + `- hosts: ["*.apps.example.com"]`, + "secretName: zero-scale-wildcard-apps-example-com-tls", + "ingressClassName: nginx", + } { + if !strings.Contains(m, want) { + t.Errorf("route missing %q:\n%s", want, m) + } + } + m, _ = RouteManifest("status.example.com", "ns", "svc", "", "") + if strings.Contains(m, "tls:") || strings.Contains(m, "ingressClassName") || !strings.Contains(m, "name: zero-scale-host-status-example-com") { + t.Errorf("plain route wrong:\n%s", m) + } + for _, bad := range []string{"*.com", "a..b.com", "*.*.x.com", "UPPER.example.com", "x.example.com/path"} { + if _, err := RouteManifest(bad, "ns", "svc", "", ""); err == nil { + t.Errorf("accepted bad host %q", bad) + } + } + if _, err := RouteManifest("a.example.com", "ns", "svc", "", "bogus"); err == nil { + t.Error("accepted bad tls value") + } + if n := RouteName("*." + strings.Repeat("abcdefghij.", 8) + "com"); len(n) > 63 { + t.Errorf("name too long: %s", n) + } +} + +func TestIssuerSupportsWildcard(t *testing.T) { + cases := map[string]bool{ + `{"spec":{"ca":{"secretName":"root"}}}`: true, + `{"spec":{"acme":{"solvers":[{"http01":{"ingress":{}}}]}}}`: false, + `{"spec":{"acme":{"solvers":[{"http01":{}},{"dns01":{"cloudflare":{}}}]}}}`: true, + } + for in, want := range cases { + got, err := IssuerSupportsWildcard([]byte(in)) + if err != nil || got != want { + t.Errorf("%s: got %v %v, want %v", in, got, err, want) + } + } +} diff --git a/internal/platform/platform_test.go b/internal/platform/platform_test.go index afb02c5..c418b83 100644 --- a/internal/platform/platform_test.go +++ b/internal/platform/platform_test.go @@ -156,6 +156,7 @@ func TestConfigRoundTrip(t *testing.T) { r, _ := Detect(fullCluster()) c, _ := Choose(r, Options{}) c.Ingress.Hosts = []string{"*.apps.example.com", "status.example.com"} + c.Ingress.TLS = map[string]string{"*.apps.example.com": "issuer:letsencrypt-dns"} back, err := FromData(c.ToData()) if err != nil { t.Fatal(err) diff --git a/internal/runner/systemd.go b/internal/runner/systemd.go index 087a416..0a19f29 100644 --- a/internal/runner/systemd.go +++ b/internal/runner/systemd.go @@ -121,7 +121,7 @@ func StartTransientService(host string, port int, binaryPath, namespace string, "host": true, "hosts": true, "url": true, "type": true, "mounts": true, "scale-to-zero": true, "scale_to_zero": true, "idle-timeout": true, "idle_timeout": true, - "database_configmap": true, "database_secret": true, + "database_configmap": true, "database_secret": true, "database_engine": true, "args": true, "user": true, "dynamic-user": true, "dynamic_user": true, "oauth-setup": true, "oauth_setup": true, "oauth": true,