Add QA and feature-branch environments
env create/delete/gc/list manage a namespace per environment, labelled
zero-scale.io/env, with a ResourceQuota, its own gateway and an optional
wildcard route. A zero-scale-env ConfigMap records the env and may override
the platform's database clusters. Hosts use ${ENV_SUFFIX}; databases in a
non-primary env are named db_<env>_<app>_<hash> and carry an owner comment,
so env delete drops only what the env owns. oauth-setup --auth-host serves
every app's login from one callback host. deploy/ manifests no longer
hardcode a namespace; deploy/kustomization.yaml sets it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uKdmp7tLySXvQXALz2x9V
This commit is contained in:
committed by
Stephen Schuresko
parent
030ba83733
commit
e33abed59b
6
Makefile
6
Makefile
@@ -45,8 +45,10 @@ build-jwks-aggregator:
|
||||
# Kubernetes Manifests
|
||||
# -------------------------------------------------------------
|
||||
deploy-manifests:
|
||||
@echo "==> Applying all Kubernetes manifests in deploy/ to namespace '$(NAMESPACE)'..."
|
||||
kubectl apply -f deploy/ -n $(NAMESPACE)
|
||||
@echo "==> Applying the core gateway manifests in deploy/ to namespace '$(NAMESPACE)'..."
|
||||
@tmp=$$(mktemp -d) && cp deploy/*.yaml $$tmp/ && \
|
||||
sed -i 's/^namespace: .*/namespace: $(NAMESPACE)/' $$tmp/kustomization.yaml && \
|
||||
kubectl apply -k $$tmp; status=$$?; rm -rf $$tmp; exit $$status
|
||||
|
||||
# -------------------------------------------------------------
|
||||
# Gateway Deployment (Binary + Service Update + Restart)
|
||||
|
||||
28
README.md
28
README.md
@@ -237,6 +237,27 @@ All manifests and CLI operations support arbitrary namespaces via `-n` / `--name
|
||||
```bash
|
||||
zero-scale-ctl apply -f ./myapp.conf -n production
|
||||
```
|
||||
The manifests in `deploy/` carry no namespace. `deploy/kustomization.yaml` sets it for the core gateway resources (including the RoleBinding subject), so `kubectl apply -k deploy/` after `kustomize edit set namespace <ns>`, or `make deploy-manifests NAMESPACE=<ns>`, works in any namespace.
|
||||
|
||||
### QA and Feature-Branch Environments
|
||||
<a id="environments"></a>
|
||||
Each environment is a namespace with its own gateway and `/opt/apps` volume, sharing the cluster's HA databases and storage classes. A `zero-scale-env` ConfigMap in the namespace records the environment.
|
||||
|
||||
```bash
|
||||
zero-scale-ctl env create qa --replicas 2 --yes # long-lived QA
|
||||
zero-scale-ctl env create feat-login --ttl 7d --yes # a branch environment from CI
|
||||
zero-scale-ctl apply -f fdm.conf -n feat-login
|
||||
zero-scale-ctl env list
|
||||
zero-scale-ctl env delete feat-login --yes # drops its databases, volumes and namespace
|
||||
zero-scale-ctl env gc --yes # deletes environments past their TTL (run from cron or CI)
|
||||
```
|
||||
|
||||
- **Hosts.** Write hostnames as `fdm${ENV_SUFFIX}.apps.example.com`. Outside an environment, or in one created with `--primary`, the suffix is empty (`fdm.apps.example.com`); in `qa` it is `fdm-qa.apps.example.com`. Keeping one label level lets one `*.apps.example.com` certificate cover every environment. `${ENV}` expands to the environment name in hosts, args and env values. In a non-primary environment, `apply` refuses hosts that do not carry the suffix (or fall under the environment's own `--route`), so two environments never claim the same host.
|
||||
- **Routing.** Apps in an environment get exact-host Ingresses pointing at that environment's gateway. The platform's wildcard route stays with the primary gateway. Use `env create --route '*.qa.apps.example.com'` to give an environment its own wildcard instead.
|
||||
- **Databases.** Names become `db_<env>_<app>_<hash>` and `u_<env>_<app>_<hash>` (user names stay within MySQL's 32 characters). Postgres databases carry an owner comment naming the environment, and `env delete` only drops databases whose comment matches. The primary environment keeps the original `db_<app>_<hash>` names, so existing databases are found again. `--postgres ns/name --postgres-service host:port` points one environment at its own cluster.
|
||||
- **Volumes.** `env delete` switches the namespace's PersistentVolumes to the `Delete` reclaim policy before deleting the namespace, so Longhorn frees them. `--keep-data` keeps databases and volumes.
|
||||
- **Quota.** Each environment gets a ResourceQuota on pods, claims and storage (`--quota-pods`, `--quota-storage`). It does not limit CPU or memory, so the gateway needs no resource requests.
|
||||
- **OAuth.** `zero-scale-ctl oauth-setup <name> --url <provider> --auth-host auth.apps.example.com -n zero-scale-system` serves every login from one callback host with a cookie for `.apps.example.com`. Apps in any environment then point at that one oauth2-proxy, and new branch hosts need no change at the OAuth provider. Hosts outside the cookie domain are refused.
|
||||
|
||||
---
|
||||
|
||||
@@ -256,8 +277,11 @@ make push
|
||||
|
||||
### 3. Deploy to Kubernetes
|
||||
```bash
|
||||
# Apply all core platform manifests (ServiceAccount, RBAC, PVC, Deployment, Service, Ingress):
|
||||
kubectl apply -f deploy/
|
||||
# Recommended: an HA gateway rendered by the CLI
|
||||
zero-scale-ctl gateway install --image <registry>/zero-scale:<tag> --yes
|
||||
|
||||
# Or the plain manifests (ServiceAccount, RBAC, PVC, Deployment, Service) in any namespace:
|
||||
make deploy-manifests NAMESPACE=zero-scale-system
|
||||
|
||||
# Or deploy via Makefile:
|
||||
make deploy
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/appname"
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/env"
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/volumes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -58,6 +59,9 @@ type AppConfig struct {
|
||||
Secrets map[string]string // Custom managed secrets (key -> type, e.g. "generate")
|
||||
ConfigFiles []string // Auxiliary config files to template and upload to /opt/apps/
|
||||
Launcher string // Explicit full launcher script override (optional)
|
||||
|
||||
Environment *env.Config // the target namespace's environment; nil outside one (see bindEnv)
|
||||
envBound bool
|
||||
}
|
||||
|
||||
// RedirectConfig represents an edge NGINX redirect rule.
|
||||
@@ -95,12 +99,14 @@ func sha8(s string) string {
|
||||
|
||||
// DBName returns the deterministic, conflict-free database name.
|
||||
func (a *AppConfig) DBName() string {
|
||||
return fmt.Sprintf("db_%s_%s", a.AppName(), sha8(a.CanonicalHost()))
|
||||
db, _ := a.Environment.DBNames(a.AppName(), sha8(a.CanonicalHost()))
|
||||
return db
|
||||
}
|
||||
|
||||
// DBUser returns the unique, unguessable database username.
|
||||
func (a *AppConfig) DBUser() string {
|
||||
return fmt.Sprintf("u_%s_%s", a.AppName(), sha8(a.CanonicalHost()))
|
||||
_, user := a.Environment.DBNames(a.AppName(), sha8(a.CanonicalHost()))
|
||||
return user
|
||||
}
|
||||
|
||||
// SecretName returns the Kubernetes Secret name for this app.
|
||||
@@ -371,7 +377,8 @@ func LoadConfig(filePath string) (interface{}, error) {
|
||||
// Also extract short name from hostname (e.g. hs from hs.ffxm.cc)
|
||||
var hostShort string
|
||||
if len(hostnames) > 0 {
|
||||
hostShort = appname.Name(hostnames[0])
|
||||
// Templated hosts (fdm${ENV_SUFFIX}.example.com) take the primary env's name.
|
||||
hostShort = appname.Name((*env.Config)(nil).Expand(hostnames[0]))
|
||||
}
|
||||
|
||||
for _, cf := range configFiles {
|
||||
|
||||
@@ -88,6 +88,9 @@ func ProvisionPostgres(app *AppConfig, namespace string) (dbName, dbUser, dbPass
|
||||
|
||||
// ProvisionDataLayer orchestrates database and Redis provisioning and populates k8s resources.
|
||||
func ProvisionDataLayer(app *AppConfig, namespace string) error {
|
||||
if err := bindEnv(app, namespace); err != nil {
|
||||
return err
|
||||
}
|
||||
secretData := make(map[string]string)
|
||||
configMapData := make(map[string]string)
|
||||
|
||||
@@ -165,7 +168,7 @@ func ProvisionDataLayer(app *AppConfig, namespace string) error {
|
||||
|
||||
if app.Redis != nil {
|
||||
redisEndpoint := fmt.Sprintf("shared-redis.%s.svc.cluster.local:6379", namespace)
|
||||
if p, err := loadPlatform(); err == nil && p != nil && p.Redis != "" {
|
||||
if p, err := loadPlatformFor(namespace); err == nil && p != nil && p.Redis != "" {
|
||||
redisEndpoint = p.Redis
|
||||
}
|
||||
redisHost, redisPort, _ := strings.Cut(redisEndpoint, ":")
|
||||
|
||||
199
cmd/zero-scale-ctl/env_test.go
Normal file
199
cmd/zero-scale-ctl/env_test.go
Normal file
@@ -0,0 +1,199 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/platform"
|
||||
)
|
||||
|
||||
const pgPlatformCM = `{"data":{"version":"1","storage.rwxClass":"longhorn-rwx","gateway.namespace":"zero-scale-system","ingress.class":"nginx","ingress.hosts":"*.apps.example.com","postgres.operator":"cnpg","postgres.cluster":"cnpg-system/ha-postgres","postgres.rwService":"ha-postgres-rw.cnpg-system.svc.cluster.local:5432"}}`
|
||||
|
||||
func fixedNow(t *testing.T, ts string) {
|
||||
at, _ := time.Parse(time.RFC3339, ts)
|
||||
old := now
|
||||
now = func() time.Time { return at }
|
||||
t.Cleanup(func() { now = old })
|
||||
}
|
||||
|
||||
func TestEnvCreate(t *testing.T) {
|
||||
fixedNow(t, "2026-10-27T10:00:00Z")
|
||||
base := ` "get configmap zero-scale-platform -n zero-scale-system -o json") echo '` + pgPlatformCM + `' ;;
|
||||
"get namespace -l zero-scale.io/env=feat-x -o json") echo '{"items":[]}' ;;
|
||||
"get namespace feat-x -o json") echo 'Error from server (NotFound)' >&2; exit 1 ;;
|
||||
"get deployment -n zero-scale-system -l app=zero-scale-gateway -o jsonpath="*) printf reg/zs:7 ;;
|
||||
"-n feat-x rollout status "*) exit 0 ;;`
|
||||
log := fakeKubectl(t, base)
|
||||
if err := runEnv([]string{"create", "feat-x", "--ttl", "3d"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m := mutatingCalls(readLog(t, log)); len(m) != 0 {
|
||||
t.Errorf("dry run changed things: %v", m)
|
||||
}
|
||||
|
||||
log = fakeKubectl(t, base)
|
||||
if err := runEnv([]string{"create", "feat-x", "--ttl", "3d", "--yes"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := readLog(t, log)
|
||||
for _, want := range []string{
|
||||
"zero-scale.io/env: feat-x", `zero-scale.io/expires: "2026-10-30T10:00:00Z"`, "kind: ResourceQuota",
|
||||
`env.name: "feat-x"`, "image: reg/zs:7", "namespace: feat-x", "replicas: 1", "storageClassName: longhorn-rwx",
|
||||
} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("missing %q", want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(got, "zero-scale-platform\n") && strings.Contains(got, "gateway.namespace: \"feat-x\"") {
|
||||
t.Error("an env's gateway must not replace the platform gateway")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvCreateRefusesForeignNamespace(t *testing.T) {
|
||||
fakeKubectl(t, ` "get namespace team-a -o json") echo '{"metadata":{"name":"team-a","labels":{}}}' ;;`)
|
||||
if err := runEnv([]string{"create", "team-a"}); err == nil || !strings.Contains(err.Error(), "--adopt") {
|
||||
t.Errorf("want --adopt error, got %v", err)
|
||||
}
|
||||
fakeKubectl(t, ` "get namespace qa -o json") echo '{"metadata":{"name":"qa","labels":{"zero-scale.io/env":"staging"}}}' ;;`)
|
||||
if err := runEnv([]string{"create", "qa"}); err == nil || !strings.Contains(err.Error(), "staging") {
|
||||
t.Errorf("want ownership error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
const featEnvCM = `{"data":{"env.name":"feat-x","env.expires":"2026-10-30T10:00:00Z"}}`
|
||||
|
||||
func TestApplyInEnvExpandsHostsAndScopesDB(t *testing.T) {
|
||||
log := fakeKubectl(t, ` "get configmap zero-scale-platform -n zero-scale-system -o json") echo '`+pgPlatformCM+`' ;;
|
||||
"get configmap zero-scale-env -n feat-x -o json") echo '`+featEnvCM+`' ;;
|
||||
"get pods -n cnpg-system -l cnpg.io/cluster=ha-postgres,cnpg.io/instanceRole=primary "*) printf ha-postgres-1 ;;`)
|
||||
app := &AppConfig{Hostnames: []string{"fdm${ENV_SUFFIX}.apps.example.com"}, Env: map[string]string{"BASE_URL": "https://fdm${ENV_SUFFIX}.apps.example.com"},
|
||||
Database: &DatabaseConfig{Engine: "postgres"}}
|
||||
if err := bindEnv(app, "feat-x"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if app.CanonicalHost() != "fdm-feat-x.apps.example.com" || app.Env["BASE_URL"] != "https://fdm-feat-x.apps.example.com" {
|
||||
t.Errorf("expansion: %v %v", app.Hostnames, app.Env)
|
||||
}
|
||||
if !strings.HasPrefix(app.DBName(), "db_feat_x_fdmfeatx_") || len(app.DBUser()) > 32 {
|
||||
t.Errorf("names: %s %s", app.DBName(), app.DBUser())
|
||||
}
|
||||
if _, _, _, _, err := ProvisionPostgres(app, "feat-x"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := readLog(t, log); !strings.Contains(got, "zero-scale: env=feat-x namespace=feat-x app=fdmfeatx") {
|
||||
t.Errorf("owner comment missing:\n%s", got)
|
||||
}
|
||||
if hostsCoveredByRoutes(app.Hostnames, "feat-x") {
|
||||
t.Error("prod's wildcard route must not cover an env's hosts")
|
||||
}
|
||||
|
||||
bad := &AppConfig{Hostnames: []string{"fdm.apps.example.com"}}
|
||||
if err := bindEnv(bad, "feat-x"); err == nil {
|
||||
t.Error("an unsuffixed host must be refused in a scoped env")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvDelete(t *testing.T) {
|
||||
apps := `{"items":[{"metadata":{"name":"zero-scale-app-fdmfeatx"},"data":{"host":"fdm-feat-x.apps.example.com","database_engine":"postgres"}},{"metadata":{"name":"zero-scale-app-web"},"data":{"host":"web-feat-x.apps.example.com"}}]}`
|
||||
script := ` "get configmap zero-scale-platform -n zero-scale-system -o json") echo '` + pgPlatformCM + `' ;;
|
||||
"get namespace -l zero-scale.io/env=feat-x -o json") echo '{"items":[{"metadata":{"name":"feat-x","labels":{"zero-scale.io/env":"feat-x"}}}]}' ;;
|
||||
"get configmap zero-scale-env -n feat-x -o json") echo '` + featEnvCM + `' ;;
|
||||
"get configmap -n feat-x -l zero-scale-app=true -o json") echo '` + apps + `' ;;
|
||||
"get pvc -n feat-x -o jsonpath="*) printf 'pvc-111 pvc-222' ;;
|
||||
"get pods -n cnpg-system -l cnpg.io/cluster=ha-postgres,cnpg.io/instanceRole=primary "*) printf ha-postgres-1 ;;
|
||||
"patch pv "*|"delete namespace "*) exit 0 ;;`
|
||||
log := fakeKubectl(t, script)
|
||||
if err := runEnv([]string{"delete", "feat-x"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m := mutatingCalls(readLog(t, log)); len(m) != 0 {
|
||||
t.Errorf("dry run changed things: %v", m)
|
||||
}
|
||||
|
||||
log = fakeKubectl(t, script)
|
||||
if err := runEnv([]string{"delete", "feat-x", "--yes"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := readLog(t, log)
|
||||
for _, want := range []string{
|
||||
"zero-scale: env=feat-x namespace=feat-x app=fdmfeatx",
|
||||
`kubectl patch pv pvc-111 -p {"spec":{"persistentVolumeReclaimPolicy":"Delete"}}`,
|
||||
"kubectl patch pv pvc-222",
|
||||
"kubectl delete namespace feat-x",
|
||||
} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("missing %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
if strings.Index(got, "DROP DATABASE") > strings.Index(got, "delete namespace") {
|
||||
t.Error("databases must be dropped before the namespace goes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvDeleteRefusesPrimary(t *testing.T) {
|
||||
fakeKubectl(t, ` "get namespace -l zero-scale.io/env=prod -o json") echo '{"items":[{"metadata":{"name":"apps","labels":{"zero-scale.io/env":"prod"}}}]}' ;;
|
||||
"get configmap zero-scale-env -n apps -o json") echo '{"data":{"env.name":"prod","env.primary":"true"}}' ;;`)
|
||||
if err := runEnv([]string{"delete", "prod", "--yes"}); err == nil || !strings.Contains(err.Error(), "primary") {
|
||||
t.Errorf("want primary refusal, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvGC(t *testing.T) {
|
||||
fixedNow(t, "2026-11-01T00:00:00Z")
|
||||
list := `{"items":[
|
||||
{"metadata":{"name":"feat-x","labels":{"zero-scale.io/env":"feat-x"},"annotations":{"zero-scale.io/expires":"2026-10-30T10:00:00Z"}}},
|
||||
{"metadata":{"name":"feat-y","labels":{"zero-scale.io/env":"feat-y"},"annotations":{"zero-scale.io/expires":"2026-12-01T00:00:00Z"}}},
|
||||
{"metadata":{"name":"qa","labels":{"zero-scale.io/env":"qa"}}}]}`
|
||||
log := fakeKubectl(t, ` "get namespace -l zero-scale.io/env -o json") echo '`+list+`' ;;
|
||||
"get namespace -l zero-scale.io/env=feat-x -o json") echo '{"items":[{"metadata":{"name":"feat-x"}}]}' ;;
|
||||
"get configmap zero-scale-env -n feat-x -o json") echo '`+featEnvCM+`' ;;
|
||||
"get configmap -n feat-x -l zero-scale-app=true -o json") echo '{"items":[]}' ;;
|
||||
"get pvc -n feat-x -o jsonpath="*) printf '' ;;
|
||||
"delete namespace "*) exit 0 ;;`)
|
||||
if err := runEnv([]string{"gc", "--yes"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := mutatingCalls(readLog(t, log))
|
||||
if len(m) != 1 || m[0] != "kubectl delete namespace feat-x --wait=false" {
|
||||
t.Errorf("gc should delete only feat-x: %v", m)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedOAuthIngress(t *testing.T) {
|
||||
cm := `{"data":{"version":"1","ingress.class":"nginx","oauth.host":"auth.apps.example.com","oauth.namespace":"zero-scale-system"}}`
|
||||
log := fakeKubectl(t, ` "get configmap zero-scale-platform -n zero-scale-system -o json") echo '`+cm+`' ;;`)
|
||||
if err := ApplyIngress("zero-scale-fdmqa", "qa", "zero-scale-gateway", 80, []string{"fdm-qa.apps.example.com"}, "team"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := readLog(t, log)
|
||||
for _, want := range []string{
|
||||
`auth-url: "http://oauth2-proxy-team.zero-scale-system.svc.cluster.local:4180/oauth2/auth"`,
|
||||
`auth-signin: "https://auth.apps.example.com/oauth2/start?rd=https://$host$escaped_request_uri"`,
|
||||
} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("missing %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
if err := ReconcileOAuthSetup("team", "https://git.example.com", "", []string{"fdm.other.org"}, "qa"); err == nil {
|
||||
t.Error("a host outside the cookie domain must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedOAuthProxyArgs(t *testing.T) {
|
||||
log := fakeKubectl(t, ` "get service shared-redis -n zero-scale-system -o json") echo '{}' ;;`)
|
||||
shared := sharedOAuthConfig("auth.apps.example.com", "zero-scale-system")
|
||||
if err := deploySharedOAuth2Proxy("team", "https://git.example.com", "", []string{"https://auth.apps.example.com/oauth2/callback"}, "zero-scale-system", shared); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := readLog(t, log)
|
||||
for _, want := range []string{"--redirect-url=https://auth.apps.example.com/oauth2/callback", "--cookie-domain=.apps.example.com", "--whitelist-domain=.apps.example.com"} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("missing %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sharedOAuthConfig(host, ns string) platform.OAuthConfig {
|
||||
return platform.OAuthConfig{Host: host, Namespace: ns}
|
||||
}
|
||||
407
cmd/zero-scale-ctl/envcmd.go
Normal file
407
cmd/zero-scale-ctl/envcmd.go
Normal file
@@ -0,0 +1,407 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/appname"
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/env"
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/platform"
|
||||
)
|
||||
|
||||
// now is swapped in tests.
|
||||
var now = time.Now
|
||||
|
||||
func runEnv(args []string) error {
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("usage: zero-scale-ctl env create|delete|gc|list")
|
||||
}
|
||||
switch args[0] {
|
||||
case "create":
|
||||
return envCreate(args[1:])
|
||||
case "delete":
|
||||
return envDeleteCmd(args[1:])
|
||||
case "gc":
|
||||
return envGC(args[1:])
|
||||
case "list", "ls":
|
||||
return envList()
|
||||
}
|
||||
return fmt.Errorf("unknown env command %q (create, delete, gc, list)", args[0])
|
||||
}
|
||||
|
||||
type nsMeta struct {
|
||||
Metadata struct {
|
||||
Name string `json:"name"`
|
||||
Labels map[string]string `json:"labels"`
|
||||
Annotations map[string]string `json:"annotations"`
|
||||
} `json:"metadata"`
|
||||
}
|
||||
|
||||
// listEnvNamespaces returns the namespaces labelled as zero-scale environments.
|
||||
func listEnvNamespaces(selector string) ([]nsMeta, error) {
|
||||
out, err := RunKubectl([]string{"get", "namespace", "-l", selector, "-o", "json"}, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var list struct{ Items []nsMeta }
|
||||
if err := json.Unmarshal([]byte(out), &list); err != nil {
|
||||
return nil, fmt.Errorf("parsing namespaces: %w", err)
|
||||
}
|
||||
return list.Items, nil
|
||||
}
|
||||
|
||||
func getNamespace(name string) (*nsMeta, error) {
|
||||
out, err := RunKubectl([]string{"get", "namespace", name, "-o", "json"}, "")
|
||||
if err != nil {
|
||||
if isNotFound(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var ns nsMeta
|
||||
if err := json.Unmarshal([]byte(out), &ns); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ns, nil
|
||||
}
|
||||
|
||||
// currentGatewayImage is the image the platform's gateway runs, so new environments match it.
|
||||
func currentGatewayImage(p *platform.Config) string {
|
||||
if p == nil || p.Gateway.Namespace == "" {
|
||||
return ""
|
||||
}
|
||||
out, err := RunKubectl([]string{"get", "deployment", "-n", p.Gateway.Namespace, "-l", "app=zero-scale-gateway",
|
||||
"-o", "jsonpath={.items[0].spec.template.spec.containers[0].image}"}, "")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(out)
|
||||
}
|
||||
|
||||
func envCreate(args []string) error {
|
||||
name, rest := splitHostArgs(args)
|
||||
fs := flag.NewFlagSet("env create", flag.ExitOnError)
|
||||
nsFlag := fs.String("namespace", "", "Namespace for the environment (default: the env name)")
|
||||
ttl := fs.String("ttl", "", "Delete with 'env gc' after this long, e.g. 7d or 36h (default: never)")
|
||||
primary := fs.Bool("primary", false, "Mark as the primary environment (prod): unsuffixed hosts and the original database names")
|
||||
adopt := fs.Bool("adopt", false, "Allow an existing namespace that is not yet a zero-scale environment")
|
||||
image := fs.String("image", "", "Gateway image (default: the image the platform gateway runs)")
|
||||
replicas := fs.Int("replicas", 1, "Gateway replicas (use 2 or more for long-lived environments)")
|
||||
route := fs.String("route", "", "Optional wildcard or host routed to this env's gateway, e.g. '*.qa.apps.example.com'")
|
||||
secret := fs.String("tls-secret", "", "TLS Secret in the env namespace for --route")
|
||||
issuer := fs.String("issuer", "", "cert-manager ClusterIssuer for --route (DNS-01 for a wildcard)")
|
||||
pgCluster := fs.String("postgres", "", "Use this Postgres cluster (<namespace>/<name>) instead of the platform's")
|
||||
pgService := fs.String("postgres-service", "", "host:port of --postgres's read-write service")
|
||||
pgOperator := fs.String("postgres-operator", "cnpg", "Operator of --postgres")
|
||||
quotaPods := fs.Int("quota-pods", env.DefaultQuota.Pods, "ResourceQuota: max pods")
|
||||
quotaStorage := fs.String("quota-storage", env.DefaultQuota.Storage, "ResourceQuota: max requested storage")
|
||||
yes := fs.Bool("yes", false, "Apply (otherwise only print the plan)")
|
||||
_ = fs.Parse(rest)
|
||||
|
||||
if err := env.ValidateName(name); err != nil {
|
||||
return fmt.Errorf("usage: zero-scale-ctl env create <name> [--ttl 7d] [--primary] ...: %w", err)
|
||||
}
|
||||
ns := *nsFlag
|
||||
if ns == "" {
|
||||
ns = name
|
||||
}
|
||||
if *primary && *ttl != "" {
|
||||
return fmt.Errorf("the primary environment cannot have a TTL")
|
||||
}
|
||||
d, err := env.ParseTTL(*ttl)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if (*pgCluster == "") != (*pgService == "") {
|
||||
return fmt.Errorf("--postgres and --postgres-service go together")
|
||||
}
|
||||
|
||||
// Refuse to take over a namespace that belongs to something else or to another env.
|
||||
existing, err := getNamespace(ns)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing != nil {
|
||||
if owner := existing.Metadata.Labels[env.Label]; owner != "" && owner != name {
|
||||
return fmt.Errorf("namespace %s already belongs to environment %q", ns, owner)
|
||||
} else if owner == "" && !*adopt {
|
||||
return fmt.Errorf("namespace %s already exists and is not a zero-scale environment; pass --adopt to turn it into one", ns)
|
||||
}
|
||||
}
|
||||
others, err := listEnvNamespaces(env.Label + "=" + name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, o := range others {
|
||||
if o.Metadata.Name != ns {
|
||||
return fmt.Errorf("environment %q already exists in namespace %s", name, o.Metadata.Name)
|
||||
}
|
||||
}
|
||||
|
||||
p, err := loadPlatform()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if p == nil {
|
||||
return fmt.Errorf("no platform config yet; run 'zero-scale-ctl init' first so environments share the same storage and databases")
|
||||
}
|
||||
|
||||
cfg := &env.Config{Name: name, Primary: *primary, Created: now().UTC().Truncate(time.Second), Overrides: map[string]string{}}
|
||||
if d > 0 {
|
||||
cfg.Expires = cfg.Created.Add(d)
|
||||
}
|
||||
if *pgCluster != "" {
|
||||
cfg.Overrides["postgres.operator"] = *pgOperator
|
||||
cfg.Overrides["postgres.cluster"] = *pgCluster
|
||||
cfg.Overrides["postgres.rwService"] = *pgService
|
||||
}
|
||||
var routeManifest string
|
||||
if *route != "" {
|
||||
host := strings.ToLower(strings.TrimSpace(*route))
|
||||
tls, err := resolveRouteTLS(host, *secret, *issuer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if routeManifest, err = platform.RouteManifest(host, ns, "zero-scale-gateway", resolveIngressClass(), tls); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.Overrides["ingress.hosts"] = host
|
||||
if tls != "" {
|
||||
cfg.Overrides["ingress.tls"] = host + "=" + tls
|
||||
}
|
||||
}
|
||||
|
||||
steps := []platform.Step{{
|
||||
Title: fmt.Sprintf("Namespace %s (labelled %s=%s), ResourceQuota and %s ConfigMap", ns, env.Label, name, env.ConfigMapName),
|
||||
Manifest: cfg.Manifest(ns, env.Quota{Pods: *quotaPods, PVCs: env.DefaultQuota.PVCs, Storage: *quotaStorage}),
|
||||
}}
|
||||
if manager, exists := existingGatewayManager(ns); exists {
|
||||
fmt.Printf("==> A gateway (managed by %s) already runs in %s; keeping it.\n", manager, ns)
|
||||
} else {
|
||||
img := *image
|
||||
if img == "" {
|
||||
img = currentGatewayImage(p)
|
||||
}
|
||||
gw, err := platform.GatewayManifest(platform.GatewayOptions{Namespace: ns, Image: img, Replicas: *replicas, RWXClass: p.Storage.RWXClass})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
steps = append(steps,
|
||||
platform.Step{Title: fmt.Sprintf("Gateway in %s (%d replica(s), image %s)", ns, *replicas, img), Manifest: gw},
|
||||
platform.Step{Title: "Wait for the rollout", Command: []string{"kubectl", "-n", ns, "rollout", "status", "deployment/zero-scale-gateway", "--timeout=5m"}})
|
||||
}
|
||||
if routeManifest != "" {
|
||||
steps = append(steps, platform.Step{Title: "Route " + *route + " to this environment's gateway", Manifest: routeManifest})
|
||||
}
|
||||
|
||||
fmt.Printf("==> Environment %q in namespace %s\n", name, ns)
|
||||
if cfg.Scoped() {
|
||||
fmt.Printf(" hosts: write them as <app>${ENV_SUFFIX}.<domain>; here that is <app>%s.<domain>\n", cfg.Suffix())
|
||||
fmt.Printf(" databases: db_%s_<app>_<hash> on %s\n", strings.ReplaceAll(name, "-", "_"), map[bool]string{true: *pgCluster, false: "the platform's clusters"}[*pgCluster != ""])
|
||||
}
|
||||
if !cfg.Expires.IsZero() {
|
||||
fmt.Printf(" expires: %s ('zero-scale-ctl env gc' deletes it after that)\n", cfg.Expires.Format(time.RFC3339))
|
||||
}
|
||||
if err := executePlan(steps, *yes); err != nil || !*yes {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("✅ Environment %q is ready. Deploy into it with: zero-scale-ctl apply -f app.conf -n %s\n", name, ns)
|
||||
return nil
|
||||
}
|
||||
|
||||
func envDeleteCmd(args []string) error {
|
||||
name, rest := splitHostArgs(args)
|
||||
fs := flag.NewFlagSet("env delete", flag.ExitOnError)
|
||||
keepData := fs.Bool("keep-data", false, "Keep the databases and volumes (only delete the namespace)")
|
||||
force := fs.Bool("force", false, "Delete the namespace even if dropping a database fails")
|
||||
yes := fs.Bool("yes", false, "Apply (otherwise only print the plan)")
|
||||
_ = fs.Parse(rest)
|
||||
if err := env.ValidateName(name); err != nil {
|
||||
return fmt.Errorf("usage: zero-scale-ctl env delete <name> [--keep-data] [--yes]: %w", err)
|
||||
}
|
||||
return envDelete(name, *keepData, *force, *yes)
|
||||
}
|
||||
|
||||
type appEntry struct {
|
||||
Name string
|
||||
Data map[string]string
|
||||
}
|
||||
|
||||
func listApps(namespace string) ([]appEntry, error) {
|
||||
out, err := RunKubectl([]string{"get", "configmap", "-n", namespace, "-l", "zero-scale-app=true", "-o", "json"}, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var list struct {
|
||||
Items []struct {
|
||||
Metadata struct{ Name string } `json:"metadata"`
|
||||
Data map[string]string `json:"data"`
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out), &list); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var apps []appEntry
|
||||
for _, it := range list.Items {
|
||||
if strings.HasPrefix(it.Metadata.Name, "zero-scale-app-") {
|
||||
apps = append(apps, appEntry{strings.TrimPrefix(it.Metadata.Name, "zero-scale-app-"), it.Data})
|
||||
}
|
||||
}
|
||||
return apps, nil
|
||||
}
|
||||
|
||||
// pvNames returns the PersistentVolumes bound to the namespace's claims.
|
||||
func pvNames(namespace string) ([]string, error) {
|
||||
out, err := RunKubectl([]string{"get", "pvc", "-n", namespace, "-o", "jsonpath={.items[*].spec.volumeName}"}, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return strings.Fields(out), nil
|
||||
}
|
||||
|
||||
func envDelete(name string, keepData, force, yes bool) error {
|
||||
matches, err := listEnvNamespaces(env.Label + "=" + name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(matches) != 1 {
|
||||
return fmt.Errorf("found %d namespaces labelled %s=%s; expected exactly one", len(matches), env.Label, name)
|
||||
}
|
||||
ns := matches[0].Metadata.Name
|
||||
if ns == platformNamespace() || ns == "default" || strings.HasPrefix(ns, "kube-") {
|
||||
return fmt.Errorf("refusing to delete namespace %s", ns)
|
||||
}
|
||||
e, err := loadEnv(ns)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if e == nil || e.Name != name {
|
||||
return fmt.Errorf("namespace %s has no %s ConfigMap for %q; delete it by hand if that is intended", ns, env.ConfigMapName, name)
|
||||
}
|
||||
if e.Primary {
|
||||
return fmt.Errorf("%q is the primary environment; zero-scale-ctl will not delete it", name)
|
||||
}
|
||||
|
||||
apps, err := listApps(ns)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var withDB []appEntry
|
||||
for _, a := range apps {
|
||||
if a.Data["database_engine"] != "" {
|
||||
withDB = append(withDB, a)
|
||||
}
|
||||
}
|
||||
pvs, err := pvNames(ns)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("==> Deleting environment %q (namespace %s, %d app(s))\n", name, ns, len(apps))
|
||||
if keepData {
|
||||
fmt.Println(" keeping databases and volumes (--keep-data)")
|
||||
} else {
|
||||
for _, a := range withDB {
|
||||
fmt.Printf(" drop the %s database of app %s (only if its owner comment names env=%s)\n", a.Data["database_engine"], a.Name, name)
|
||||
}
|
||||
for _, pv := range pvs {
|
||||
fmt.Printf(" delete PersistentVolume %s with the namespace (reclaim policy set to Delete)\n", pv)
|
||||
}
|
||||
}
|
||||
fmt.Printf(" delete namespace %s\n", ns)
|
||||
if !yes {
|
||||
fmt.Println("\nNothing was changed. Re-run with --yes to apply this plan.")
|
||||
return nil
|
||||
}
|
||||
|
||||
if !keepData {
|
||||
failed := 0
|
||||
for _, a := range withDB {
|
||||
if err := dropAppDatabase(a.Name, appname.Hosts(a.Data), a.Data, ns); err != nil {
|
||||
failed++
|
||||
fmt.Printf("⚠️ app %s: %v\n", a.Name, err)
|
||||
}
|
||||
}
|
||||
if failed > 0 && !force {
|
||||
return fmt.Errorf("%d database(s) could not be dropped; the namespace was kept. Fix the cause and re-run, or pass --force", failed)
|
||||
}
|
||||
for _, pv := range pvs {
|
||||
if _, err := RunKubectl([]string{"patch", "pv", pv, "-p", `{"spec":{"persistentVolumeReclaimPolicy":"Delete"}}`}, ""); err != nil {
|
||||
fmt.Printf("⚠️ PersistentVolume %s keeps its reclaim policy: %v\n", pv, err)
|
||||
}
|
||||
}
|
||||
} else if len(pvs) > 0 {
|
||||
fmt.Printf("--> Volumes kept: %s (delete them by hand when no longer needed)\n", strings.Join(pvs, " "))
|
||||
}
|
||||
if _, err := RunKubectl([]string{"delete", "namespace", ns, "--wait=false"}, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("✅ Environment %q deleted (namespace %s is terminating).\n", name, ns)
|
||||
return nil
|
||||
}
|
||||
|
||||
func envGC(args []string) error {
|
||||
fs := flag.NewFlagSet("env gc", flag.ExitOnError)
|
||||
yes := fs.Bool("yes", false, "Delete the expired environments (otherwise only list them)")
|
||||
_ = fs.Parse(args)
|
||||
items, err := listEnvNamespaces(env.Label)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var expired []string
|
||||
for _, ns := range items {
|
||||
exp := ns.Metadata.Annotations[env.ExpiresAnnotation]
|
||||
if exp == "" {
|
||||
continue
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339, exp)
|
||||
if err != nil {
|
||||
fmt.Printf("⚠️ namespace %s: bad %s %q\n", ns.Metadata.Name, env.ExpiresAnnotation, exp)
|
||||
continue
|
||||
}
|
||||
if now().After(t) {
|
||||
expired = append(expired, ns.Metadata.Labels[env.Label])
|
||||
}
|
||||
}
|
||||
sort.Strings(expired)
|
||||
if len(expired) == 0 {
|
||||
fmt.Println("No expired environments.")
|
||||
return nil
|
||||
}
|
||||
failed := 0
|
||||
for _, name := range expired {
|
||||
if err := envDelete(name, false, false, *yes); err != nil {
|
||||
failed++
|
||||
fmt.Printf("⚠️ %s: %v\n", name, err)
|
||||
}
|
||||
}
|
||||
if failed > 0 {
|
||||
return fmt.Errorf("%d of %d expired environment(s) could not be deleted", failed, len(expired))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func envList() error {
|
||||
items, err := listEnvNamespaces(env.Label)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 2, 2, ' ', 0)
|
||||
fmt.Fprintln(w, "ENV\tNAMESPACE\tEXPIRES")
|
||||
for _, ns := range items {
|
||||
exp := ns.Metadata.Annotations[env.ExpiresAnnotation]
|
||||
if exp == "" {
|
||||
exp = "never"
|
||||
} else if t, err := time.Parse(time.RFC3339, exp); err == nil && now().After(t) {
|
||||
exp += " (expired)"
|
||||
}
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\n", ns.Metadata.Labels[env.Label], ns.Metadata.Name, exp)
|
||||
}
|
||||
return w.Flush()
|
||||
}
|
||||
@@ -230,6 +230,33 @@ func splitHostArgs(args []string) (host string, rest []string) {
|
||||
return host, rest
|
||||
}
|
||||
|
||||
// resolveRouteTLS turns --tls-secret / --issuer into the ingress.tls value, checking
|
||||
// that an issuer used for a wildcard can solve DNS-01.
|
||||
func resolveRouteTLS(host, secret, issuer string) (string, error) {
|
||||
switch {
|
||||
case secret != "" && issuer != "":
|
||||
return "", fmt.Errorf("use either --tls-secret or --issuer, not both")
|
||||
case secret != "":
|
||||
return "secret:" + secret, nil
|
||||
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)
|
||||
}
|
||||
}
|
||||
return "issuer:" + issuer, nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func ingressAddHost(args []string) error {
|
||||
host, rest := splitHostArgs(args)
|
||||
fs := flag.NewFlagSet("ingress add-host", flag.ExitOnError)
|
||||
@@ -243,28 +270,9 @@ func ingressAddHost(args []string) error {
|
||||
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
|
||||
tls, err := resolveRouteTLS(host, *secret, *issuer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
p, err := loadPlatform()
|
||||
@@ -360,7 +368,7 @@ func hasString(list []string, s string) bool {
|
||||
// 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()
|
||||
p, err := loadPlatformFor(namespace)
|
||||
if err != nil || p == nil || len(p.Ingress.Hosts) == 0 || p.Gateway.Namespace != namespace {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -166,11 +166,15 @@ metadata:
|
||||
`)
|
||||
if oauthSetupName != "" {
|
||||
proxySvc := OAuthProxyServiceName(oauthSetupName)
|
||||
proxyNS, signin := namespace, "https://$host/oauth2/start?rd=$escaped_request_uri"
|
||||
if shared := sharedOAuth(); shared.Host != "" {
|
||||
proxyNS, signin = shared.Namespace, "https://"+shared.Host+"/oauth2/start?rd=https://$host$escaped_request_uri"
|
||||
}
|
||||
b.WriteString(fmt.Sprintf(` nginx.ingress.kubernetes.io/auth-url: "http://%s.%s.svc.cluster.local:4180/oauth2/auth"
|
||||
nginx.ingress.kubernetes.io/auth-signin: "https://$host/oauth2/start?rd=$escaped_request_uri"
|
||||
nginx.ingress.kubernetes.io/auth-signin: "%s"
|
||||
nginx.ingress.kubernetes.io/auth-response-headers: "X-Auth-Request-User,X-Auth-Request-Email,X-Auth-Request-Groups,X-Auth-Request-Preferred-Username"
|
||||
nginx.ingress.kubernetes.io/proxy-buffer-size: "16k"
|
||||
`, proxySvc, namespace))
|
||||
`, proxySvc, proxyNS, signin))
|
||||
}
|
||||
b.WriteString("spec:\n")
|
||||
if cls := resolveIngressClass(); cls != "" {
|
||||
|
||||
@@ -106,6 +106,9 @@ func runDeleteApp(args []string, namespace string) error {
|
||||
}
|
||||
|
||||
func removeOAuthCallbacks(setup string, hosts []string, namespace string) {
|
||||
if sharedOAuth().Host != "" {
|
||||
return // one shared callback; nothing per host to remove
|
||||
}
|
||||
cmName := OAuthSetupConfigMapName(setup)
|
||||
cm, err := GetConfigMapData(cmName, namespace)
|
||||
if err != nil {
|
||||
@@ -146,6 +149,11 @@ func dropAppDatabase(appName string, hosts []string, data map[string]string, nam
|
||||
engine = "postgres"
|
||||
}
|
||||
app := &AppConfig{Hostnames: hosts}
|
||||
e, err := loadEnv(namespace)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
app.Environment, app.envBound = e, true
|
||||
target, op, err := resolveDBTarget(engine, namespace)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/appname"
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/platform"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -27,21 +28,32 @@ Platform setup:
|
||||
[--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]
|
||||
[--namespace zero-scale-system] [--rwx-class X] [--volumes-size 20Gi] [--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: <host|*.domain> [--tls-secret S | --issuer I]
|
||||
ingress remove-host <host>
|
||||
ingress list
|
||||
|
||||
Environments (QA, feature branches) on one cluster:
|
||||
env create <name> Namespace + quota + gateway for an environment; hosts use <app>${ENV_SUFFIX}.<domain>
|
||||
[--ttl 7d] [--namespace N] [--primary] [--replicas 1] [--image I]
|
||||
[--route '*.qa.example.com' --tls-secret S | --issuer I]
|
||||
[--postgres ns/name --postgres-service host:port] [--adopt] [--yes]
|
||||
env delete <name> Drop the env's databases, delete its volumes and namespace [--keep-data] [--force] [--yes]
|
||||
env gc Delete environments past their --ttl [--yes]
|
||||
env list
|
||||
|
||||
Commands:
|
||||
apply Reconcile an app or redirect from a simple 10-line declarative config file
|
||||
oauth-setup <name> Create or update a shared ingress-nginx OAuth2 setup profile
|
||||
[--auth-host auth.apps.example.com: one callback host for every app and environment]
|
||||
status <host> Inspect systemd service status of an app
|
||||
logs <host> Fetch journalctl logs for an app unit
|
||||
list-apps List all registered zero-scale applications
|
||||
delete-app <name> Delete an application ConfigMap; --purge removes its Ingress, Secrets, host entries
|
||||
and OAuth routes and stops it everywhere; --drop-database also drops its database
|
||||
and OAuth routes and stops it everywhere; --drop-database also drops its database,
|
||||
--delete-volumes its volume data
|
||||
upload-binary Upload a local binary directly to platform storage
|
||||
provision-db Provision schema and credentials on shared database operator
|
||||
|
||||
@@ -223,7 +235,19 @@ func main() {
|
||||
groupFlag := oauthFlags.String("group", "", "Allowed Gitea group(s)/org(s) (comma-separated)")
|
||||
hostFlag := oauthFlags.String("host", "", "Optional application hostname(s) to register Redirect URI for")
|
||||
nsFlag := oauthFlags.String("n", namespace, "Target namespace")
|
||||
authHostFlag := oauthFlags.String("auth-host", "", "Serve every app's login from this one callback host (e.g. auth.apps.example.com), with a cookie for its parent domain; recorded in the platform config")
|
||||
_ = oauthFlags.Parse(os.Args[3:])
|
||||
if *authHostFlag != "" {
|
||||
h := strings.ToLower(strings.TrimSpace(*authHostFlag))
|
||||
if err := platform.ValidateHost(h); err != nil || strings.HasPrefix(h, "*.") || strings.Count(h, ".") < 2 {
|
||||
fmt.Fprintf(os.Stderr, "ERROR: --auth-host must be a single host with a parent domain, like auth.apps.example.com\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := updatePlatform(func(c *platform.Config) { c.OAuth = platform.OAuthConfig{Host: h, Namespace: *nsFlag} }); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
var hosts []string
|
||||
if *hostFlag != "" {
|
||||
@@ -257,6 +281,12 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
case "env":
|
||||
if err := runEnv(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)
|
||||
@@ -286,10 +316,18 @@ func handleApply(configPath, expandPath, namespace string) error {
|
||||
|
||||
// 1. Edge Redirect Ingress Mode
|
||||
if redir, ok := cfg.(*RedirectConfig); ok {
|
||||
e, err := loadEnv(namespace)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
redir.SourceHost, redir.TargetHost = e.Expand(redir.SourceHost), e.Expand(redir.TargetHost)
|
||||
if err := e.CheckHost(redir.SourceHost); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("==> Applying Edge NGINX Redirect: https://%s -> https://%s...\n", redir.SourceHost, redir.TargetHost)
|
||||
ingressName := fmt.Sprintf("redirect-%s", redir.SourceHost)
|
||||
ingressName = strings.ReplaceAll(ingressName, ".", "-")
|
||||
err := ApplyRedirectIngress(ingressName, namespace, redir.SourceHost, redir.TargetHost, "zero-scale-gateway")
|
||||
err = ApplyRedirectIngress(ingressName, namespace, redir.SourceHost, redir.TargetHost, "zero-scale-gateway")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to apply redirect ingress: %w", err)
|
||||
}
|
||||
@@ -303,6 +341,9 @@ func handleApply(configPath, expandPath, namespace string) error {
|
||||
return fmt.Errorf("unsupported configuration type")
|
||||
}
|
||||
|
||||
if err := bindEnv(app, namespace); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("==> Reconciling Zero-Scale Application '%s' for host '%s'...\n", app.AppName(), app.CanonicalHost())
|
||||
|
||||
// Step A: Provision database schema, user, and secrets
|
||||
|
||||
@@ -13,8 +13,33 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/platform"
|
||||
)
|
||||
|
||||
// sharedOAuth returns the platform's shared auth host settings; Host is empty when
|
||||
// each app host has its own callback (the original mode).
|
||||
func sharedOAuth() platform.OAuthConfig {
|
||||
if p, err := loadPlatform(); err == nil && p != nil && p.OAuth.Host != "" {
|
||||
o := p.OAuth
|
||||
if o.Namespace == "" {
|
||||
o.Namespace = platformNamespace()
|
||||
}
|
||||
return o
|
||||
}
|
||||
return platform.OAuthConfig{}
|
||||
}
|
||||
|
||||
// checkSharedOAuthHosts makes sure every app host can use the shared auth cookie.
|
||||
func checkSharedOAuthHosts(shared platform.OAuthConfig, hosts []string) error {
|
||||
for _, h := range hosts {
|
||||
if !strings.HasSuffix(h, shared.CookieDomain()) {
|
||||
return fmt.Errorf("host %s is outside %s, so it cannot use the shared auth host %s", h, shared.CookieDomain(), shared.Host)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// OAuthSetupSecretName returns the Kubernetes Secret name for a shared oauth-setup profile.
|
||||
func OAuthSetupSecretName(setupName string) string {
|
||||
return fmt.Sprintf("zero-scale-oauth-%s", strings.ToLower(strings.TrimSpace(setupName)))
|
||||
@@ -202,6 +227,24 @@ func ReconcileOAuthSetup(setupName, oauthURL, oauthGroup string, appHosts []stri
|
||||
oauthURL = strings.TrimRight(strings.TrimSpace(oauthURL), "/")
|
||||
|
||||
requiredCallbacks := collectAllSetupCallbacks(setupName, existingCM, appHosts)
|
||||
shared := sharedOAuth()
|
||||
callbackHosts := appHosts
|
||||
if shared.Host != "" {
|
||||
if err := checkSharedOAuthHosts(shared, appHosts); err != nil {
|
||||
return err
|
||||
}
|
||||
if namespace != shared.Namespace {
|
||||
// Apps in other namespaces (QA, branches) use the one oauth2-proxy behind the shared host.
|
||||
if _, err := GetConfigMapData(cmName, shared.Namespace); err != nil {
|
||||
return fmt.Errorf("oauth-setup '%s' does not exist in %s, where the shared auth host %s is served\n--> Run: zero-scale-ctl oauth-setup %s --url <oauth-url> --auth-host %s -n %s",
|
||||
setupName, shared.Namespace, shared.Host, setupName, shared.Host, shared.Namespace)
|
||||
}
|
||||
fmt.Printf("--> Using shared OAuth2 setup '%s' at https://%s (namespace %s)\n", setupName, shared.Host, shared.Namespace)
|
||||
return nil
|
||||
}
|
||||
requiredCallbacks = []string{fmt.Sprintf("https://%s/oauth2/callback", shared.Host)}
|
||||
callbackHosts = []string{shared.Host}
|
||||
}
|
||||
|
||||
// Credential resolution order:
|
||||
// 1. Environment variables OAUTH_CLIENT_ID & OAUTH_CLIENT_SECRET
|
||||
@@ -348,13 +391,13 @@ func ReconcileOAuthSetup(setupName, oauthURL, oauthGroup string, appHosts []stri
|
||||
}
|
||||
|
||||
// Deploy or update shared oauth2-proxy-<setupName> Deployment & Service
|
||||
if err := deploySharedOAuth2Proxy(setupName, oauthURL, oauthGroup, requiredCallbacks, namespace); err != nil {
|
||||
if err := deploySharedOAuth2Proxy(setupName, oauthURL, oauthGroup, requiredCallbacks, namespace, shared); err != nil {
|
||||
return fmt.Errorf("failed to deploy shared oauth2-proxy for '%s': %w", setupName, err)
|
||||
}
|
||||
|
||||
// If appHosts were provided, apply the /oauth2 Ingress for those hosts
|
||||
if len(appHosts) > 0 {
|
||||
if err := ApplyOAuth2CallbackIngress(setupName, namespace, appHosts); err != nil {
|
||||
// Route /oauth2 on the app hosts (or on the shared auth host) to the proxy
|
||||
if len(callbackHosts) > 0 {
|
||||
if err := ApplyOAuth2CallbackIngress(setupName, namespace, callbackHosts); err != nil {
|
||||
return fmt.Errorf("failed to apply /oauth2 ingress: %w", err)
|
||||
}
|
||||
}
|
||||
@@ -363,7 +406,7 @@ func ReconcileOAuthSetup(setupName, oauthURL, oauthGroup string, appHosts []stri
|
||||
}
|
||||
|
||||
// deploySharedOAuth2Proxy deploys the shared oauth2-proxy Deployment and Service for setupName.
|
||||
func deploySharedOAuth2Proxy(setupName, oauthURL, oauthGroup string, requiredCallbacks []string, namespace string) error {
|
||||
func deploySharedOAuth2Proxy(setupName, oauthURL, oauthGroup string, requiredCallbacks []string, namespace string, shared platform.OAuthConfig) error {
|
||||
svcName := OAuthProxyServiceName(setupName)
|
||||
secName := OAuthSetupSecretName(setupName)
|
||||
|
||||
@@ -424,6 +467,10 @@ func deploySharedOAuth2Proxy(setupName, oauthURL, oauthGroup string, requiredCal
|
||||
}
|
||||
|
||||
extraArgs := ""
|
||||
if shared.Host != "" {
|
||||
// One callback host; the session cookie covers every host under its parent domain.
|
||||
extraArgs += fmt.Sprintf("\n - --redirect-url=https://%s/oauth2/callback\n - --cookie-domain=%s", shared.Host, shared.CookieDomain())
|
||||
}
|
||||
if len(whitelistArgs) > 0 {
|
||||
extraArgs += "\n" + strings.Join(whitelistArgs, "\n")
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/env"
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/platform"
|
||||
)
|
||||
|
||||
@@ -26,11 +27,53 @@ func platformNamespace() string {
|
||||
return platform.DefaultNamespace
|
||||
}
|
||||
|
||||
// loadPlatform reads the platform ConfigMap. It returns nil, nil when none exists yet.
|
||||
func loadPlatform() (*platform.Config, error) {
|
||||
// loadPlatformData reads the platform ConfigMap's data. It returns nil, nil when none exists yet.
|
||||
func loadPlatformData() (map[string]string, error) {
|
||||
out, err := RunKubectl([]string{"get", "configmap", platform.ConfigMapName, "-n", platformNamespace(), "-o", "json"}, "")
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "NotFound") || strings.Contains(err.Error(), "not found") {
|
||||
if isNotFound(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return configMapDataFromJSON(out)
|
||||
}
|
||||
|
||||
// loadPlatform reads the platform ConfigMap. It returns nil, nil when none exists yet.
|
||||
func loadPlatform() (*platform.Config, error) {
|
||||
data, err := loadPlatformData()
|
||||
if err != nil || data == nil {
|
||||
return nil, err
|
||||
}
|
||||
return platform.FromData(data)
|
||||
}
|
||||
|
||||
// loadPlatformFor is the platform config as seen from namespace: an environment's
|
||||
// zero-scale-env overrides (its own DB cluster, its own routes and gateway) applied.
|
||||
func loadPlatformFor(namespace string) (*platform.Config, error) {
|
||||
data, err := loadPlatformData()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e, err := loadEnv(namespace)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if data == nil && e == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if data == nil {
|
||||
data = map[string]string{}
|
||||
}
|
||||
return platform.FromData(e.Overlay(data, namespace))
|
||||
}
|
||||
|
||||
// loadEnv reads namespace's zero-scale-env ConfigMap. It returns nil, nil when the
|
||||
// namespace is not a zero-scale environment, which behaves like the primary env.
|
||||
func loadEnv(namespace string) (*env.Config, error) {
|
||||
out, err := RunKubectl([]string{"get", "configmap", env.ConfigMapName, "-n", namespace, "-o", "json"}, "")
|
||||
if err != nil {
|
||||
if isNotFound(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
@@ -39,12 +82,55 @@ func loadPlatform() (*platform.Config, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return platform.FromData(data)
|
||||
return env.FromData(data)
|
||||
}
|
||||
|
||||
func isNotFound(err error) bool {
|
||||
return strings.Contains(err.Error(), "NotFound") || strings.Contains(err.Error(), "not found")
|
||||
}
|
||||
|
||||
// bindEnv attaches namespace's environment to app and expands ${ENV_SUFFIX} and
|
||||
// ${ENV} in its hosts, args and env values. It is safe to call more than once.
|
||||
func bindEnv(app *AppConfig, namespace string) error {
|
||||
if app.envBound {
|
||||
return nil
|
||||
}
|
||||
e, err := loadEnv(namespace)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading %s in namespace %s: %w", env.ConfigMapName, namespace, err)
|
||||
}
|
||||
for i, h := range app.Hostnames {
|
||||
h = strings.ToLower(e.Expand(h))
|
||||
if strings.Contains(h, "${") {
|
||||
return fmt.Errorf("hostname %q: only ${ENV_SUFFIX} and ${ENV} can be used in hostnames", h)
|
||||
}
|
||||
if err := e.CheckHost(h); err != nil {
|
||||
return err
|
||||
}
|
||||
app.Hostnames[i] = h
|
||||
}
|
||||
app.Args = e.Expand(app.Args)
|
||||
app.Launcher = e.Expand(app.Launcher)
|
||||
app.PreStart = e.Expand(app.PreStart)
|
||||
app.InitCmd = e.Expand(app.InitCmd)
|
||||
for k, v := range app.Env {
|
||||
app.Env[k] = e.Expand(v)
|
||||
}
|
||||
app.Environment = e
|
||||
app.envBound = true
|
||||
if e != nil {
|
||||
fmt.Printf("--> Environment '%s' (namespace %s): hosts %v\n", e.Name, namespace, app.Hostnames)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Owner identifies this app's databases for later cleanup.
|
||||
func (a *AppConfig) Owner(namespace string) platform.Owner {
|
||||
return platform.Owner{App: a.AppName(), Namespace: namespace}
|
||||
o := platform.Owner{App: a.AppName(), Namespace: namespace}
|
||||
if a.Environment.Scoped() {
|
||||
o.Env = a.Environment.Name
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
var warnedNoPlatform bool
|
||||
@@ -52,7 +138,7 @@ var warnedNoPlatform bool
|
||||
// resolveDBTarget picks the database cluster for engine: the platform ConfigMap when
|
||||
// present, otherwise the pre-ConfigMap defaults (CNPG ha-postgres, shared-mysql).
|
||||
func resolveDBTarget(engine, namespace string) (*platform.DBTarget, *platform.Operator, error) {
|
||||
p, err := loadPlatform()
|
||||
p, err := loadPlatformFor(namespace)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("reading platform config: %w", err)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: zero-scale-gateway
|
||||
namespace: default
|
||||
labels:
|
||||
app: zero-scale-gateway
|
||||
app.kubernetes.io/name: zero-scale-gateway
|
||||
|
||||
@@ -2,7 +2,6 @@ apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: zero-scale-kstat
|
||||
namespace: default
|
||||
labels:
|
||||
app: zero-scale-gateway
|
||||
app.kubernetes.io/name: zero-scale-kstat
|
||||
|
||||
@@ -2,7 +2,6 @@ apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: zero-scale-gateway
|
||||
namespace: default
|
||||
labels:
|
||||
app: zero-scale-gateway
|
||||
app.kubernetes.io/name: zero-scale-gateway
|
||||
|
||||
25
deploy/kustomization.yaml
Normal file
25
deploy/kustomization.yaml
Normal file
@@ -0,0 +1,25 @@
|
||||
# Core gateway resources for one namespace. Pick the namespace here (or with
|
||||
# 'kustomize edit set namespace qa') and apply with: kubectl apply -k deploy/
|
||||
# The RoleBinding subject follows the namespace automatically.
|
||||
#
|
||||
# 'zero-scale-ctl gateway install' and 'zero-scale-ctl env create' render an HA
|
||||
# version of these (replicas, PDB, spread) and are the recommended path.
|
||||
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||
kind: Kustomization
|
||||
namespace: default
|
||||
resources:
|
||||
- rbac.yaml
|
||||
- pvc.yaml
|
||||
- deployment.yaml
|
||||
- service.yaml
|
||||
replacements:
|
||||
- source:
|
||||
kind: ServiceAccount
|
||||
name: zero-scale-gateway
|
||||
fieldPath: metadata.namespace
|
||||
targets:
|
||||
- select:
|
||||
kind: RoleBinding
|
||||
name: zero-scale-gateway-binding
|
||||
fieldPaths:
|
||||
- subjects.[name=zero-scale-gateway].namespace
|
||||
@@ -2,7 +2,6 @@ apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: zero-scale-binaries-pvc
|
||||
namespace: default
|
||||
labels:
|
||||
app.kubernetes.io/name: zero-scale-gateway
|
||||
app.kubernetes.io/part-of: zero-scale-platform
|
||||
|
||||
@@ -2,7 +2,6 @@ apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: zero-scale-gateway
|
||||
namespace: default
|
||||
labels:
|
||||
app.kubernetes.io/name: zero-scale-gateway
|
||||
app.kubernetes.io/part-of: zero-scale-platform
|
||||
@@ -11,7 +10,6 @@ apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: Role
|
||||
metadata:
|
||||
name: zero-scale-gateway-role
|
||||
namespace: default
|
||||
labels:
|
||||
app.kubernetes.io/name: zero-scale-gateway
|
||||
app.kubernetes.io/part-of: zero-scale-platform
|
||||
@@ -25,7 +23,6 @@ apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: RoleBinding
|
||||
metadata:
|
||||
name: zero-scale-gateway-binding
|
||||
namespace: default
|
||||
labels:
|
||||
app.kubernetes.io/name: zero-scale-gateway
|
||||
app.kubernetes.io/part-of: zero-scale-platform
|
||||
|
||||
@@ -2,7 +2,6 @@ apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: zero-scale-gateway
|
||||
namespace: default
|
||||
labels:
|
||||
app: zero-scale-gateway
|
||||
app.kubernetes.io/name: zero-scale-gateway
|
||||
|
||||
@@ -2,7 +2,6 @@ apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: shared-mysql-pvc
|
||||
namespace: default
|
||||
labels:
|
||||
app: shared-mysql
|
||||
app.kubernetes.io/part-of: zero-scale-platform
|
||||
@@ -18,7 +17,6 @@ apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: shared-mysql
|
||||
namespace: default
|
||||
labels:
|
||||
app: shared-mysql
|
||||
app.kubernetes.io/part-of: zero-scale-platform
|
||||
@@ -36,7 +34,6 @@ apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: shared-mysql
|
||||
namespace: default
|
||||
labels:
|
||||
app: shared-mysql
|
||||
app.kubernetes.io/part-of: zero-scale-platform
|
||||
@@ -104,7 +101,6 @@ apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: shared-redis
|
||||
namespace: default
|
||||
labels:
|
||||
app: shared-redis
|
||||
app.kubernetes.io/part-of: zero-scale-platform
|
||||
@@ -122,7 +118,6 @@ apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: shared-redis
|
||||
namespace: default
|
||||
labels:
|
||||
app: shared-redis
|
||||
app.kubernetes.io/part-of: zero-scale-platform
|
||||
|
||||
296
internal/env/env.go
vendored
Normal file
296
internal/env/env.go
vendored
Normal file
@@ -0,0 +1,296 @@
|
||||
// Package env describes a zero-scale environment: a namespace with its own
|
||||
// gateway (prod, qa, a feature branch) sharing the cluster's HA databases and
|
||||
// storage. Its settings live in the namespace's zero-scale-env ConfigMap.
|
||||
package env
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.fairfaxmedia.net/open-cream-cheese/zero-scale-platform/internal/platform"
|
||||
)
|
||||
|
||||
// ConfigMapName is the per-namespace environment ConfigMap.
|
||||
const ConfigMapName = "zero-scale-env"
|
||||
|
||||
// Label marks a namespace as a zero-scale environment; its value is the env name.
|
||||
const Label = "zero-scale.io/env"
|
||||
|
||||
// ExpiresAnnotation holds the RFC 3339 time after which 'env gc' deletes the environment.
|
||||
const ExpiresAnnotation = "zero-scale.io/expires"
|
||||
|
||||
// MaxNameLen leaves room for the app name in env-scoped MySQL user names (32 characters max).
|
||||
const MaxNameLen = 16
|
||||
|
||||
var nameRe = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`)
|
||||
|
||||
// Config is one environment.
|
||||
type Config struct {
|
||||
Name string
|
||||
Primary bool // the primary env (prod) uses unsuffixed hosts and the original DB names
|
||||
Created time.Time // zero when unknown
|
||||
Expires time.Time // zero means no TTL
|
||||
// Overrides are platform keys (postgres.*, mysql.*, redis.service, ingress.*)
|
||||
// that replace the cluster-wide value for this environment.
|
||||
Overrides map[string]string
|
||||
}
|
||||
|
||||
// ValidateName checks an environment name.
|
||||
func ValidateName(name string) error {
|
||||
if len(name) == 0 || len(name) > MaxNameLen || !nameRe.MatchString(name) {
|
||||
return fmt.Errorf("environment name %q must be 1-%d characters of [a-z0-9-], starting and ending with a letter or digit", name, MaxNameLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Suffix is what ${ENV_SUFFIX} expands to: "" for the primary env, "-<name>" otherwise.
|
||||
func (c *Config) Suffix() string {
|
||||
if c == nil || c.Primary {
|
||||
return ""
|
||||
}
|
||||
return "-" + c.Name
|
||||
}
|
||||
|
||||
// Scoped reports whether names (hosts, databases) carry this env's name.
|
||||
func (c *Config) Scoped() bool {
|
||||
return c != nil && !c.Primary
|
||||
}
|
||||
|
||||
// Expand replaces ${ENV_SUFFIX} and ${ENV} in s. A nil config is the primary env.
|
||||
func (c *Config) Expand(s string) string {
|
||||
name := ""
|
||||
if c != nil {
|
||||
name = c.Name
|
||||
}
|
||||
return strings.NewReplacer("${ENV_SUFFIX}", c.Suffix(), "${ENV}", name).Replace(s)
|
||||
}
|
||||
|
||||
// CheckHost makes sure a scoped env only claims hosts that carry its suffix or fall
|
||||
// under its own routes, so two environments never fight over one host in the
|
||||
// ingress controller.
|
||||
func (c *Config) CheckHost(host string) error {
|
||||
if !c.Scoped() || platform.HostCovered(host, c.Routes()) {
|
||||
return nil
|
||||
}
|
||||
label := strings.Split(host, ".")[0]
|
||||
if strings.HasPrefix(host, "*.") || !strings.HasSuffix(label, c.Suffix()) {
|
||||
return fmt.Errorf("host %q is not specific to environment %q; write it as <name>${ENV_SUFFIX}.<domain> so it expands to <name>%s.<domain>", host, c.Name, c.Suffix())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Routes are the env's own routed hosts and wildcards (ingress.hosts override).
|
||||
func (c *Config) Routes() []string {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
for _, h := range strings.Split(c.Overrides["ingress.hosts"], ",") {
|
||||
if h = strings.TrimSpace(h); h != "" {
|
||||
out = append(out, h)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Expired reports whether the env's TTL has passed.
|
||||
func (c *Config) Expired(now time.Time) bool {
|
||||
return !c.Expires.IsZero() && now.After(c.Expires)
|
||||
}
|
||||
|
||||
// ParseTTL reads durations like 7d, 36h or 90m. "0" or "" means no TTL.
|
||||
func ParseTTL(s string) (time.Duration, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" || s == "0" {
|
||||
return 0, nil
|
||||
}
|
||||
if strings.HasSuffix(s, "d") {
|
||||
n, err := strconv.Atoi(strings.TrimSuffix(s, "d"))
|
||||
if err != nil || n <= 0 {
|
||||
return 0, fmt.Errorf("invalid TTL %q", s)
|
||||
}
|
||||
return time.Duration(n) * 24 * time.Hour, nil
|
||||
}
|
||||
d, err := time.ParseDuration(s)
|
||||
if err != nil || d <= 0 {
|
||||
return 0, fmt.Errorf("invalid TTL %q (use e.g. 7d, 36h)", s)
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// ToData renders the env ConfigMap data.
|
||||
func (c *Config) ToData() map[string]string {
|
||||
d := map[string]string{"env.name": c.Name}
|
||||
if c.Primary {
|
||||
d["env.primary"] = "true"
|
||||
}
|
||||
if !c.Created.IsZero() {
|
||||
d["env.created"] = c.Created.UTC().Format(time.RFC3339)
|
||||
}
|
||||
if !c.Expires.IsZero() {
|
||||
d["env.expires"] = c.Expires.UTC().Format(time.RFC3339)
|
||||
}
|
||||
for k, v := range c.Overrides {
|
||||
d[k] = v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// overridable are the platform keys an environment may replace.
|
||||
var overridable = []string{"postgres.", "mysql.", "redis.", "ingress."}
|
||||
|
||||
// FromData parses the env ConfigMap data.
|
||||
func FromData(d map[string]string) (*Config, error) {
|
||||
c := &Config{Name: d["env.name"], Primary: d["env.primary"] == "true", Overrides: map[string]string{}}
|
||||
if err := ValidateName(c.Name); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", ConfigMapName, err)
|
||||
}
|
||||
for key, dst := range map[string]*time.Time{"env.created": &c.Created, "env.expires": &c.Expires} {
|
||||
if v := d[key]; v != "" {
|
||||
t, err := time.Parse(time.RFC3339, v)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %s: %w", ConfigMapName, key, err)
|
||||
}
|
||||
*dst = t
|
||||
}
|
||||
}
|
||||
for k, v := range d {
|
||||
for _, p := range overridable {
|
||||
if strings.HasPrefix(k, p) {
|
||||
c.Overrides[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Overlay returns the platform ConfigMap data as seen from this environment's
|
||||
// namespace: the env's overrides win, and routes and the gateway are the env's
|
||||
// own, so a scoped env never inherits prod's wildcard route.
|
||||
func (c *Config) Overlay(platformData map[string]string, namespace string) map[string]string {
|
||||
out := map[string]string{}
|
||||
for k, v := range platformData {
|
||||
out[k] = v
|
||||
}
|
||||
if c == nil {
|
||||
return out
|
||||
}
|
||||
if c.Scoped() {
|
||||
for _, k := range []string{"ingress.hosts", "ingress.tls", "gateway.managedBy"} {
|
||||
delete(out, k)
|
||||
}
|
||||
out["gateway.namespace"] = namespace
|
||||
out["gateway.service"] = "zero-scale-gateway"
|
||||
}
|
||||
for _, prefix := range []string{"postgres.", "mysql."} {
|
||||
// A DB override replaces the whole target, never a mix of two clusters.
|
||||
if hasPrefix(c.Overrides, prefix) {
|
||||
for k := range out {
|
||||
if strings.HasPrefix(k, prefix) {
|
||||
delete(out, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for k, v := range c.Overrides {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func hasPrefix(m map[string]string, prefix string) bool {
|
||||
for k := range m {
|
||||
if strings.HasPrefix(k, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// DBNames returns the database and user names for an app. Unscoped envs keep the
|
||||
// original db_<app>_<sha8> form so existing databases are found again; scoped envs
|
||||
// use db_<env>_<app>_<sha8>, with the app part shortened so the user name fits
|
||||
// MySQL's 32-character limit.
|
||||
func (c *Config) DBNames(app, hostHash string) (db, user string) {
|
||||
if !c.Scoped() {
|
||||
return fmt.Sprintf("db_%s_%s", app, hostHash), fmt.Sprintf("u_%s_%s", app, hostHash)
|
||||
}
|
||||
e := strings.ReplaceAll(c.Name, "-", "_")
|
||||
if max := 32 - len("u___") - len(e) - len(hostHash); len(app) > max {
|
||||
app = app[:max]
|
||||
}
|
||||
return fmt.Sprintf("db_%s_%s_%s", e, app, hostHash), fmt.Sprintf("u_%s_%s_%s", e, app, hostHash)
|
||||
}
|
||||
|
||||
// Manifest renders the namespace (labelled and annotated), a ResourceQuota on object
|
||||
// counts and storage, and the env ConfigMap.
|
||||
func (c *Config) Manifest(namespace string, quota Quota) string {
|
||||
annotations := ""
|
||||
if !c.Expires.IsZero() {
|
||||
annotations = fmt.Sprintf("\n annotations:\n %s: %q", ExpiresAnnotation, c.Expires.UTC().Format(time.RFC3339))
|
||||
}
|
||||
var data strings.Builder
|
||||
d := c.ToData()
|
||||
for _, k := range sortedKeys(d) {
|
||||
fmt.Fprintf(&data, " %s: %q\n", k, d[k])
|
||||
}
|
||||
return fmt.Sprintf(`apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: %[1]s
|
||||
labels:
|
||||
%[2]s: %[3]s
|
||||
app.kubernetes.io/part-of: zero-scale-platform
|
||||
app.kubernetes.io/managed-by: zero-scale-ctl%[4]s
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: ResourceQuota
|
||||
metadata:
|
||||
name: zero-scale-env
|
||||
namespace: %[1]s
|
||||
labels:
|
||||
app.kubernetes.io/part-of: zero-scale-platform
|
||||
app.kubernetes.io/managed-by: zero-scale-ctl
|
||||
spec:
|
||||
hard:
|
||||
pods: "%[5]d"
|
||||
persistentvolumeclaims: "%[6]d"
|
||||
requests.storage: %[7]s
|
||||
services.loadbalancers: "0"
|
||||
services.nodeports: "0"
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: %[8]s
|
||||
namespace: %[1]s
|
||||
labels:
|
||||
app.kubernetes.io/part-of: zero-scale-platform
|
||||
app.kubernetes.io/managed-by: zero-scale-ctl
|
||||
data:
|
||||
%[9]s`, namespace, Label, c.Name, annotations, quota.Pods, quota.PVCs, quota.Storage, ConfigMapName, data.String())
|
||||
}
|
||||
|
||||
// Quota limits what one environment can claim. It counts objects and storage only,
|
||||
// so pods without resource requests (the gateway) are still admitted.
|
||||
type Quota struct {
|
||||
Pods int
|
||||
PVCs int
|
||||
Storage string
|
||||
}
|
||||
|
||||
// DefaultQuota fits a gateway, an oauth2-proxy and a little headroom.
|
||||
var DefaultQuota = Quota{Pods: 10, PVCs: 4, Storage: "100Gi"}
|
||||
|
||||
func sortedKeys(m map[string]string) []string {
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
142
internal/env/env_test.go
vendored
Normal file
142
internal/env/env_test.go
vendored
Normal file
@@ -0,0 +1,142 @@
|
||||
package env
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestValidateName(t *testing.T) {
|
||||
for _, ok := range []string{"qa", "feat-x", "pr-1234", "a"} {
|
||||
if err := ValidateName(ok); err != nil {
|
||||
t.Errorf("%q: %v", ok, err)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"", "QA", "-qa", "qa-", "feat_x", "a-very-long-branch-name"} {
|
||||
if ValidateName(bad) == nil {
|
||||
t.Errorf("%q should be rejected", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpandAndCheckHost(t *testing.T) {
|
||||
var prod *Config
|
||||
if got := prod.Expand("fdm${ENV_SUFFIX}.apps.example.com"); got != "fdm.apps.example.com" {
|
||||
t.Errorf("no env: %s", got)
|
||||
}
|
||||
primary := &Config{Name: "prod", Primary: true}
|
||||
if got := primary.Expand("fdm${ENV_SUFFIX}.apps.example.com"); got != "fdm.apps.example.com" {
|
||||
t.Errorf("primary: %s", got)
|
||||
}
|
||||
qa := &Config{Name: "qa"}
|
||||
if got := qa.Expand("fdm${ENV_SUFFIX}.apps.example.com"); got != "fdm-qa.apps.example.com" {
|
||||
t.Errorf("qa: %s", got)
|
||||
}
|
||||
if got := qa.Expand("https://${ENV}.example.com"); got != "https://qa.example.com" {
|
||||
t.Errorf("qa ${ENV}: %s", got)
|
||||
}
|
||||
if err := qa.CheckHost("fdm-qa.apps.example.com"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
for _, h := range []string{"fdm.apps.example.com", "*.apps.example.com", "qa.example.com"} {
|
||||
if qa.CheckHost(h) == nil {
|
||||
t.Errorf("%s must be rejected in qa", h)
|
||||
}
|
||||
}
|
||||
routed := &Config{Name: "qa", Overrides: map[string]string{"ingress.hosts": "*.qa.apps.example.com"}}
|
||||
if routed.CheckHost("fdm.qa.apps.example.com") != nil || routed.CheckHost("fdm.apps.example.com") == nil {
|
||||
t.Error("hosts under the env's own wildcard are allowed, others not")
|
||||
}
|
||||
if primary.CheckHost("fdm.apps.example.com") != nil {
|
||||
t.Error("primary may use any host")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTTL(t *testing.T) {
|
||||
cases := map[string]time.Duration{"": 0, "0": 0, "7d": 7 * 24 * time.Hour, "36h": 36 * time.Hour}
|
||||
for in, want := range cases {
|
||||
if got, err := ParseTTL(in); err != nil || got != want {
|
||||
t.Errorf("%q: %v %v", in, got, err)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"x", "-1d", "0d", "-3h"} {
|
||||
if _, err := ParseTTL(bad); err == nil {
|
||||
t.Errorf("%q should fail", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDBNames(t *testing.T) {
|
||||
db, user := (*Config)(nil).DBNames("fdm", "1234abcd")
|
||||
if db != "db_fdm_1234abcd" || user != "u_fdm_1234abcd" {
|
||||
t.Errorf("unscoped: %s %s", db, user)
|
||||
}
|
||||
db, user = (&Config{Name: "prod", Primary: true}).DBNames("fdm", "1234abcd")
|
||||
if db != "db_fdm_1234abcd" {
|
||||
t.Errorf("primary must keep the original names: %s", db)
|
||||
}
|
||||
db, user = (&Config{Name: "feat-x"}).DBNames("fdmfeatx", "1234abcd")
|
||||
if db != "db_feat_x_fdmfeatx_1234abcd" || user != "u_feat_x_fdmfeatx_1234abcd" {
|
||||
t.Errorf("scoped: %s %s", db, user)
|
||||
}
|
||||
_, user = (&Config{Name: "abcdefghijklmnop"}).DBNames("averyveryverylongappname", "1234abcd")
|
||||
if len(user) > 32 {
|
||||
t.Errorf("user %s is %d chars", user, len(user))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoundTripAndOverlay(t *testing.T) {
|
||||
exp := time.Date(2026, 11, 3, 0, 0, 0, 0, time.UTC)
|
||||
c := &Config{Name: "qa", Expires: exp, Overrides: map[string]string{"postgres.operator": "cnpg", "postgres.cluster": "qa-db/pg", "postgres.rwService": "pg-rw.qa-db.svc:5432"}}
|
||||
back, err := FromData(c.ToData())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if back.Name != "qa" || !back.Expires.Equal(exp) || back.Overrides["postgres.cluster"] != "qa-db/pg" {
|
||||
t.Errorf("round trip: %+v", back)
|
||||
}
|
||||
if !back.Expired(exp.Add(time.Second)) || back.Expired(exp.Add(-time.Second)) {
|
||||
t.Error("Expired")
|
||||
}
|
||||
|
||||
plat := map[string]string{
|
||||
"postgres.operator": "zalando", "postgres.cluster": "db/main", "postgres.rwService": "main.db.svc:5432", "postgres.adminSecret": "x",
|
||||
"ingress.hosts": "*.apps.example.com", "ingress.tls": "*.apps.example.com=secret:wild", "ingress.class": "nginx",
|
||||
"gateway.namespace": "zero-scale-system", "storage.rwxClass": "longhorn-ha-rwx",
|
||||
}
|
||||
got := back.Overlay(plat, "qa")
|
||||
if got["postgres.cluster"] != "qa-db/pg" || got["postgres.adminSecret"] != "" {
|
||||
t.Errorf("DB override must replace the whole target: %v", got)
|
||||
}
|
||||
if got["ingress.hosts"] != "" || got["gateway.namespace"] != "qa" || got["ingress.class"] != "nginx" || got["storage.rwxClass"] != "longhorn-ha-rwx" {
|
||||
t.Errorf("overlay: %v", got)
|
||||
}
|
||||
if (&Config{Name: "prod", Primary: true}).Overlay(plat, "prod")["ingress.hosts"] == "" {
|
||||
t.Error("the primary env keeps the platform routes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifest(t *testing.T) {
|
||||
c := &Config{Name: "feat-x", Expires: time.Date(2026, 11, 3, 0, 0, 0, 0, time.UTC)}
|
||||
m := c.Manifest("zs-feat-x", DefaultQuota)
|
||||
var kinds []string
|
||||
for _, doc := range strings.Split(m, "\n---\n") {
|
||||
for _, line := range strings.Split(doc, "\n") {
|
||||
if strings.HasPrefix(line, "kind: ") {
|
||||
kinds = append(kinds, strings.TrimPrefix(line, "kind: "))
|
||||
}
|
||||
}
|
||||
}
|
||||
if os.Getenv("DUMP_MANIFESTS") != "" {
|
||||
os.WriteFile(os.Getenv("DUMP_MANIFESTS")+"/env.yaml", []byte(m), 0644)
|
||||
}
|
||||
if strings.Join(kinds, ",") != "Namespace,ResourceQuota,ConfigMap" {
|
||||
t.Errorf("kinds %v", kinds)
|
||||
}
|
||||
for _, want := range []string{"zero-scale.io/env: feat-x", `zero-scale.io/expires: "2026-11-03T00:00:00Z"`, `env.name: "feat-x"`} {
|
||||
if !strings.Contains(m, want) {
|
||||
t.Errorf("missing %q in\n%s", want, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,23 @@ type Config struct {
|
||||
Redis string // host:port
|
||||
Ingress IngressConfig
|
||||
Gateway GatewayConfig
|
||||
OAuth OAuthConfig
|
||||
}
|
||||
|
||||
// OAuthConfig, when Host is set, puts every OAuth-protected app behind one callback
|
||||
// host (auth.apps.example.com) served by the oauth2-proxy in Namespace, with a cookie
|
||||
// shared across the parent domain. New hosts then need no provider changes.
|
||||
type OAuthConfig struct {
|
||||
Host string
|
||||
Namespace string
|
||||
}
|
||||
|
||||
// CookieDomain is the parent domain of the shared auth host (".apps.example.com").
|
||||
func (o OAuthConfig) CookieDomain() string {
|
||||
if i := strings.Index(o.Host, "."); i >= 0 {
|
||||
return o.Host[i:]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// StorageConfig names the HA storage classes.
|
||||
@@ -115,6 +132,8 @@ func (c *Config) ToData() map[string]string {
|
||||
set("gateway.namespace", c.Gateway.Namespace)
|
||||
set("gateway.service", c.Gateway.Service)
|
||||
set("gateway.managedBy", c.Gateway.ManagedBy)
|
||||
set("oauth.host", c.OAuth.Host)
|
||||
set("oauth.namespace", c.OAuth.Namespace)
|
||||
return d
|
||||
}
|
||||
|
||||
@@ -128,6 +147,7 @@ func FromData(d map[string]string) (*Config, error) {
|
||||
Redis: d["redis.service"],
|
||||
Ingress: IngressConfig{Class: d["ingress.class"]},
|
||||
Gateway: GatewayConfig{Namespace: d["gateway.namespace"], Service: d["gateway.service"], ManagedBy: d["gateway.managedBy"]},
|
||||
OAuth: OAuthConfig{Host: d["oauth.host"], Namespace: d["oauth.namespace"]},
|
||||
}
|
||||
for _, h := range strings.Split(d["ingress.hosts"], ",") {
|
||||
if h = strings.TrimSpace(h); h != "" {
|
||||
|
||||
Reference in New Issue
Block a user