diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fa6a405..bffd4cf 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -13,8 +13,11 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: "1.22" - - run: go test ./... + go-version-file: go.mod + - name: gofmt + run: test -z "$(gofmt -l .)" || (gofmt -l . && exit 1) + - run: go vet ./... + - run: go test -race ./... build: needs: test @@ -25,6 +28,9 @@ jobs: - goos: linux goarch: amd64 suffix: "" + - goos: linux + goarch: arm64 + suffix: "" - goos: darwin goarch: amd64 suffix: "" @@ -41,13 +47,13 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: "1.22" + go-version-file: go.mod - name: Build env: CGO_ENABLED: "0" GOOS: ${{ matrix.goos }} GOARCH: ${{ matrix.goarch }} - run: go build -ldflags="-s -w" -o ct-${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.suffix }} ./cmd/ct + run: go build -ldflags="-s -w -X github.com/cloudticon/ct/internal/cli.version=dev-${{ github.sha }}" -o ct-${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.suffix }} ./cmd/ct - uses: actions/upload-artifact@v4 with: name: ct-${{ matrix.goos }}-${{ matrix.goarch }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9fba70e..5dfe09c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,8 +11,11 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: "1.22" - - run: go test ./... + go-version-file: go.mod + - name: gofmt + run: test -z "$(gofmt -l .)" || (gofmt -l . && exit 1) + - run: go vet ./... + - run: go test -race ./... release: needs: test @@ -25,6 +28,9 @@ jobs: - goos: linux goarch: amd64 suffix: "" + - goos: linux + goarch: arm64 + suffix: "" - goos: darwin goarch: amd64 suffix: "" @@ -41,13 +47,13 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: - go-version: "1.22" + go-version-file: go.mod - name: Build env: CGO_ENABLED: "0" GOOS: ${{ matrix.goos }} GOARCH: ${{ matrix.goarch }} - run: go build -ldflags="-s -w" -o ct-${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.suffix }} ./cmd/ct + run: go build -ldflags="-s -w -X github.com/cloudticon/ct/internal/cli.version=${{ github.ref_name }}" -o ct-${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.suffix }} ./cmd/ct - uses: softprops/action-gh-release@v2 with: files: ct-${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.suffix }} diff --git a/README.md b/README.md index d2a501f..2e0128a 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,37 @@ -# ct — Kubernetes manifests from code +# ct — Kubernetes packages in TypeScript, checked before they ship -[![Build](https://github.com/cloudticon/ctts/actions/workflows/build.yml/badge.svg)](https://github.com/cloudticon/ctts/actions/workflows/build.yml) -[![Release](https://github.com/cloudticon/ctts/actions/workflows/release.yml/badge.svg)](https://github.com/cloudticon/ctts/actions/workflows/release.yml) -[![Go Version](https://img.shields.io/github/go-mod/go-version/cloudticon/ctts)](https://github.com/cloudticon/ctts) -[![License](https://img.shields.io/github/license/cloudticon/ctts)](https://github.com/cloudticon/ctts/blob/master/LICENSE) +[![Build](https://github.com/cloudticon/ct/actions/workflows/build.yml/badge.svg)](https://github.com/cloudticon/ct/actions/workflows/build.yml) +[![Release](https://github.com/cloudticon/ct/actions/workflows/release.yml/badge.svg)](https://github.com/cloudticon/ct/actions/workflows/release.yml) +[![Go Version](https://img.shields.io/github/go-mod/go-version/cloudticon/ct)](https://github.com/cloudticon/ct) +[![License](https://img.shields.io/github/license/cloudticon/ct)](https://github.com/cloudticon/ct/blob/master/LICENSE) -> **⚠️ Beta** — `ct` is under active development. APIs, CLI flags, and file formats may change between releases. Feedback and bug reports are welcome! +> **⚠️ Beta.** `ct` is under active development. APIs, CLI flags and file formats may change between releases. Feedback and bug reports are welcome. -`ct` generates Kubernetes YAML/JSON manifests from `.ct` definitions. Write real code (loops, conditionals, cross-references) instead of templating languages. +`ct` replaces Helm with real code and fast, precise feedback. You describe a release in TypeScript (`main.ct`), and `ct` renders it, **validates every object against the Kubernetes API before anything reaches a cluster**, and applies it with inventory-based pruning. Every error points at the line of your code that caused it, in plain text or JSON. That tight loop is what humans and AI coding agents both need. -`ct dev` mode is inspired by [DevSpace](https://devspace.sh): fast inner-loop development directly against Kubernetes workloads. +```bash +ct init # main.ct, values.json, AGENTS.md +ct template my-app . -n prod # render + validate -> YAML +ct apply my-app . -n prod # render + validate + server-side apply + prune +``` -**Documentation:** [cloudticon.com](https://cloudticon.com/) +**Documentation:** [cloudticon.com](https://cloudticon.com/) · **Direction:** [RFC: ct as an AI-friendly Helm replacement](docs/rfc/ai-friendly-helm-replacement.md) -## Features +## Why ct -- **TypeScript syntax** — full language power: variables, loops, conditionals, type safety -- **Registration model** — each helper call (`deployment()`, `service()`, …) registers a resource and returns it for cross-references -- **URL imports** — packages resolved directly from URLs, no local config needed -- **Values** — `values.json` or `values.yaml` with `--set` overrides, like Helm -- **Multi-env** — separate values files per environment (ArgoCD-style) -- **Custom resources** — `resource()` factory for CRDs and any K8s object, with optional schema -- **High-level helpers** — `deployment`, `service`, `configMap`, `secret`, `ingress`, `statefulSet`, `daemonSet`, `namespace` -- **IDE support** — `ct types` generates `.d.ts` files for autocomplete and type checking -- **Embeddable engine** — public Go API in `pkg/` for building tools on top of ct -- **Zero dependencies for users** — single Go binary, no Node.js required -- **Zero config** — no `tsconfig.json`, no generated directories, just your code and values +- **Code, not text templates.** Loops, conditionals, functions and imports instead of `{{ range }}`, `nindent` and `_helpers.tpl`. Objects are values, so cross-references (`web.spec.selector.matchLabels`) can't drift. +- **Checked before it ships.** Built-in kinds are decoded strictly against the Kubernetes API types, plus the admission rules the API server enforces (selector vs. template labels, Job `restartPolicy`, port names, volume sources, ...). Unknown fields, wrong types, `core/v1`-style apiVersions and removed APIs fail at render time, not in Argo CD. +- **Errors point at your code.** Bundles carry source maps, and `ct` records where each object was registered, so diagnostics read `main.ct:12:3: Deployment "web": spec.replicas: ...`. Add `--error-format json` for tools and agents. +- **Releases without ceremony.** `ct apply` does server-side apply in Helm's install order (namespaces and CRDs first), tracks an inventory per release, and prunes objects you removed from the code. +- **Agent-ready.** `ct init` writes an `AGENTS.md`, output is deterministic, every diagnostic has a stable code, and git never blocks on a password prompt. +- **One static binary.** No Node.js, no Tiller, no plugins. ## Install One-line install (Linux/macOS): ```bash -curl -fsSL https://cloudtion.com/install.sh | sudo sh +curl -fsSL https://cloudticon.com/install.sh | sudo sh ``` Via `go install`: @@ -52,459 +51,339 @@ go build -ldflags="-s -w" -o ct ./cmd/ct ## Quick start ```bash -# Initialize a project in the current directory -ct init - -# Edit main.ct and values.json, then render: -ct template my-app . --namespace production - -# JSON output -ct template my-app . --namespace production --output json - -# Override values -ct template my-app . --namespace production --set replicas=5 - -# Explicit values file (useful for multi-env) -ct template my-app . --namespace staging --values values-staging.json - -# Render from GitHub source -ct template my-app github.com/cloudticon/my-app@v1.0 --namespace staging +ct init # scaffold in the current directory (or: ct init myproject) +ct template my-app . -n production # render to YAML (validated) +ct template my-app . -n production -o json +ct template my-app . -f values.yaml -f values-prod.yaml --set replicas=5 +ct template my-app github.com/acme/my-app@v1.0 -n staging # render a remote source ``` -## User project layout - -After `ct init`, you get: +After `ct init`: ``` myproject/ - main.ct # manifest definitions (TypeScript syntax) - values.json # configurable values + main.ct # the release, in TypeScript + values.json # settings, read as Values. + AGENTS.md # how coding agents should work on this project ``` -That's it — no generated directories, no config files. +No `tsconfig.json`, no generated directories, no `node_modules`. -**Multi-env project (ArgoCD):** +## Writing main.ct -``` -myproject/ - main.ct # code - values.json # default values - values-prod.json # production overrides - values-staging.yaml # staging (YAML also supported) -``` +### High level: factories -## Example: main.ct +[`k8s-factories`](https://github.com/cloudticon/k8s-factories) builds common shapes for you. `webApp` registers a Deployment and a Service (plus HPA, PVCs and Ingress/VirtualService when asked): ```typescript -import { deployment } from "github.com/cloudticon/k8s@master"; -import { service } from "github.com/cloudticon/k8s@master"; +import { webApp } from "github.com/cloudticon/k8s-factories@master"; -const app = deployment({ - name: "web-app", +webApp({ + name: "api", image: Values.image, + port: 8080, replicas: Values.replicas, - ports: [{ containerPort: 8080 }], -}); - -// Cross-reference — use app.metadata.name, zero typos -service({ - name: "web-app-svc", - selector: { app: app.metadata.name }, - ports: [{ port: 80, targetPort: 8080 }], + probes: "/healthz", }); ``` -## Example: values.json - -```json -{ - "image": "nginx:1.25", - "replicas": 3 -} -``` +### Primitives: the Kubernetes API, typed -Values can also be YAML: +[`cloudticon/k8s`](https://github.com/cloudticon/k8s) has one typed factory per kind. Each call registers the object and returns it: -```yaml -# values.yaml -image: nginx:1.25 -replicas: 3 -domain: app.example.com -``` +```typescript +import { deployment, service, configMap } from "github.com/cloudticon/k8s@master"; + +const labels = { app: "web" }; + +const web = deployment({ + name: "web", + selector: { matchLabels: labels }, + template: { + metadata: { labels }, + spec: { + containers: [{ name: "web", image: Values.image, ports: [{ name: "http", containerPort: 8080 }] }], + }, + }, +}); -## Output +service({ + name: "web", + selector: web.spec.selector.matchLabels, // cross-reference, not a copy + ports: [{ port: 80, targetPort: "http" }], +}); -```bash -$ ct template my-app . --namespace production +configMap({ name: "web-config", data: { LOG_LEVEL: Values.logLevel ?? "info" } }); ``` -```yaml -apiVersion: apps/v1 -kind: Deployment -metadata: - labels: - app: web-app - name: web-app - namespace: production -spec: - replicas: 3 - selector: - matchLabels: - app: web-app - template: - metadata: - labels: - app: web-app - spec: - containers: - - image: nginx:1.25 - name: web-app - ports: - - containerPort: 8080 ---- -apiVersion: v1 -kind: Service -metadata: - name: web-app-svc - namespace: production -spec: - ports: - - port: 80 - targetPort: 8080 - selector: - app: web-app -``` +### Loops, conditionals, local helpers -## Conditional resources +It's TypeScript, so reuse is a function and an import: ```typescript +// lib/worker.ct import { deployment } from "github.com/cloudticon/k8s@master"; -import { ingress } from "github.com/cloudticon/k8s@master"; -deployment({ name: "api", image: Values.image }); - -if (Values.enableIngress) { - ingress({ - name: "api-ingress", - host: Values.domain, - serviceName: "api-svc", +export function worker(w: { name: string; queue: string; replicas?: number }) { + const labels = { app: `worker-${w.name}` }; + return deployment({ + name: `worker-${w.name}`, + replicas: w.replicas ?? 1, + selector: { matchLabels: labels }, + template: { + metadata: { labels }, + spec: { containers: [{ name: "worker", image: Values.image, args: ["--queue", w.queue] }] }, + }, }); } ``` -## Loops - ```typescript -import { deployment } from "github.com/cloudticon/k8s@master"; +// main.ct +import { worker } from "./lib/worker"; // .ct/.ts extensions are optional -for (const worker of Values.workers) { - deployment({ - name: `worker-${worker.name}`, - image: worker.image, - replicas: worker.replicas, - }); -} +for (const w of Values.workers) worker(w); ``` -## Custom resources (CRDs) +### Custom resources -Use `resource()` to define your own typed resource factory: +`resource()` defines a typed factory for any CRD. Cluster-scoped kinds get no namespace: ```typescript import { resource, z } from "github.com/cloudticon/k8s@master"; const redis = resource("redis.redis.opstreelabs.in/v1beta2", "Redis", { - spec: { - image: z.string(), - exporter: z.boolean().optional(), - }, -}); - -redis({ - name: "my-redis", - image: "redis:7.2", - exporter: true, + spec: { kubernetesConfig: z.object({ image: z.string() }) }, }); -``` - -For cluster-scoped resources, set `scope`: - -```typescript -import { resource, z } from "github.com/cloudticon/k8s@master"; - -const clusterPolicy = resource("kyverno.io/v1", "ClusterPolicy", { - scope: "Cluster", - spec: { - validationFailureAction: z.enum(["Enforce", "Audit"]), - }, -}); - -clusterPolicy({ - name: "require-labels", - validationFailureAction: "Enforce", -}); -``` - -## Available helpers - -| Function | Description | -| ------------ | ------------------------------------------------------------- | -| `deployment` | Deployment (apps/v1) | -| `statefulSet`| StatefulSet (apps/v1) | -| `daemonSet` | DaemonSet (apps/v1) | -| `service` | Service (core/v1) | -| `configMap` | ConfigMap (core/v1) | -| `secret` | Secret (core/v1) | -| `namespace` | Namespace (core/v1) | -| `ingress` | Ingress (networking/v1) | -| `resource` | Factory for custom/CRD resources (`scope: "Cluster"` option) | -| `z` | Schema builder for `resource()` spec definitions | - -All helpers are imported from `github.com/cloudticon/k8s@`. - -## URL imports -Packages are referenced directly via URL in import statements: - -```typescript -import { deployment } from "github.com/cloudticon/k8s@master"; +if (Values.redis?.enabled) { + redis({ name: "cache", kubernetesConfig: { image: "redis:7.2" } }); +} ``` -URL format: `github.com/{owner}/{repo}@{version}` +### Imports -- `{version}` is a git tag or branch name -- Packages are downloaded on first use and cached in `~/.ct/cache/` -- Subsequent runs work offline from cache +- Packages are git repositories, imported by URL: `github.com/{owner}/{repo}@{tag-or-branch}`, optionally with a sub-path (`github.com/acme/lib@v2/presets/ha`). Other hosts work too (`git.example.com/group/team/repo@v1`). +- Packages are cloned on first use into `~/.ct/cache/` and reused offline. `--no-cache` re-downloads the source and every imported package (useful for branch versions like `@master`). +- Private repositories need git credentials for https (e.g. `gh auth setup-git`). `ct` never waits on a password prompt. +- There is no npm, and no `async`/`await`: rendering is synchronous. -Use `--no-cache` to force re-download when using remote sources: +### Globals -```bash -ct template my-app github.com/cloudticon/my-app@main --namespace prod --no-cache -``` +| Global | Value | +| --- | --- | +| `Values` | merged values (files + `--set`) | +| `Release.name` | the release name given to `ct template`/`ct apply` | +| `Release.namespace` | the `-n` namespace (empty if not set) | -## IDE support — `ct types` +## Values -Generate TypeScript type definitions for IDE autocomplete and type checking: +- Without `-f`, `ct` uses the first of `values.json`, `values.yaml`, `values.yml` in the project. +- `-f` is repeatable. Files deep-merge left to right: objects merge key by key, everything else (including arrays) is replaced, like Helm. A single `-f` replaces the auto-detected file. A relative `-f` that isn't in the working directory is looked up in the project, so remote sources can use their own `values-prod.yaml`. +- `--set key.nested=value` overrides one value. `true`/`false`/`null` and numbers are typed, but only when the number round-trips: `1.10`, `1.0` and `0123` stay strings. `--set-string` always sets a string. Escape dots in keys with a backslash: `--set 'annotations.nginx\.ingress\.kubernetes\.io/rewrite-target=/'`. ```bash -# Generate types for the current project -ct types . - -# Custom output directory -ct types . --output ./types - -# Include operator globals (getStatus, setStatus, fetch, log, Env) -ct types . --operator +ct template shop . -f values.yaml -f values-prod.yaml --set-string image.tag=1.10 ``` -Generated files: +## Validation and errors -| File | Contents | -| -------------- | ------------------------------------------------------ | -| `values.d.ts` | `CtValues` interface inferred from `values.json`/YAML | -| `globals.d.ts` | `declare const Values: CtValues` + operator globals | +`ct template` and `ct apply` validate every rendered object before printing or applying anything: -The command also resolves and caches URL imports so IDE resolution works offline. +- **built-in kinds** are decoded strictly into the Kubernetes API types: unknown fields, wrong types and wrong apiVersions are reported with their field path, all in one run; +- **removed APIs** (e.g. `extensions/v1beta1` Ingress, `batch/v1beta1` CronJob) name their replacement; +- **admission rules** the API server enforces: valid names and labels, selector matching the template labels, containers with name and image, at most one source per volume, `volumeMounts` referencing a volume (or a StatefulSet volume claim), Jobs with `restartPolicy: OnFailure|Never`, Services with ports, Ingress paths with `pathType`, base64 `Secret.data`, TLS secrets with `tls.crt`/`tls.key`, CRD names equal to `.`, and more; +- **duplicates**: registering the same object twice is an error, not a silent last-write-wins. -Output directory defaults to `~/.ct/types/`. The path is printed to stdout so tools (e.g. VS Code extension) can consume it. +Custom resources get metadata checks; their schemas live in their CRDs. -## Apply manifests to cluster — `ct apply` - -Render and apply manifests in one step using Kubernetes server-side apply. - -```bash -# Render + apply resources from main.ct -ct apply my-app . +Each diagnostic names the code location that registered the object: -# Apply with explicit namespace and context -ct apply my-app . --namespace development --context staging - -# Override values while applying -ct apply my-app . --values values-staging.yaml --set replicas=2 - -# Optionally print applied output -ct apply my-app . --output yaml - -# Apply from GitHub source -ct apply my-app github.com/cloudticon/my-app@v1.0 --namespace staging - -# Create namespace automatically when it does not exist -ct apply my-app . --namespace development --create-namespace +``` +$ ct template web . -n prod +Error: 3 problems +main.ct:3:11: Deployment "web" (namespace "prod"): spec.replicas: Invalid value: expected an integer, got string [invalid-value] +main.ct:3:11: Deployment "web" (namespace "prod"): spec.template.metadata.labels: Invalid value: {"app":"website"}: `selector` does not match template `labels` [invalid-value] +main.ct:3:11: Deployment "web" (namespace "prod"): spec.template.spec.containers[0].ports[0].name: Invalid value: "http-metrics-port": must be no more than 15 characters [invalid-value] ``` -`ct apply` is useful when you want one command for both generation and deployment without a separate `kubectl apply`. - -`ct apply` stores inventory per release and prunes orphaned resources that were removed from templates. +Syntax and runtime errors carry positions in your `.ct` files too (bundles have source maps), with the offending line and a stack: -## Delete release — `ct delete` +``` +Error: lib/factory.ct:3:10: Error: name is required [runtime] + at make (lib/factory.ct:3:10) + at main.ct:4:5 +``` -Delete all resources tracked in release inventory: +With `--error-format json`, errors go to stderr as JSON with stable codes (`syntax`, `import`, `async-not-supported`, `runtime`, `timeout`, `duplicate-resource`, `invalid-resource`, `unknown-kind`, `unknown-field`, `invalid-value`, `missing-field`, `namespace-not-found`, or `error` for anything else): -```bash -ct delete my-app --namespace production -ct delete my-app --namespace staging --context staging +```json +{ + "errors": [ + { + "code": "invalid-value", + "message": "Invalid value: expected an integer, got string", + "file": "main.ct", + "line": 3, + "column": 11, + "resource": "Deployment \"web\" (namespace \"prod\")", + "path": "spec.replicas" + } + ] +} ``` -`ct delete` does not require source path or repo URL. It deletes resources based on the latest saved inventory. +Validation uses the Kubernetes types `ct` was built with. If your cluster is newer and you use a field `ct` doesn't know yet, pass `--validate=false`. -## List releases — `ct list` - -List all releases tracked by ct inventory in a namespace or across all namespaces. +## Releases: apply, list, delete ```bash -# List releases in current/default namespace context -ct list - -# List releases in selected namespace -ct list --namespace production +ct apply my-app . -n production # render + validate + apply + prune +ct apply my-app . -n development --create-namespace +ct apply my-app . -n production --context prod-cluster -o yaml +ct apply my-app github.com/acme/my-app@v1.0 -n staging -# List releases from all namespaces -ct list --all-namespaces +ct list -n production # releases in a namespace +ct list -A -o json # all namespaces, structured -# Structured output -ct list --all-namespaces --output json +ct delete my-app -n production # deletes what the inventory tracks; no source needed ``` +`ct apply` uses server-side apply (field manager `ct`) in Helm's install order. Custom resources wait until the API server serves a CRD applied in the same run. Each release keeps an inventory in the ConfigMap `ct-inventory-` (labels `app.kubernetes.io/managed-by=ct`, `ct.cloudticon.com/instance=`); objects that disappear from the code are pruned on the next apply, including objects created by an apply that failed halfway. + ## Development mode — `ct dev` -Run live development workflows directly on cluster workloads from `dev.ct` (DevSpace-inspired flow). +Run live development workflows directly on cluster workloads from `dev.ct` (DevSpace-inspired): ```bash -# Start dev mode from current directory -ct dev +ct dev # from the current directory +ct dev --env-file .env.dev # custom env file ("" to skip) +ct dev --context staging +ct dev --delete # remove the dev release and exit +``` -# Use a custom env file -ct dev --env-file .env.dev +`ct dev` executes `dev.ct`, applies the resources, then starts port forwarding, log streaming, file sync and a terminal for each dev target. -# Skip env file loading -ct dev --env-file "" +## IDE support — `ct types` -# Use a specific kubeconfig context -ct dev --context staging +```bash +ct types . # values.d.ts + globals.d.ts, path printed to stdout +ct types . --output ./types +ct types . --dev # dev.d.ts for dev.ct ``` -`ct dev` executes `dev.ct`, applies rendered resources, then starts development features such as port forwarding, logs, and sync according to your dev targets. +`values.d.ts` holds a `CtValues` interface inferred from your values file; `globals.d.ts` declares `Values` and `Release`. The command also caches URL imports so the editor resolves them offline. ## CLI reference ``` -ct init [flags] - -d, --dir string project directory (default ".") +Global flags: + --error-format string how to print errors: text, or json for tools and AI agents (default "text") + +ct init [dir] [flags] + -d, --dir string project directory (default ".") + --force overwrite an existing main.ct and values.json (AGENTS.md is never overwritten) ct template [flags] - --no-cache skip cache, re-download remote source - -n, --namespace string default namespace for resources - -f, --values string path to values file (JSON or YAML, overrides auto-detect) - -o, --output string output format: yaml or json (default "yaml") - --set stringArray override values (e.g. --set replicas=5) + -n, --namespace string default namespace for resources + -o, --output string output format: yaml or json (default "yaml") + -f, --values stringArray values file; repeat to deep-merge left to right + --set stringArray override a value (typed) + --set-string stringArray override a value as a string + --validate check objects against the Kubernetes API (default true) + --no-cache re-download the source and imported packages ct apply [flags] - --no-cache skip cache, re-download remote source - -n, --namespace string target namespace for resources - -f, --values string path to values file (JSON or YAML, overrides auto-detect) - -o, --output string output format: yaml or json (default: no output) - --set stringArray override values (e.g. --set replicas=5) - --context string kubeconfig context to use - --create-namespace create namespace if it does not exist + (template flags, with -o defaulting to no output, plus) + --context string kubeconfig context to use + --create-namespace create the namespace if it does not exist ct delete [flags] - -n, --namespace string namespace where release inventory is stored - --context string kubeconfig context to use + -n, --namespace string namespace holding the release inventory + --context string kubeconfig context to use ct list [flags] - -n, --namespace string namespace to search releases in + -n, --namespace string namespace to search -A, --all-namespaces list releases across all namespaces --context string kubeconfig context to use - -o, --output string output format: table, yaml, or json (default "table") + -o, --output string table, json or yaml (default table) ct dev [flags] - --env-file string path to .env file (empty to skip) (default ".env") - --context string kubeconfig context - --name string release name used for labels/inventory (default "dev") - --create-namespace create namespace automatically before apply (default true) - --delete delete dev resources from inventory and exit + --env-file string .env file to load ("" to skip) (default ".env") + --context string kubeconfig context + --name string release name for labels/inventory (default "dev") + --create-namespace create the namespace before apply (default true) + --delete delete the dev release and exit ct types [dir] [flags] - --output string output directory (default ~/.ct/types/) - --operator include operator globals (getStatus, setStatus, fetch, log, Env) - --dev generate dev.d.ts for dev.ct IDE support + --output string output directory (default ~/.ct/types/) + --operator include operator globals (getStatus, setStatus, fetch, log, Env) + --dev generate dev.d.ts for dev.ct ``` -`ct template` auto-detects values files in order: `values.json`, `values.yaml`, `values.yml`. Use `--values` to override. - ## How it works -1. **esbuild** bundles `main.ct` + URL-imported packages into a single IIFE JS file -2. URL imports are resolved from `~/.ct/cache/` (downloaded on first use via `git clone`) -3. An esbuild plugin rejects `async`/`await` at bundle time — the Goja runtime is synchronous -4. **Goja** (pure Go JS engine) executes the bundle — each helper call pushes a resource to a global registry -5. `Values` object is injected as a global from the loaded JSON/YAML values file -6. **Post-processing** applies default namespace (from `--namespace`), skips cluster-scoped resources, removes nil fields -7. **Serializer** outputs YAML or JSON +1. **esbuild** bundles `main.ct` and its imports into one script with an inline source map. URL imports resolve from `~/.ct/cache/`; `async`/`await` is rejected by the parser with a precise location. +2. **Goja**, a JavaScript engine written in Go, runs the bundle with `Values` and `Release` as globals. Each factory call pushes an object to `__ct_resources`; `ct` records the call site of each push. Runaway scripts stop after a minute with a stack trace. +3. **Normalize**: objects are copied out of the JS runtime, `null`/`undefined` fields are dropped the way `JSON.stringify` drops `undefined` (empty objects and arrays like `emptyDir: {}` or `ingress: [{}]` are kept), and namespaced objects without a namespace get `-n`. +4. **Validate** against the Kubernetes API types and admission rules; reject duplicates. +5. **Order** objects like Helm does, add the release labels, and print YAML/JSON or server-side-apply them. -No Node.js runtime needed — everything runs inside the Go binary. +No Node.js runtime is needed. Everything runs inside the Go binary. ## Using ct as a Go library -The engine, cache, and package resolver are exported as public Go packages under `pkg/`: - ```go import ( - "github.com/cloudticon/ctts/pkg/engine" - "github.com/cloudticon/ctts/pkg/cache" - "github.com/cloudticon/ctts/pkg/packages" + "github.com/cloudticon/ct/pkg/engine" + "github.com/cloudticon/ct/pkg/validate" ) -``` - -### Engine — bundle and execute -```go -transpiler := engine.NewTranspiler("/path/to/project") -jsCode, err := transpiler.Bundle("main.ct") +tr := engine.NewTranspiler("/path/to/project") +js, err := tr.Bundle("/path/to/project/main.ct") -values, err := engine.LoadValuesFile("values.json", []string{"replicas=5"}) +values, err := engine.LoadValues(engine.ValuesOpts{ + Files: []string{"values.yaml", "values-prod.yaml"}, + Set: []string{"replicas=5"}, +}) -resources, err := engine.Execute(engine.ExecuteOpts{ - JSCode: jsCode, +result, err := engine.Render(engine.ExecuteOpts{ + JSCode: js, Values: values, Namespace: "production", + SourceDir: "/path/to/project", }) -``` -### Cache — resolve URL imports to local paths - -```go -localDir, err := cache.Resolve("https://github.com/cloudticon/k8s@master") +problems := validate.Resources(result.Resources, result.Origin) // diag.List ``` -### Packages — parse imports and sync dependencies - -```go -imports, err := packages.ParseImports("main.ct") -err = packages.SyncPackages("/path/to/project") -``` +Errors from `Bundle`, `Render` and `validate.Resources` are `diag.List` values: structured diagnostics with code, position, resource, field path and hint. ## Source layout ``` cmd/ct/ CLI entry point internal/ - cli/ commands: init, template, types + cli/ commands + dev/ ct dev runner output/ YAML/JSON serializer - scaffold/ ct init scaffolding + scaffold/ ct init pkg/ - engine/ transpiler (esbuild) + runtime (Goja) + values loader - cache/ URL import → local cache resolver - packages/ git client, import parser, dependency sync + engine/ transpiler (esbuild) + runtime (Goja) + values + diag/ structured diagnostics + manifest/ pure object transforms: cleaning, namespaces, ordering, duplicates + validate/ Kubernetes schema and admission checks + k8s/ cluster port: apply, inventory, prune, exec, port-forward, logs + sync/ ct dev file sync + cache/ URL import cache + packages/ import parsing and dependency sync ``` ## Development ```bash -# Run all tests -go test ./... - -# Build (strip debug symbols for smaller binary) +go test -race ./... +go vet ./... go build -ldflags="-s -w" -o ct ./cmd/ct ``` diff --git a/cmd/ct/main.go b/cmd/ct/main.go index 877c754..2b28174 100644 --- a/cmd/ct/main.go +++ b/cmd/ct/main.go @@ -1,17 +1,16 @@ package main import ( - "fmt" "log" "os" - "github.com/cloudticon/ctts/internal/cli" + "github.com/cloudticon/ct/internal/cli" ) func main() { log.SetFlags(0) if err := cli.Execute(); err != nil { - fmt.Fprintln(os.Stderr, err) + cli.PrintError(os.Stderr, err) os.Exit(1) } } diff --git a/docs/rfc/ai-friendly-helm-replacement.md b/docs/rfc/ai-friendly-helm-replacement.md new file mode 100644 index 0000000..bc383a1 --- /dev/null +++ b/docs/rfc/ai-friendly-helm-replacement.md @@ -0,0 +1,120 @@ +# RFC: ct as an AI-friendly replacement for Helm + +- **Status:** draft for discussion +- **Scope:** ct CLI, `cloudticon/k8s`, `cloudticon/k8s-factories`, docs and skills + +## Summary + +ct should be the tool you reach for instead of Helm, and the one an AI coding agent can drive without a human translating cluster errors back into code. Two goals follow: + +1. **Feedback in one loop.** A mistake in a `.ct` file must fail at render time, with the file, line, object and field that caused it, in a form both people and programs can act on. +2. **Helm parity where it matters.** Values layering, install order, diff, wait, rollback, hooks, pinned dependencies, and a way to consume existing charts. Without these, teams can't drop Helm. + +ct already has the right base for both: a real language, typed primitives, a single binary, and inventory-based apply with pruning. This RFC makes the two goals explicit, records what landed with it, and orders the rest. + +## Why + +AI agents now write a large share of deployment code, and they work in tight loops: edit, run, read the error, fix. Helm makes each turn of that loop long and noisy: + +- It templates YAML as text, so whitespace (`nindent`) and quoting bugs are common, and errors refer to rendered YAML lines (`error converting YAML to JSON: line 37`) rather than the template. +- Most mistakes surface only at apply time, on the cluster, far from their cause. Some never surface: unknown fields are dropped with a warning nobody reads. +- Values have no types unless someone maintains a `values.schema.json`. +- Errors are prose meant for humans, with no stable codes or positions. + +Agents are good at fixing a precise error and bad at guessing where an imprecise one came from. The same is true of people. A tool that gives precise errors helps both. + +## Principles + +1. **Fail at render time, not on the cluster.** Anything the API server would reject should be caught by `ct template`. +2. **Every error points at code.** File, line and column in the user's `.ct` sources; the object and field path; a stable code; a hint. Available as JSON. +3. **Deterministic, boring output.** Same input, same bytes: Helm's install order, 2-space YAML, no hidden defaults. +4. **One obvious way.** Explicit values layering, imports by URL and version, no npm, no async. +5. **Safe releases by default.** Inventory and prune today; diff, wait and rollback next. +6. **Projects explain themselves.** Agents get the commands and rules from the project (`AGENTS.md`), not from guesswork. + +## What landed with this RFC + +The branch that introduces this document fixes correctness bugs and lays the base for principles 1–3 and 6: + +| Area | Change | +| --- | --- | +| Validation | `pkg/validate`: strict decoding of built-in kinds into client-go types (unknown fields, wrong types, wrong or removed apiVersions) plus the admission rules the API server enforces. On by default; `--validate=false` skips it. | +| Diagnostics | `pkg/diag`: structured errors with code, position, resource, field path and hint; `--error-format json`. Inline source maps make Goja stack traces point at `.ct` lines; each object remembers the call chain that registered it. | +| Rendering | Only `null`/`undefined` fields are dropped, like `JSON.stringify` (before, empty objects and arrays vanished too, turning a NetworkPolicy `ingress: [{}]` from allow-all into deny-all); objects are copied out of the JS runtime so shared objects can't leak namespaces; cluster-scoped kinds get no namespace; duplicate objects are an error; Helm install order (by API group and kind) for `template` and `apply`; apply waits for CRDs created in the same run; bounded call stack and a 1-minute render timeout. | +| Values | Repeatable `-f` with Helm-style deep merge, `--set` without a values file, number typing that keeps `1.10` a string, `--set-string`, escaped dots in keys. | +| Bundling | Parser-based async detection (no false positives on comments, strings or names like `async-worker`), extensionless `.ct` imports, import errors with hints. | +| Releases | Prune compares objects by API group, kind, effective namespace and name (it used to delete the object it had just applied after an `apiVersion` or `-n` change); the inventory keeps objects created by a failed apply; delete runs in reverse install order; `ct list` counts only inventories. | +| Cache | Atomic installs, package URLs and import paths can't escape the cache, `--no-cache` refreshes imported packages, no git password prompts, custom git hosts. | +| Project | Module path `github.com/cloudticon/ct` (so `go install` works); `ct init` never overwrites files, scaffolds a valid app and writes `AGENTS.md`. | + +In `cloudticon/k8s` (separate branch): core kinds use `apiVersion: v1` instead of `core/v1`; ConfigMap, Secret, ServiceAccount, RBAC and StorageClass fields render at the top level instead of under `spec`; cluster-scoped kinds carry the scope marker. ct's new validation would have caught all three. + +## Gap analysis: what replacing Helm takes + +| Helm capability | ct today | Plan | +| --- | --- | --- | +| Templating | TypeScript | done | +| Values files, `--set`, `--set-string` | done | `--set-json`; typed values (below) | +| `values.schema.json` | — | **Typed values**: validate the merged values against a type declared in the project, report the values file line | +| Install order | done | — | +| Lint / kubeconform | built-in kinds | **CRD schemas**: validate custom resources against the schemas the factory library already carries (`openAPISchema`) and, with cluster access, the CRDs on the cluster | +| `helm diff` (plugin) | — | **`ct diff`** via server-side dry-run apply against live objects | +| `--dry-run=server` | — | `ct apply --dry-run=server` | +| `--wait`, `--atomic` | — | **`ct apply --wait`**: rollout status, and on failure the events and last log lines of failing pods as diagnostics | +| History, `rollback` | latest inventory only | Keep the last N rendered releases (compressed) next to the inventory; `ct history`, `ct rollback` | +| Hooks (pre/post install Jobs) | — | `hook()` helper: Jobs run and awaited before or after apply (migrations) | +| `Chart.lock`, dependency pinning | `@branch`/`@tag`, no lock | **`ct.lock`** with commit SHAs, `ct update`; SHA versions in URLs | +| Chart repos / OCI | git repos | git is the registry for now | +| Consuming third-party charts | — | **`helmChart({ repo, chart, version, values })`** renders a chart into ct objects, so one ct release can include upstream software (ingress-nginx, cert-manager, ...) | +| `helm test`, helm-unittest | — | **`ct test`** for `*.test.ct` files with `describe`/`it`/`assertResource` (the ct skills already document this API) | +| `--show-only` | — | `ct template -k Kind/name` filter | + +## Roadmap + +Each phase is usable on its own. The bold rows in the table above are the priority items. + +### Phase 1: trustworthy render (in progress) + +- Done: built-in validation, diagnostics, source maps, JSON errors. +- **CRD validation** from library schemas. Acceptance: a typo in a cert-manager `Certificate` spec fails `ct template` with a field path. +- **Typed values**. Acceptance: a wrong type in `values-prod.yaml` fails with the values file and key, before rendering. +- **`ct check`**: render and validate every environment (each `values-*.yaml`) in one command; exit code and JSON summary. +- **`ct explain [.field]`**: field docs and types offline, for agents that can't reach a cluster. + +### Phase 2: safe releases + +- `ct diff`, `ct apply --dry-run=server`. +- `ct apply --wait` with failure diagnostics (events, container states, last log lines). +- History and `ct rollback`. +- Hooks for pre/post-apply Jobs. + +### Phase 3: reproducibility and ecosystem + +- `ct.lock` and `ct update`; SHA-pinned imports. +- `helmChart()` for third-party charts. +- `ct test`. + +### Phase 4: agent integration + +- `ct mcp`: an MCP server exposing render, validate, explain and diff as tools. +- Ship the ct skills (`cloudticon/skills`) with the repo and keep them tested against the CLI. +- `llms.txt` on cloudticon.com generated from the docs. + +## Ecosystem work + +- **`cloudticon/k8s`**: int-or-string fields (`targetPort`, `maxSurge`, PDB `minAvailable`) and quantities are typed as `string`, so valid numbers need casts. The built-ins come from Kubernetes 1.26 schemas, so newer fields aren't typed. Generated `.default()`s make required fields optional and add `undefined` to array elements. `z` builders aren't marked side-effect free, so importing one core kind keeps all of them. The generator should emit the committed format (local imports, `/* @__PURE__ */`). +- **Docs** (cloudticon.com): the Helm comparison promises compile-time Zod validation, which ct doesn't do; validation now happens at render time and the page should say so. Examples use shorthands the library doesn't have (`deployment({ image })`, Ingress `service`/`port` on paths). The pattern docs should cover `topLevel`. +- **Skills**: `ct` says `Release.Name` doesn't exist (it's `Release.name`) and that `--values` doesn't merge (repeated `-f` now does); `ct-create-factories` documents `ct test`, which the CLI doesn't have yet. + +## Non-goals + +- Cloud resources or general infrastructure as code (Pulumi and Terraform already do that). +- A chart repository or OCI registry in the near term: a git repository with tags is the package. +- Compatibility with Go templates. + +## Open questions + +1. **Kubernetes version skew.** Validation uses the Kubernetes types ct was built with. Should ct also accept `--kube-version`, or read the server version during `ct apply`, to avoid false "unknown field" errors on newer clusters? +2. **Helm charts.** Embed the Helm SDK (bigger binary, no external tool) or call the `helm` binary when present? +3. **Release history storage.** One Secret per revision (Helm's approach, 1 MiB limit each) or a compressed ring in the inventory ConfigMap? +4. **Lockfile format.** JSON `ct.lock` next to `main.ct`, keyed by import URL, holding the commit SHA and a content hash? diff --git a/go.mod b/go.mod index 8477ef4..85b67b8 100644 --- a/go.mod +++ b/go.mod @@ -1,31 +1,35 @@ -module github.com/cloudticon/ctts +module github.com/cloudticon/ct go 1.25.0 require ( + github.com/bmatcuk/doublestar/v4 v4.10.0 github.com/dop251/goja v0.0.0-20260311135729-065cd970411c github.com/evanw/esbuild v0.27.4 + github.com/fatih/color v1.19.0 + github.com/fsnotify/fsnotify v1.9.0 + github.com/go-logr/logr v1.4.3 + github.com/pterm/pterm v0.12.83 github.com/spf13/cobra v1.10.2 github.com/stretchr/testify v1.11.1 + golang.org/x/term v0.40.0 gopkg.in/yaml.v3 v3.0.1 + k8s.io/api v0.35.3 k8s.io/apimachinery v0.35.3 k8s.io/client-go v0.35.3 + k8s.io/klog/v2 v2.130.1 ) require ( atomicgo.dev/cursor v0.2.0 // indirect atomicgo.dev/keyboard v0.2.9 // indirect atomicgo.dev/schedule v0.1.0 // indirect - github.com/bmatcuk/doublestar/v4 v4.10.0 // indirect github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/containerd/console v1.0.5 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dlclark/regexp2 v1.11.4 // indirect github.com/emicklei/go-restful/v3 v3.12.2 // indirect - github.com/fatih/color v1.19.0 // indirect - github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/fxamacker/cbor/v2 v2.9.0 // indirect - github.com/go-logr/logr v1.4.3 // indirect github.com/go-openapi/jsonpointer v0.21.0 // indirect github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.23.0 // indirect @@ -49,7 +53,6 @@ require ( github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/pterm/pterm v0.12.83 // indirect github.com/spf13/pflag v1.0.9 // indirect github.com/x448/float16 v0.8.4 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect @@ -58,14 +61,11 @@ require ( golang.org/x/net v0.47.0 // indirect golang.org/x/oauth2 v0.30.0 // indirect golang.org/x/sys v0.42.0 // indirect - golang.org/x/term v0.40.0 // indirect golang.org/x/text v0.34.0 // indirect golang.org/x/time v0.9.0 // indirect google.golang.org/protobuf v1.36.8 // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect - k8s.io/api v0.35.3 // indirect - k8s.io/klog/v2 v2.130.1 // indirect k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 // indirect k8s.io/utils v0.0.0-20251002143259-bc988d571ff4 // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect diff --git a/go.sum b/go.sum index 998cf55..eed667d 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +atomicgo.dev/assert v0.0.2 h1:FiKeMiZSgRrZsPo9qn/7vmr7mCsh5SZyXY4YGYiYwrg= +atomicgo.dev/assert v0.0.2/go.mod h1:ut4NcI3QDdJtlmAxQULOmA13Gz6e2DWbSAS8RUOmNYQ= atomicgo.dev/cursor v0.2.0 h1:H6XN5alUJ52FZZUkI7AlJbUc1aW38GWZalpYRPpoPOw= atomicgo.dev/cursor v0.2.0/go.mod h1:Lr4ZJB3U7DfPPOkbH7/6TOtJ4vFGHlgj1nc+n900IpU= atomicgo.dev/keyboard v0.2.9 h1:tOsIid3nlPLZ3lwgG8KZMp/SFmr7P0ssEN5JUsm78K8= @@ -11,8 +13,12 @@ github.com/MarvinJWendt/testza v0.2.10/go.mod h1:pd+VWsoGUiFtq+hRKSU1Bktnn+DMCSr github.com/MarvinJWendt/testza v0.2.12/go.mod h1:JOIegYyV7rX+7VZ9r77L/eH6CfJHHzXjB69adAhzZkI= github.com/MarvinJWendt/testza v0.3.0/go.mod h1:eFcL4I0idjtIx8P9C6KkAuLgATNKpX4/2oUqKc6bF2c= github.com/MarvinJWendt/testza v0.4.2/go.mod h1:mSdhXiKH8sg/gQehJ63bINcCKp7RtYewEjXsvsVUPbE= +github.com/MarvinJWendt/testza v0.5.2 h1:53KDo64C1z/h/d/stCYCPY69bt/OSwjq5KpFNwi+zB4= +github.com/MarvinJWendt/testza v0.5.2/go.mod h1:xu53QFE5sCdjtMCKk8YMQ2MnymimEctc4n3EjyIYvEY= github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk= github.com/bmatcuk/doublestar/v4 v4.10.0 h1:zU9WiOla1YA122oLM6i4EXvGW62DvKZVxIe6TYWexEs= github.com/bmatcuk/doublestar/v4 v4.10.0/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= @@ -63,6 +69,8 @@ github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 h1:BHT72Gu3keYf3ZEu2J github.com/google/pprof v0.0.0-20250403155104-27863c87afa6/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gookit/assert v0.1.1 h1:lh3GcawXe/p+cU7ESTZ5Ui3Sm/x8JWpIis4/1aF0mY0= +github.com/gookit/assert v0.1.1/go.mod h1:jS5bmIVQZTIwk42uXl4lyj4iaaxx32tqH16CFj0VX2E= github.com/gookit/color v1.4.2/go.mod h1:fqRyamkC1W8uxl+lxCQxOT09l/vYfZ+QeiX3rKQHCoQ= github.com/gookit/color v1.5.0/go.mod h1:43aQb+Zerm/BWh2GnrgOQm7ffz7tvQXEKV6BFMl7wAo= github.com/gookit/color v1.6.0 h1:JjJXBTk1ETNyqyilJhkTXJYYigHG24TM9Xa2M1xAhRA= @@ -78,6 +86,8 @@ github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHm github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.0.10/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c= github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c= +github.com/klauspost/cpuid/v2 v2.2.3 h1:sxCkb+qR91z4vsqw4vGGZlDgPz3G7gjaLyK3V8y70BU= +github.com/klauspost/cpuid/v2 v2.2.3/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= @@ -128,6 +138,7 @@ github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJ github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ= github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= @@ -159,11 +170,12 @@ go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E= +golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA= -golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w= golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c= +golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= @@ -175,9 +187,8 @@ golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKl golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= -golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -191,8 +202,6 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= -golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= @@ -200,8 +209,6 @@ golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9sn golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= -golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg= golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -209,8 +216,6 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= -golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= @@ -219,9 +224,8 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ= -golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs= golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= +golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc= google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU= diff --git a/internal/cli/apply.go b/internal/cli/apply.go index 7953771..b2f19ca 100644 --- a/internal/cli/apply.go +++ b/internal/cli/apply.go @@ -2,11 +2,14 @@ package cli import ( "context" + "errors" "fmt" - "github.com/cloudticon/ctts/internal/output" - "github.com/cloudticon/ctts/pkg/k8s" + "github.com/cloudticon/ct/internal/output" + "github.com/cloudticon/ct/pkg/diag" + "github.com/cloudticon/ct/pkg/k8s" "github.com/spf13/cobra" + apierrors "k8s.io/apimachinery/pkg/api/errors" ) type applyOpts struct { @@ -32,10 +35,9 @@ func newApplyCmd() *cobra.Command { } cmd.Flags().StringVarP(&opts.namespace, "namespace", "n", "", "target namespace for resources") - cmd.Flags().StringVarP(&opts.valuesFile, "values", "f", "", "path to values file (JSON or YAML, overrides auto-detect)") cmd.Flags().StringVarP(&opts.outputFmt, "output", "o", "", "output format: yaml or json (default: no output)") - cmd.Flags().StringArrayVar(&opts.setValues, "set", nil, "override values (e.g. --set replicas=5)") - cmd.Flags().BoolVar(&opts.noCache, "no-cache", false, "skip cache, re-download remote source") + addRenderFlags(cmd, &opts.templateOpts) + cmd.Flags().BoolVar(&opts.noCache, "no-cache", false, "re-download the remote source and imported packages instead of using ~/.ct/cache") cmd.Flags().StringVar(&opts.context, "context", "", "kubeconfig context to use") cmd.Flags().BoolVar(&opts.createNamespace, "create-namespace", false, "create namespace if it does not exist") @@ -47,12 +49,16 @@ func init() { } func runApply(cmd *cobra.Command, releaseName, source string, opts applyOpts) error { + if err := validateReleaseName(releaseName); err != nil { + return err + } resolvedDir, err := resolveSourceDirForApply(source, opts.noCache) if err != nil { return err } opts.templateOpts.releaseName = releaseName + opts.templateOpts.sourceURL = remoteSourceURL(source) resources, err := renderResourcesForApply(resolvedDir, opts.templateOpts) if err != nil { return err @@ -70,7 +76,7 @@ func runApply(cmd *cobra.Command, releaseName, source string, opts applyOpts) er } if err := cluster.ApplyRelease(cmd.Context(), opts.namespace, releaseName, resources); err != nil { - return fmt.Errorf("apply failed: %w", err) + return applyError(err) } if opts.outputFmt != "" { @@ -84,6 +90,20 @@ func runApply(cmd *cobra.Command, releaseName, source string, opts applyOpts) er return nil } +// applyError turns common cluster errors into diagnostics with a next step. +func applyError(err error) error { + var status *apierrors.StatusError + if errors.As(err, &status) && apierrors.IsNotFound(err) && status.ErrStatus.Details != nil && + status.ErrStatus.Details.Kind == "namespaces" { + return diag.List{{ + Code: diag.CodeNamespaceNotFound, + Message: fmt.Sprintf("apply failed: %v", err), + Hint: "pass --create-namespace, or register a Namespace object in main.ct", + }} + } + return fmt.Errorf("apply failed: %w", err) +} + func ensureApplyNamespace(ctx context.Context, cluster k8s.Cluster, namespace string, createNamespace bool) error { if !createNamespace || namespace == "" { return nil diff --git a/internal/cli/apply_test.go b/internal/cli/apply_test.go index 65a733e..bc5559a 100644 --- a/internal/cli/apply_test.go +++ b/internal/cli/apply_test.go @@ -4,14 +4,18 @@ import ( "bytes" "context" "errors" + "fmt" "path/filepath" "testing" - "github.com/cloudticon/ctts/internal/scaffold" - "github.com/cloudticon/ctts/pkg/k8s" + "github.com/cloudticon/ct/internal/scaffold" + "github.com/cloudticon/ct/pkg/diag" + "github.com/cloudticon/ct/pkg/k8s" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/runtime/schema" ) func TestApplyCmd_MissingMainCt(t *testing.T) { @@ -78,14 +82,15 @@ func TestApplyCmd_UsageShowsTwoArgs(t *testing.T) { func TestApplyCmd_MissingMainCt_WithReleaseName(t *testing.T) { dir := filepath.Join(t.TempDir(), "project") - require.NoError(t, scaffold.Init(dir)) + _, err := scaffold.Init(dir, scaffold.Options{}) + require.NoError(t, err) cmd := newApplyCmd() cmd.SetArgs([]string{"prod-release", t.TempDir()}) cmd.SetOut(new(bytes.Buffer)) cmd.SetErr(new(bytes.Buffer)) - err := cmd.Execute() + err = cmd.Execute() require.Error(t, err) assert.Contains(t, err.Error(), "entry point not found") } @@ -162,3 +167,19 @@ func TestRunApply_CreatesNamespaceAndAppliesRelease(t *testing.T) { require.True(t, ok, "release labels should be injected onto resource metadata") assert.Equal(t, "my-release", labels["ct.cloudticon.com/instance"]) } + +func TestApplyError_MissingNamespaceGetsHint(t *testing.T) { + notFound := apierrors.NewNotFound(schema.GroupResource{Resource: "namespaces"}, "ghost") + + err := applyError(fmt.Errorf("applying resources: %w", notFound)) + + var list diag.List + require.ErrorAs(t, err, &list) + assert.Equal(t, "namespace-not-found", list[0].Code) + assert.Contains(t, list[0].Hint, "--create-namespace") +} + +func TestApplyError_OtherErrorsPassThrough(t *testing.T) { + err := applyError(errors.New("boom")) + assert.EqualError(t, err, "apply failed: boom") +} diff --git a/internal/cli/cluster.go b/internal/cli/cluster.go index cbebfe4..0a34bad 100644 --- a/internal/cli/cluster.go +++ b/internal/cli/cluster.go @@ -1,6 +1,6 @@ package cli -import "github.com/cloudticon/ctts/pkg/k8s" +import "github.com/cloudticon/ct/pkg/k8s" // newClusterFn is the single seam for constructing a k8s.Cluster from CLI // flags. Tests override this to inject k8stest.NewFake() and exercise diff --git a/internal/cli/delete_test.go b/internal/cli/delete_test.go index 7077347..eaa63d1 100644 --- a/internal/cli/delete_test.go +++ b/internal/cli/delete_test.go @@ -6,7 +6,7 @@ import ( "errors" "testing" - "github.com/cloudticon/ctts/pkg/k8s" + "github.com/cloudticon/ct/pkg/k8s" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/internal/cli/dev.go b/internal/cli/dev.go index 1d679dc..81c7205 100644 --- a/internal/cli/dev.go +++ b/internal/cli/dev.go @@ -1,10 +1,13 @@ package cli import ( + "context" "fmt" "os" + "os/signal" + "syscall" - "github.com/cloudticon/ctts/internal/dev" + "github.com/cloudticon/ct/internal/dev" "github.com/spf13/cobra" ) @@ -49,9 +52,13 @@ func runDev(cmd *cobra.Command, opts devOpts) error { return fmt.Errorf("resolving working directory: %w", err) } - if err := runDevMode(cmd.Context(), dev.RunOpts{ + ctx, stop := devSignalContext(cmd.Context()) + defer stop() + + if err := runDevMode(ctx, dev.RunOpts{ Dir: dir, EnvFile: opts.envFile, + EnvFileRequired: cmd.Flags().Changed("env-file"), KubeCtx: opts.context, ReleaseName: opts.releaseName, Delete: opts.delete, @@ -65,3 +72,19 @@ func runDev(cmd *cobra.Command, opts devOpts) error { return nil } + +// devSignalContext cancels the dev session on Ctrl+C or SIGTERM so it can +// shut down gracefully (stop port-forwards and syncs, restore the terminal). +// Once the context is cancelled the default signal behavior is restored, so +// a second Ctrl+C still kills a session that does not stop. +func devSignalContext(parent context.Context) (context.Context, context.CancelFunc) { + if parent == nil { + parent = context.Background() + } + ctx, stop := signal.NotifyContext(parent, os.Interrupt, syscall.SIGTERM) + go func() { + <-ctx.Done() + stop() + }() + return ctx, stop +} diff --git a/internal/cli/dev_signal_test.go b/internal/cli/dev_signal_test.go new file mode 100644 index 0000000..c1fcf44 --- /dev/null +++ b/internal/cli/dev_signal_test.go @@ -0,0 +1,38 @@ +//go:build !windows + +package cli + +import ( + "context" + "errors" + "syscall" + "testing" + "time" + + "github.com/cloudticon/ct/internal/dev" + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" +) + +// The dev session's graceful shutdown (stop port-forwards, restore the +// terminal, flush) hangs off ctx, but nothing cancelled ctx on Ctrl+C or +// SIGTERM: the process was simply killed, e.g. with the TTY left in raw mode. +func TestRunDev_CancelsContextOnSignal(t *testing.T) { + origRunner := runDevMode + t.Cleanup(func() { runDevMode = origRunner }) + + for _, sig := range []syscall.Signal{syscall.SIGINT, syscall.SIGTERM} { + runDevMode = func(ctx context.Context, _ dev.RunOpts) error { + if err := syscall.Kill(syscall.Getpid(), sig); err != nil { + return err + } + select { + case <-ctx.Done(): + return nil + case <-time.After(2 * time.Second): + return errors.New("context was not cancelled by " + sig.String()) + } + } + require.NoError(t, runDev(&cobra.Command{}, devOpts{})) + } +} diff --git a/internal/cli/dev_test.go b/internal/cli/dev_test.go index a9fa228..3c776fd 100644 --- a/internal/cli/dev_test.go +++ b/internal/cli/dev_test.go @@ -8,7 +8,7 @@ import ( "strings" "testing" - "github.com/cloudticon/ctts/internal/dev" + "github.com/cloudticon/ct/internal/dev" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -88,7 +88,28 @@ func TestRunDev_PassesOptionsToRunner(t *testing.T) { assert.Equal(t, "my-dev", captured.ReleaseName) assert.True(t, captured.Delete) assert.True(t, captured.CreateNamespace) + assert.False(t, captured.EnvFileRequired, "flag not set on the command line: the default .env is optional") assert.Same(t, stdin, captured.Stdin) assert.Same(t, stdout, captured.Stdout) assert.Same(t, stderr, captured.Stderr) } + +// An --env-file given on the command line must exist; only the default +// .env is optional. +func TestDevCmd_ExplicitEnvFileIsRequired(t *testing.T) { + origRunner := runDevMode + t.Cleanup(func() { runDevMode = origRunner }) + var captured dev.RunOpts + runDevMode = func(_ context.Context, opts dev.RunOpts) error { + captured = opts + return nil + } + + cmd := newDevCmd() + cmd.SetArgs([]string{"--env-file", ".env.staging"}) + cmd.SetOut(new(bytes.Buffer)) + cmd.SetErr(new(bytes.Buffer)) + require.NoError(t, cmd.Execute()) + assert.Equal(t, ".env.staging", captured.EnvFile) + assert.True(t, captured.EnvFileRequired) +} diff --git a/internal/cli/init.go b/internal/cli/init.go index c54b797..eaf490d 100644 --- a/internal/cli/init.go +++ b/internal/cli/init.go @@ -2,28 +2,40 @@ package cli import ( "fmt" + "strings" - "github.com/cloudticon/ctts/internal/scaffold" + "github.com/cloudticon/ct/internal/scaffold" "github.com/spf13/cobra" ) func newInitCmd() *cobra.Command { var dir string + var force bool cmd := &cobra.Command{ - Use: "init", + Use: "init [dir]", Short: "Initialize a new ct project", - Long: "Creates main.ct and values.json in the target directory.", + Long: "Creates main.ct, values.json and AGENTS.md (instructions for AI coding agents) in the target directory. An existing main.ct or values.json is kept unless --force is given; an existing AGENTS.md is always kept.", + Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - if err := scaffold.Init(dir); err != nil { + if len(args) == 1 { + if cmd.Flags().Changed("dir") && args[0] != dir { + return fmt.Errorf("give the directory either as an argument or with --dir, not both") + } + dir = args[0] + } + written, err := scaffold.Init(dir, scaffold.Options{Force: force}) + if err != nil { return fmt.Errorf("init failed: %w", err) } - fmt.Fprintf(cmd.OutOrStdout(), "Initialized ct project in %s/\n", dir) + fmt.Fprintf(cmd.OutOrStdout(), "Initialized ct project in %s/ (%s)\n", strings.TrimSuffix(dir, "/"), strings.Join(written, ", ")) + fmt.Fprintf(cmd.OutOrStdout(), "Next: ct template my-app %s -n default\n", dir) return nil }, } cmd.Flags().StringVarP(&dir, "dir", "d", ".", "project directory") + cmd.Flags().BoolVar(&force, "force", false, "overwrite existing files") return cmd } diff --git a/internal/cli/init_test.go b/internal/cli/init_test.go index 8b7f489..d803005 100644 --- a/internal/cli/init_test.go +++ b/internal/cli/init_test.go @@ -44,3 +44,29 @@ func TestInitCmd_DefaultDir(t *testing.T) { assert.FileExists(t, filepath.Join(tmpDir, "main.ct")) assert.FileExists(t, filepath.Join(tmpDir, "values.json")) } + +func TestInitCmd_DoesNotOverwriteExistingProject(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "values.json"), []byte(`{"mine":true}`), 0o644)) + + cmd := newInitCmd() + cmd.SetArgs([]string{"--dir", dir}) + cmd.SetOut(new(bytes.Buffer)) + cmd.SetErr(new(bytes.Buffer)) + + err := cmd.Execute() + require.Error(t, err) + content, _ := os.ReadFile(filepath.Join(dir, "values.json")) + assert.Equal(t, `{"mine":true}`, string(content)) +} + +func TestInitCmd_DirectoryArgument(t *testing.T) { + projectDir := filepath.Join(t.TempDir(), "myproject") + + cmd := newInitCmd() + cmd.SetArgs([]string{projectDir}) + cmd.SetOut(new(bytes.Buffer)) + + require.NoError(t, cmd.Execute()) + assert.FileExists(t, filepath.Join(projectDir, "main.ct")) +} diff --git a/internal/cli/list.go b/internal/cli/list.go index 7bee898..a693562 100644 --- a/internal/cli/list.go +++ b/internal/cli/list.go @@ -4,11 +4,13 @@ import ( "encoding/json" "fmt" "io" + "os" "strings" - "github.com/cloudticon/ctts/pkg/k8s" + "github.com/cloudticon/ct/pkg/k8s" "github.com/pterm/pterm" "github.com/spf13/cobra" + "golang.org/x/term" "gopkg.in/yaml.v3" ) @@ -35,7 +37,7 @@ func newListCmd() *cobra.Command { cmd.Flags().StringVarP(&opts.namespace, "namespace", "n", "", "namespace to search") cmd.Flags().BoolVarP(&opts.allNamespaces, "all-namespaces", "A", false, "list releases across all namespaces") cmd.Flags().StringVar(&opts.context, "context", "", "kubeconfig context to use") - cmd.Flags().StringVarP(&opts.outputFmt, "output", "o", "", "output format: json or yaml (default: table)") + cmd.Flags().StringVarP(&opts.outputFmt, "output", "o", "", "output format: table, json or yaml") return cmd } @@ -56,7 +58,7 @@ func runList(cmd *cobra.Command, opts listOpts) error { } switch strings.ToLower(opts.outputFmt) { - case "": + case "", "table": return writeReleaseTable(cmd.OutOrStdout(), releases) case "json": return writeReleaseJSON(cmd.OutOrStdout(), releases) @@ -68,6 +70,12 @@ func runList(cmd *cobra.Command, opts listOpts) error { } func writeReleaseTable(w io.Writer, releases []k8s.ReleaseInfo) error { + // Colors only for a terminal; pipes, files and agents get plain text. + if isColorTerminal(w) { + pterm.EnableStyling() + } else { + pterm.DisableStyling() + } data := [][]string{{"NAME", "NAMESPACE", "RESOURCES"}} for _, r := range releases { data = append(data, []string{r.Name, r.Namespace, fmt.Sprintf("%d", r.Resources)}) @@ -105,3 +113,8 @@ func writeReleaseYAML(w io.Writer, releases []k8s.ReleaseInfo) error { } return nil } + +func isColorTerminal(w io.Writer) bool { + f, ok := w.(*os.File) + return ok && os.Getenv("NO_COLOR") == "" && term.IsTerminal(int(f.Fd())) +} diff --git a/internal/cli/list_test.go b/internal/cli/list_test.go index a5f2d10..ed25d52 100644 --- a/internal/cli/list_test.go +++ b/internal/cli/list_test.go @@ -6,8 +6,8 @@ import ( "errors" "testing" - "github.com/cloudticon/ctts/pkg/k8s" - "github.com/cloudticon/ctts/pkg/k8s/k8stest" + "github.com/cloudticon/ct/pkg/k8s" + "github.com/cloudticon/ct/pkg/k8s/k8stest" "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -91,11 +91,24 @@ func TestRunList_TableOutput(t *testing.T) { }) require.NoError(t, err) assert.Contains(t, stdout.String(), "NAME") + assert.NotContains(t, stdout.String(), "\x1b[", "no ANSI colors when not writing to a terminal") assert.Contains(t, stdout.String(), "api") // Listing scoped to "prod" namespace excludes "staging". assert.NotContains(t, stdout.String(), "backend") } +func TestRunList_ExplicitTableFormat(t *testing.T) { + fake := withFakeCluster(t) + seedRelease(t, fake, "prod", "api", 3) + + stdout := new(bytes.Buffer) + cmd := &cobra.Command{} + cmd.SetOut(stdout) + + require.NoError(t, runList(cmd, listOpts{namespace: "prod", outputFmt: "table"})) + assert.Contains(t, stdout.String(), "api") +} + func TestRunList_JSONOutput(t *testing.T) { fake := withFakeCluster(t) seedRelease(t, fake, "prod", "api", 2) diff --git a/internal/cli/resolve.go b/internal/cli/resolve.go index d4c9052..2af8942 100644 --- a/internal/cli/resolve.go +++ b/internal/cli/resolve.go @@ -2,10 +2,11 @@ package cli import ( "fmt" + "os" "path/filepath" - "github.com/cloudticon/ctts/pkg/cache" - "github.com/cloudticon/ctts/pkg/packages" + "github.com/cloudticon/ct/pkg/cache" + "github.com/cloudticon/ct/pkg/packages" ) var ( @@ -14,17 +15,12 @@ var ( ) func resolveSourceDir(arg string, noCache bool) (string, error) { - if !packages.IsGitPackage(arg) { + if remoteSourceURL(arg) == "" { return arg, nil } - pkgWithVersion, subPath := packages.SplitPackagePath(arg) - pkg, version := packages.SplitPackageVersion(pkgWithVersion) - - url := "https://" + pkg - if version != "" { - url += "@" + version - } + url, _ := packages.ImportURL(arg) + _, subPath := packages.SplitPackagePath(arg) if noCache { if err := cacheInvalidateFn(url); err != nil { @@ -39,3 +35,14 @@ func resolveSourceDir(arg string, noCache bool) (string, error) { return filepath.Join(localDir, subPath), nil } + +// remoteSourceURL returns the package URL for a remote source argument, or +// "" when arg is a local directory. An existing directory always wins, so a +// local path like "my.app/deploy" isn't mistaken for a package. +func remoteSourceURL(arg string) string { + if info, err := os.Stat(arg); err == nil && info.IsDir() { + return "" + } + url, _ := packages.ImportURL(arg) + return url +} diff --git a/internal/cli/resolve_test.go b/internal/cli/resolve_test.go index 4f6269b..8c0ee50 100644 --- a/internal/cli/resolve_test.go +++ b/internal/cli/resolve_test.go @@ -2,6 +2,7 @@ package cli import ( "errors" + "os" "path/filepath" "testing" @@ -103,3 +104,11 @@ func TestResolveSourceDir_NoCacheInvalidateError(t *testing.T) { assert.Contains(t, err.Error(), "invalidating cache") } +func TestRemoteSourceURL(t *testing.T) { + local := filepath.Join(t.TempDir(), "my.app", "deploy") + require.NoError(t, os.MkdirAll(local, 0o755)) + + assert.Equal(t, "", remoteSourceURL(local), "an existing directory is local even if it looks like a host") + assert.Equal(t, "", remoteSourceURL(".")) + assert.Equal(t, "https://github.com/acme/infra@v1", remoteSourceURL("github.com/acme/infra@v1/deploy")) +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 7f82b31..f8f4eb7 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -1,20 +1,77 @@ package cli -import "github.com/spf13/cobra" +import ( + "errors" + "fmt" + "io" + "log" + + "github.com/cloudticon/ct/pkg/diag" + "github.com/go-logr/logr" + "github.com/spf13/cobra" + "k8s.io/client-go/rest" + "k8s.io/klog/v2" +) var version = "dev" +var errorFormat string + var rootCmd = &cobra.Command{ - Use: "ct", - Short: "ct - Kubernetes manifest generator", - Long: "ct generates Kubernetes manifests from .ct definitions using a registration model.", - SilenceUsage: true, + Use: "ct", + Short: "ct - Kubernetes manifest generator", + Long: "ct generates Kubernetes manifests from .ct definitions using a registration model.", + SilenceUsage: true, + SilenceErrors: true, + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + switch errorFormat { + case "text": + case "json": + // Keep stderr a single JSON document: drop progress lines + // ("applied ...", "deleted ...") that would interleave with it. + log.SetOutput(io.Discard) + cmd.Root().SetErr(io.Discard) + default: + return fmt.Errorf("unsupported --error-format %q (expected text or json)", errorFormat) + } + quietClientGo() + return nil + }, } func init() { rootCmd.Version = version + rootCmd.PersistentFlags().StringVar(&errorFormat, "error-format", "text", "how to print errors: text, or json for tools and AI agents") +} + +// quietClientGo mutes client-go's klog output (transient trouble such as a +// port-forward to a pod that just went away, which ct reports itself) and +// prints API server warnings (deprecated APIs, unknown fields) once each, +// through the same writer as ct's own progress lines. +func quietClientGo() { + klog.SetLogger(logr.Discard()) + rest.SetDefaultWarningHandler(rest.NewWarningWriter(log.Writer(), rest.WarningWriterOptions{Deduplicate: true})) } func Execute() error { return rootCmd.Execute() } + +// PrintError writes err to w in the format chosen with --error-format. +// Diagnostics keep their structure (code, file, line, resource, path, hint) +// in JSON so tools can act on them without parsing text. +func PrintError(w io.Writer, err error) { + var list diag.List + if !errors.As(err, &list) { + list = diag.List{{Code: diag.CodeError, Message: err.Error()}} + } + if errorFormat == "json" { + _, _ = w.Write(diag.JSON(list)) + return + } + if direct, ok := err.(diag.List); ok && len(direct) > 1 { + fmt.Fprintf(w, "Error: %d problems\n%s\n", len(direct), direct) + return + } + fmt.Fprintf(w, "Error: %s\n", err) +} diff --git a/internal/cli/root_test.go b/internal/cli/root_test.go new file mode 100644 index 0000000..6a06a40 --- /dev/null +++ b/internal/cli/root_test.go @@ -0,0 +1,80 @@ +package cli + +import ( + "bytes" + "errors" + "fmt" + "log" + "os" + "testing" + + "github.com/cloudticon/ct/pkg/diag" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func withErrorFormat(t *testing.T, format string) { + t.Helper() + old := errorFormat + errorFormat = format + t.Cleanup(func() { errorFormat = old }) +} + +func TestPrintError_TextDiagnostics(t *testing.T) { + withErrorFormat(t, "text") + var buf bytes.Buffer + + PrintError(&buf, diag.List{ + {Code: "syntax", Message: "bad", File: "main.ct", Line: 1, Column: 2}, + {Code: "syntax", Message: "worse", File: "main.ct", Line: 3, Column: 4}, + }) + + assert.Equal(t, "Error: 2 problems\nmain.ct:1:2: bad [syntax]\nmain.ct:3:4: worse [syntax]\n", buf.String()) +} + +func TestPrintError_TextPlainError(t *testing.T) { + withErrorFormat(t, "text") + var buf bytes.Buffer + + PrintError(&buf, errors.New("boom")) + + assert.Equal(t, "Error: boom\n", buf.String()) +} + +func TestPrintError_JSONKeepsStructureThroughWrapping(t *testing.T) { + withErrorFormat(t, "json") + var buf bytes.Buffer + + PrintError(&buf, fmt.Errorf("render: %w", diag.List{{Code: "runtime", Message: "x", File: "main.ct", Line: 7}})) + + assert.JSONEq(t, `{"errors":[{"code":"runtime","message":"x","file":"main.ct","line":7}]}`, buf.String()) +} + +func TestPrintError_JSONPlainError(t *testing.T) { + withErrorFormat(t, "json") + var buf bytes.Buffer + + PrintError(&buf, errors.New("boom")) + + assert.JSONEq(t, `{"errors":[{"code":"error","message":"boom"}]}`, buf.String()) +} + +func TestErrorFormatJSON_SilencesProgressOutput(t *testing.T) { + fake := withFakeCluster(t) + seedRelease(t, fake, "prod", "api", 2) + var logs, stderr bytes.Buffer + log.SetOutput(&logs) + t.Cleanup(func() { + log.SetOutput(os.Stderr) + errorFormat = "text" + rootCmd.SetArgs(nil) + rootCmd.SetErr(nil) + }) + rootCmd.SetErr(&stderr) + rootCmd.SetArgs([]string{"--error-format", "json", "delete", "api", "-n", "prod"}) + + require.NoError(t, rootCmd.Execute()) + + assert.Empty(t, logs.String()) + assert.Empty(t, stderr.String()) +} diff --git a/internal/cli/template.go b/internal/cli/template.go index e5c5db6..5d9bdcf 100644 --- a/internal/cli/template.go +++ b/internal/cli/template.go @@ -4,20 +4,30 @@ import ( "fmt" "os" "path/filepath" - - "github.com/cloudticon/ctts/internal/output" - "github.com/cloudticon/ctts/pkg/engine" - "github.com/cloudticon/ctts/pkg/k8s" + "strings" + "time" + + "github.com/cloudticon/ct/internal/output" + "github.com/cloudticon/ct/pkg/diag" + "github.com/cloudticon/ct/pkg/engine" + "github.com/cloudticon/ct/pkg/k8s" + "github.com/cloudticon/ct/pkg/manifest" + "github.com/cloudticon/ct/pkg/validate" "github.com/spf13/cobra" + utilvalidation "k8s.io/apimachinery/pkg/util/validation" ) type templateOpts struct { - namespace string - valuesFile string - outputFmt string - setValues []string - noCache bool - releaseName string + namespace string + valuesFiles []string + outputFmt string + setValues []string + setStringValues []string + noCache bool + releaseName string + validate bool + // sourceURL is the package URL of a remote source, "" for a local one. + sourceURL string } func newTemplateCmd() *cobra.Command { @@ -34,10 +44,9 @@ func newTemplateCmd() *cobra.Command { } cmd.Flags().StringVarP(&opts.namespace, "namespace", "n", "", "default namespace for resources") - cmd.Flags().StringVarP(&opts.valuesFile, "values", "f", "", "path to values file (JSON or YAML, overrides auto-detect)") cmd.Flags().StringVarP(&opts.outputFmt, "output", "o", "yaml", "output format: yaml or json") - cmd.Flags().StringArrayVar(&opts.setValues, "set", nil, "override values (e.g. --set replicas=5)") - cmd.Flags().BoolVar(&opts.noCache, "no-cache", false, "skip cache, re-download remote source") + addRenderFlags(cmd, &opts) + cmd.Flags().BoolVar(&opts.noCache, "no-cache", false, "re-download the remote source and imported packages instead of using ~/.ct/cache") return cmd } @@ -46,13 +55,24 @@ func init() { rootCmd.AddCommand(newTemplateCmd()) } +func addRenderFlags(cmd *cobra.Command, opts *templateOpts) { + cmd.Flags().BoolVar(&opts.validate, "validate", true, "check rendered objects against the Kubernetes API schema before output") + cmd.Flags().StringArrayVarP(&opts.valuesFiles, "values", "f", nil, "values file (JSON or YAML); repeat to deep-merge files left to right; replaces auto-detected values.json/values.yaml") + cmd.Flags().StringArrayVar(&opts.setValues, "set", nil, "override a value (e.g. --set replicas=5, --set 'annotations.a\\.b/c=x'); numbers, true/false and null are typed") + cmd.Flags().StringArrayVar(&opts.setStringValues, "set-string", nil, "override a value, always as a string (e.g. --set-string image.tag=1.10)") +} + func runTemplate(cmd *cobra.Command, releaseName, sourceDir string, opts templateOpts) error { + if err := validateReleaseName(releaseName); err != nil { + return err + } resolvedDir, err := resolveSourceDir(sourceDir, opts.noCache) if err != nil { return err } opts.releaseName = releaseName + opts.sourceURL = remoteSourceURL(sourceDir) resources, err := renderResources(resolvedDir, opts) if err != nil { return err @@ -74,53 +94,104 @@ func renderResources(dir string, opts templateOpts) ([]engine.Resource, error) { return nil, fmt.Errorf("entry point not found: %s", entryPoint) } - tr := engine.NewTranspiler(dir) + absDir, err := filepath.Abs(dir) + if err != nil { + return nil, fmt.Errorf("resolving project directory: %w", err) + } + tr := engine.NewTranspiler(absDir) + tr.RefreshPackages = opts.noCache + if opts.sourceURL != "" { + tr.MarkFresh(opts.sourceURL) // resolveSourceDir already re-downloaded it + } - valuesPath := resolveValuesPath(dir, opts.valuesFile) - values, err := loadValuesIfPresent(valuesPath, opts.setValues) + values, err := engine.LoadValues(engine.ValuesOpts{ + Files: resolveValuesFiles(dir, opts.valuesFiles), + Set: opts.setValues, + SetString: opts.setStringValues, + }) if err != nil { return nil, err } jsCode, err := tr.Bundle(entryPoint) if err != nil { - return nil, fmt.Errorf("bundle failed: %w", err) + return nil, err } - return engine.Execute(engine.ExecuteOpts{ + result, err := engine.Render(engine.ExecuteOpts{ JSCode: jsCode, Values: values, Namespace: opts.namespace, ReleaseName: opts.releaseName, + SourceDir: absDir, + Timeout: renderTimeout, }) + if err != nil { + return nil, err + } + if opts.validate { + if problems := validate.Resources(result.Resources, result.Origin); len(problems) > 0 { + return nil, problems + } + } + resources := result.Resources + manifest.SortForApply(resources) + return resources, nil } -func resolveValuesPath(dir, explicit string) string { - if explicit != "" { - return explicit +// validateReleaseName enforces what the release name ends up in: a label +// value and the inventory ConfigMap name. +func validateReleaseName(name string) error { + if msgs := utilvalidation.IsDNS1123Label(name); len(msgs) > 0 { + return diag.List{{ + Code: diag.CodeInvalidValue, + Message: fmt.Sprintf("invalid release name %q: %s", name, strings.Join(msgs, "; ")), + Hint: "release names are lowercase letters, digits and '-', at most 63 characters, e.g. my-app", + }} + } + return nil +} + +// renderTimeout stops runaway .ct programs (endless loops) with a stack trace +// instead of hanging the CLI. +var renderTimeout = time.Minute + +// resolveValuesFiles returns the values files for a render. Explicit files +// are used as given, falling back to the project directory, so +// `-f values-prod.yaml` works for remote sources too. Without explicit files +// the first of values.json, values.yaml, values.yml in dir is used. +func resolveValuesFiles(dir string, explicit []string) []string { + if len(explicit) > 0 { + files := make([]string, len(explicit)) + for i, f := range explicit { + files[i] = f + if _, err := os.Stat(f); err != nil && !filepath.IsAbs(f) { + if inProject := filepath.Join(dir, f); fileExists(inProject) { + files[i] = inProject + } + } + } + return files + } + if path := detectValuesFile(dir); path != "" { + return []string{path} } - candidates := []string{"values.json", "values.yaml", "values.yml"} - for _, name := range candidates { + return nil +} + +func detectValuesFile(dir string) string { + for _, name := range []string{"values.json", "values.yaml", "values.yml"} { path := filepath.Join(dir, name) - if _, err := os.Stat(path); err == nil { + if fileExists(path) { return path } } return "" } -func loadValuesIfPresent(valuesPath string, setOverrides []string) (map[string]interface{}, error) { - if valuesPath == "" && len(setOverrides) == 0 { - return nil, nil - } - if valuesPath == "" { - return nil, fmt.Errorf("--set provided but no values file found") - } - values, err := engine.LoadValuesFile(valuesPath, setOverrides) - if err != nil { - return nil, fmt.Errorf("loading values from %s: %w", valuesPath, err) - } - return values, nil +func fileExists(path string) bool { + info, err := os.Stat(path) + return err == nil && !info.IsDir() } func toOutputResources(resources []engine.Resource) []output.Resource { diff --git a/internal/cli/template_e2e_test.go b/internal/cli/template_e2e_test.go index c6e07e7..36b2aa4 100644 --- a/internal/cli/template_e2e_test.go +++ b/internal/cli/template_e2e_test.go @@ -7,7 +7,9 @@ import ( "path/filepath" "strings" "testing" + "time" + "github.com/cloudticon/ct/pkg/diag" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" @@ -24,7 +26,9 @@ func writeProject(t *testing.T, mainCt string, files map[string]string) string { dir := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(dir, "main.ct"), []byte(mainCt), 0o644)) for name, body := range files { - require.NoError(t, os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644)) + path := filepath.Join(dir, name) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(body), 0o644)) } return dir } @@ -150,7 +154,7 @@ __ct_resources.push({ data: { env: Values.env }, }); `, map[string]string{ - "values.json": `{"env": "default"}`, + "values.json": `{"env": "default"}`, "values-prod.json": `{"env": "production"}`, }) @@ -185,14 +189,14 @@ __ct_resources.push({ docs := splitYAMLDocs(t, stdout) require.Len(t, docs, 2) - cm := asMap(t, docs[0]["metadata"]) + cm := asMap(t, docByKind(t, docs, "ConfigMap")["metadata"]) assert.Equal(t, "default-ns", cm["namespace"], "namespaced resource without explicit ns must inherit default") - secret := asMap(t, docs[1]["metadata"]) + secret := asMap(t, docByKind(t, docs, "Secret")["metadata"]) assert.Equal(t, "explicit-ns", secret["namespace"], "explicit namespace must not be overridden") } -func TestTemplateE2E_RendersMultipleResourcesInRegistrationOrder(t *testing.T) { +func TestTemplateE2E_RendersResourcesInHelmInstallOrder(t *testing.T) { dir := writeProject(t, ` __ct_resources.push({ apiVersion: "apps/v1", @@ -209,16 +213,101 @@ __ct_resources.push({ kind: "ConfigMap", metadata: { name: "web-cm" }, }); +__ct_resources.push({ + apiVersion: "v1", + kind: "Namespace", + metadata: { name: "team" }, +}); +`, nil) + + stdout, _, err := runTemplateE2E(t, "demo", dir, "--validate=false") + require.NoError(t, err) + + docs := splitYAMLDocs(t, stdout) + require.Len(t, docs, 4) + assert.Equal(t, "Namespace", docs[0]["kind"]) + assert.Equal(t, "ConfigMap", docs[1]["kind"]) + assert.Equal(t, "Service", docs[2]["kind"]) + assert.Equal(t, "Deployment", docs[3]["kind"]) +} + +func TestTemplateE2E_KeepsEmptyObjects(t *testing.T) { + dir := writeProject(t, ` +__ct_resources.push({ + apiVersion: "v1", + kind: "Pod", + metadata: { name: "p", labels: undefined }, + spec: { + containers: [{ name: "app", image: "nginx", args: [] }], + volumes: [{ name: "tmp", emptyDir: {} }], + }, +}); `, nil) stdout, _, err := runTemplateE2E(t, "demo", dir) require.NoError(t, err) + assert.Contains(t, stdout, "emptyDir: {}") + assert.Contains(t, stdout, "args: []", "empty arrays stay as written") + assert.NotContains(t, stdout, "labels: null") +} + +func TestTemplateE2E_ClusterScopedKindsGetNoNamespace(t *testing.T) { + dir := writeProject(t, ` +__ct_resources.push({ apiVersion: "rbac.authorization.k8s.io/v1", kind: "ClusterRole", metadata: { name: "reader" } }); +__ct_resources.push({ apiVersion: "v1", kind: "Namespace", metadata: { name: "team" } }); +__ct_resources.push({ apiVersion: "v1", kind: "ServiceAccount", metadata: { name: "sa" } }); +`, nil) + + stdout, _, err := runTemplateE2E(t, "demo", dir, "-n", "prod") + require.NoError(t, err) + docs := splitYAMLDocs(t, stdout) require.Len(t, docs, 3) - assert.Equal(t, "Deployment", docs[0]["kind"]) - assert.Equal(t, "Service", docs[1]["kind"]) - assert.Equal(t, "ConfigMap", docs[2]["kind"]) + for _, doc := range docs { + meta := asMap(t, doc["metadata"]) + if doc["kind"] == "ServiceAccount" { + assert.Equal(t, "prod", meta["namespace"]) + } else { + assert.NotContains(t, meta, "namespace", "%s is cluster-scoped", doc["kind"]) + } + } +} + +func TestTemplateE2E_RejectsDuplicateResources(t *testing.T) { + dir := writeProject(t, ` +for (const i of [1, 2]) { + __ct_resources.push({ apiVersion: "v1", kind: "ConfigMap", metadata: { name: "cfg" } }); +} +`, nil) + + _, _, err := runTemplateE2E(t, "demo", dir, "-n", "prod") + require.Error(t, err) + var list diag.List + require.ErrorAs(t, err, &list) + require.Len(t, list, 1) + assert.Equal(t, diag.CodeDuplicate, list[0].Code) + assert.Equal(t, `ConfigMap "cfg" (namespace "prod")`, list[0].Resource) + assert.Equal(t, "main.ct", list[0].File) + assert.Equal(t, 3, list[0].Line, "points at the push inside the loop") + assert.Contains(t, list[0].Message, "registered 2 times") +} + +func TestTemplateE2E_YAMLUsesTwoSpaceIndent(t *testing.T) { + dir := writeProject(t, ` +__ct_resources.push({ + apiVersion: "v1", + kind: "Service", + metadata: { name: "svc" }, + spec: { ports: [{ port: 80, targetPort: 8080 }] }, +}); +`, nil) + + stdout, _, err := runTemplateE2E(t, "demo", dir) + require.NoError(t, err) + + assert.Contains(t, stdout, "\nmetadata:\n labels:\n") + assert.Contains(t, stdout, "\nspec:\n ports:\n - port: 80\n targetPort: 8080\n") } func TestTemplateE2E_PreservesUserLabelsOverInjected(t *testing.T) { @@ -277,13 +366,60 @@ this is not valid javascript {{{ syntax error `, nil) _, _, err := runTemplateE2E(t, "demo", dir) - require.Error(t, err) - // Either esbuild rejects the syntax or goja fails — either is fine, - // but the error must surface to the caller. - assert.True(t, - strings.Contains(err.Error(), "bundle failed") || - strings.Contains(err.Error(), "JS execution error"), - "error should describe bundle/exec failure, got: %v", err) + + var list diag.List + require.ErrorAs(t, err, &list) + assert.Equal(t, diag.CodeSyntax, list[0].Code) + assert.Equal(t, "main.ct", list[0].File) + assert.Equal(t, 2, list[0].Line) + assert.Contains(t, list[0].LineText, "this is not valid javascript") +} + +func TestTemplateE2E_RuntimeErrorPointsAtCtSource(t *testing.T) { + dir := writeProject(t, `import { make } from "./lib/factory"; + +make({ name: "ok" }); +make({ name: "" }); +`, map[string]string{ + "lib/factory.ct": `export function make(opts: { name: string }) { + if (!opts.name) { + throw new Error("name is required"); + } + __ct_resources.push({ apiVersion: "v1", kind: "ConfigMap", metadata: { name: opts.name } }); +} +`, + }) + + _, _, err := runTemplateE2E(t, "demo", dir) + + var list diag.List + require.ErrorAs(t, err, &list) + d := list[0] + assert.Equal(t, diag.CodeRuntime, d.Code) + assert.Contains(t, d.Message, "name is required") + assert.Equal(t, "lib/factory.ct", d.File) + assert.Equal(t, 3, d.Line) + require.GreaterOrEqual(t, len(d.Stack), 2) + assert.Equal(t, "main.ct", d.Stack[1].File) + assert.Equal(t, 4, d.Stack[1].Line, "the failing call site in main.ct") +} + +func TestTemplateE2E_TimesOutEndlessLoops(t *testing.T) { + old := renderTimeout + renderTimeout = 200 * time.Millisecond + t.Cleanup(func() { renderTimeout = old }) + dir := writeProject(t, ` +let i = 0; +while (true) { i++; } +`, nil) + + _, _, err := runTemplateE2E(t, "demo", dir) + + var list diag.List + require.ErrorAs(t, err, &list) + assert.Equal(t, diag.CodeTimeout, list[0].Code) + assert.Equal(t, "main.ct", list[0].File) + assert.Equal(t, 3, list[0].Line) } func TestTemplateE2E_RejectsUnsupportedOutputFormat(t *testing.T) { @@ -296,6 +432,120 @@ __ct_resources.push({apiVersion: "v1", kind: "ConfigMap", metadata: { name: "x" assert.Contains(t, err.Error(), "serialization failed") } +func TestTemplateE2E_SetWithoutValuesFile(t *testing.T) { + dir := writeProject(t, ` +__ct_resources.push({ apiVersion: "v1", kind: "ConfigMap", metadata: { name: "cfg" }, data: { tag: Values.image.tag } }); +`, nil) + + stdout, _, err := runTemplateE2E(t, "demo", dir, "--set", "image.tag=1.10") + require.NoError(t, err) + + docs := splitYAMLDocs(t, stdout) + require.Len(t, docs, 1) + assert.Equal(t, "1.10", asMap(t, docs[0]["data"])["tag"], "tag stays the string 1.10, not the number 1.1") +} + +func TestTemplateE2E_MergesRepeatedValuesFiles(t *testing.T) { + dir := writeProject(t, ` +__ct_resources.push({ + apiVersion: "v1", kind: "ConfigMap", metadata: { name: "cfg" }, + data: { image: Values.image.repository + ":" + Values.image.tag, replicas: String(Values.replicas) }, +}); +`, map[string]string{ + "values.yaml": "image:\n repository: nginx\n tag: \"1.25\"\nreplicas: 1\n", + "values-prod.yaml": "image:\n tag: \"1.27\"\n", + }) + + stdout, _, err := runTemplateE2E(t, "demo", dir, + "-f", filepath.Join(dir, "values.yaml"), "-f", filepath.Join(dir, "values-prod.yaml"), "--set-string", "replicas=3") + require.NoError(t, err) + + data := asMap(t, splitYAMLDocs(t, stdout)[0]["data"]) + assert.Equal(t, "nginx:1.27", data["image"]) + assert.Equal(t, "3", data["replicas"]) +} + +func TestTemplateE2E_ValidationPointsAtTheRegisteringLine(t *testing.T) { + dir := writeProject(t, `import { configMap } from "./lib/k8s"; + +configMap({ name: "ok", data: { a: "1" } }); +configMap({ name: "Bad_Name", spec: { data: { a: "1" } } }); +`, map[string]string{ + "lib/k8s.ct": `export function configMap(args: { name: string; [k: string]: unknown }) { + const { name, ...rest } = args; + __ct_resources.push({ apiVersion: "v1", kind: "ConfigMap", metadata: { name }, ...rest }); +} +`, + }) + + _, _, err := runTemplateE2E(t, "demo", dir) + + var list diag.List + require.ErrorAs(t, err, &list) + require.Len(t, list, 2) + for _, d := range list { + assert.Equal(t, "lib/k8s.ct", d.File, "%s", d) + assert.Equal(t, 3, d.Line, "%s", d) + require.Len(t, d.Stack, 1, "the call chain reaches the user's call: %s", d) + assert.Equal(t, "main.ct", d.Stack[0].File) + assert.Equal(t, 4, d.Stack[0].Line) + assert.Equal(t, `ConfigMap "Bad_Name"`, d.Resource) + } + assert.Equal(t, "metadata.name", list[0].Path) + assert.Equal(t, diag.CodeUnknownField, list[1].Code) + assert.Equal(t, "spec", list[1].Path) +} + +func TestTemplateE2E_ValidateFalseSkipsValidation(t *testing.T) { + dir := writeProject(t, ` +__ct_resources.push({ apiVersion: "v1", kind: "ConfigMap", metadata: { name: "cfg" }, spec: { x: 1 } }); +`, nil) + + _, _, err := runTemplateE2E(t, "demo", dir) + require.Error(t, err) + + stdout, _, err := runTemplateE2E(t, "demo", dir, "--validate=false") + require.NoError(t, err) + assert.Contains(t, stdout, "spec:") +} + +func TestTemplateE2E_RejectsInvalidReleaseName(t *testing.T) { + dir := writeProject(t, `__ct_resources.push({ apiVersion: "v1", kind: "ConfigMap", metadata: { name: "cfg" } });`, nil) + + _, _, err := runTemplateE2E(t, "My_App", dir) + + var list diag.List + require.ErrorAs(t, err, &list) + assert.Contains(t, list[0].Message, `invalid release name "My_App"`) +} + +func TestTemplateE2E_RemoteSourceErrorsPointAtItsOwnFiles(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + cacheRoot := filepath.Join(home, ".ct", "cache", "github.com") + lib := filepath.Join(cacheRoot, "acme", "lib@v1") + project := filepath.Join(cacheRoot, "acme", "infra@v1") + require.NoError(t, os.MkdirAll(lib, 0o755)) + require.NoError(t, os.MkdirAll(project, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(lib, "index.ts"), []byte(` +export function configMap(args: any) { + const { name, ...rest } = args; + __ct_resources.push({ apiVersion: "v1", kind: "ConfigMap", metadata: { name }, ...rest }); +} +`), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(project, "main.ct"), []byte(`import { configMap } from "github.com/acme/lib@v1"; + +configMap({ name: "cfg", spec: {} }); +`), 0o644)) + + _, _, err := runTemplateE2E(t, "demo", "github.com/acme/infra@v1") + + var list diag.List + require.ErrorAs(t, err, &list) + assert.Equal(t, "main.ct", list[0].File, "%s", list[0]) + assert.Equal(t, 3, list[0].Line) +} + // --- helpers --- func splitYAMLDocs(t *testing.T, raw string) []map[string]interface{} { @@ -314,6 +564,17 @@ func splitYAMLDocs(t *testing.T, raw string) []map[string]interface{} { return docs } +func docByKind(t *testing.T, docs []map[string]interface{}, kind string) map[string]interface{} { + t.Helper() + for _, doc := range docs { + if doc["kind"] == kind { + return doc + } + } + require.Failf(t, "kind not rendered", "no %s in output", kind) + return nil +} + func asMap(t *testing.T, v interface{}) map[string]interface{} { t.Helper() m, ok := v.(map[string]interface{}) diff --git a/internal/cli/template_test.go b/internal/cli/template_test.go index 26dbf52..b917f40 100644 --- a/internal/cli/template_test.go +++ b/internal/cli/template_test.go @@ -6,7 +6,7 @@ import ( "path/filepath" "testing" - "github.com/cloudticon/ctts/internal/scaffold" + "github.com/cloudticon/ct/internal/scaffold" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -14,7 +14,8 @@ import ( func setupProject(t *testing.T) string { t.Helper() dir := filepath.Join(t.TempDir(), "project") - require.NoError(t, scaffold.Init(dir)) + _, err := scaffold.Init(dir, scaffold.Options{}) + require.NoError(t, err) return dir } @@ -45,8 +46,8 @@ func TestTemplateCmd_RequiresReleaseNameAndSource(t *testing.T) { func TestTemplateCmd_AutoDetectsValuesJSON(t *testing.T) { dir := setupProject(t) - path := resolveValuesPath(dir, "") - assert.Equal(t, filepath.Join(dir, "values.json"), path) + files := resolveValuesFiles(dir, nil) + assert.Equal(t, []string{filepath.Join(dir, "values.json")}, files) } func TestTemplateCmd_ExplicitValuesOverride(t *testing.T) { @@ -55,14 +56,22 @@ func TestTemplateCmd_ExplicitValuesOverride(t *testing.T) { custom := filepath.Join(t.TempDir(), "custom.json") require.NoError(t, os.WriteFile(custom, []byte(`{"image":"custom:1.0","replicas":1}`), 0644)) - path := resolveValuesPath(dir, custom) - assert.Equal(t, custom, path) + files := resolveValuesFiles(dir, []string{custom}) + assert.Equal(t, []string{custom}, files) +} + +func TestTemplateCmd_ExplicitValuesFallBackToProjectDir(t *testing.T) { + dir := setupProject(t) + require.NoError(t, os.WriteFile(filepath.Join(dir, "values-prod.json"), []byte(`{}`), 0644)) + t.Chdir(t.TempDir()) + + files := resolveValuesFiles(dir, []string{"values-prod.json", "missing.json"}) + assert.Equal(t, []string{filepath.Join(dir, "values-prod.json"), "missing.json"}, files) } func TestTemplateCmd_NoValuesFile(t *testing.T) { dir := t.TempDir() - path := resolveValuesPath(dir, "") - assert.Equal(t, "", path) + assert.Empty(t, resolveValuesFiles(dir, nil)) } func TestTemplateCmd_NoCacheFlagDefault(t *testing.T) { diff --git a/internal/cli/types.go b/internal/cli/types.go index e58cac2..1d54aa0 100644 --- a/internal/cli/types.go +++ b/internal/cli/types.go @@ -7,12 +7,13 @@ import ( "os" "path/filepath" "sort" + "strconv" "strings" - "github.com/cloudticon/ctts/internal/dev" - "github.com/cloudticon/ctts/pkg/cache" - "github.com/cloudticon/ctts/pkg/engine" - "github.com/cloudticon/ctts/pkg/packages" + "github.com/cloudticon/ct/internal/dev" + "github.com/cloudticon/ct/pkg/cache" + "github.com/cloudticon/ct/pkg/engine" + "github.com/cloudticon/ct/pkg/packages" "github.com/spf13/cobra" ) @@ -75,13 +76,9 @@ func runTypes(cmd *cobra.Command, dir string, opts typesOpts) error { return fmt.Errorf("creating output directory: %w", err) } - valuesPath := resolveValuesPath(absDir, "") - var values map[string]interface{} - if valuesPath != "" { - values, err = engine.LoadValuesFile(valuesPath, nil) - if err != nil { - return fmt.Errorf("loading values: %w", err) - } + values, err := engine.LoadValues(engine.ValuesOpts{Files: resolveValuesFiles(absDir, nil)}) + if err != nil { + return fmt.Errorf("loading values: %w", err) } if err := os.WriteFile(filepath.Join(outDir, "values.d.ts"), []byte(generateValuesDts(values)), 0o644); err != nil { @@ -121,7 +118,7 @@ func resolveURLImports(entryPath string) error { } for _, imp := range imports { - rawURL, ok := importToURL(imp.Path) + rawURL, ok := packages.ImportURL(imp.Path) if !ok { continue } @@ -132,22 +129,6 @@ func resolveURLImports(entryPath string) error { return nil } -func importToURL(importPath string) (string, bool) { - if packages.IsURLImport(importPath) { - return importPath, true - } - if !packages.IsGitPackage(importPath) { - return "", false - } - pkgWithVersion, _ := packages.SplitPackagePath(importPath) - pkg, version := packages.SplitPackageVersion(pkgWithVersion) - url := "https://" + pkg - if version != "" { - url += "@" + version - } - return url, true -} - func projectHash(absPath string) string { h := sha256.Sum256([]byte(absPath)) return hex.EncodeToString(h[:])[:12] @@ -166,8 +147,17 @@ func generateValuesDts(values map[string]interface{}) string { func writeObjectFields(buf *strings.Builder, obj map[string]interface{}, indent string) { for _, k := range sortedKeys(obj) { - fmt.Fprintf(buf, "%s%s: %s;\n", indent, k, inferTSType(obj[k], indent)) + fmt.Fprintf(buf, "%s%s: %s;\n", indent, tsPropertyName(k), inferTSType(obj[k], indent)) + } +} + +// tsPropertyName quotes keys that aren't identifiers, e.g. annotation keys +// like "nginx.ingress.kubernetes.io/rewrite-target". +func tsPropertyName(key string) string { + if engine.IsValidJSIdentifier(key) { + return key } + return strconv.Quote(key) } func inferTSType(v interface{}, indent string) string { @@ -245,8 +235,7 @@ func collectUniqueWorkloadNames(dir string) []string { return nil } - valuesPath := resolveValuesPath(dir, "") - values, err := loadValuesIfPresent(valuesPath, nil) + values, err := engine.LoadValues(engine.ValuesOpts{Files: resolveValuesFiles(dir, nil)}) if err != nil { return nil } @@ -254,6 +243,10 @@ func collectUniqueWorkloadNames(dir string) []string { resources, err := engine.Execute(engine.ExecuteOpts{ JSCode: js, Values: values, + // ct dev's default --name, so names built from Release.name match + // what ct dev renders. + ReleaseName: "dev", + Timeout: renderTimeout, }) if err != nil { return nil @@ -329,9 +322,11 @@ func generateDevDts(resourceNames, envKeys []string) string { buf.WriteString("declare function env(name: CtEnvKey): string;\n") buf.WriteString("declare function env(name: CtEnvKey, defaultValue: number): number;\n") + buf.WriteString("declare function env(name: CtEnvKey, defaultValue: boolean): boolean;\n") buf.WriteString("declare function env(name: CtEnvKey, defaultValue: string): string;\n") buf.WriteString("declare function env(name: string): string;\n") buf.WriteString("declare function env(name: string, defaultValue: number): number;\n") + buf.WriteString("declare function env(name: string, defaultValue: boolean): boolean;\n") buf.WriteString("declare function env(name: string, defaultValue: string): string;\n") return buf.String() diff --git a/internal/cli/types_test.go b/internal/cli/types_test.go index 36f6ab1..b88f9df 100644 --- a/internal/cli/types_test.go +++ b/internal/cli/types_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" + "github.com/cloudticon/ct/pkg/packages" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -333,6 +334,20 @@ func TestFindEntryPoint(t *testing.T) { }) } +func TestGenerateValuesDts_QuotesNonIdentifierKeys(t *testing.T) { + dts := generateValuesDts(map[string]interface{}{ + "annotations": map[string]interface{}{"nginx.ingress.kubernetes.io/rewrite-target": "/"}, + "my-key": "x", + "2fa": true, + "ok_key": int64(1), + }) + + assert.Contains(t, dts, ` "2fa": boolean;`) + assert.Contains(t, dts, ` "nginx.ingress.kubernetes.io/rewrite-target": string;`) + assert.Contains(t, dts, ` "my-key": string;`) + assert.Contains(t, dts, ` ok_key: number;`) +} + func TestImportToURL(t *testing.T) { tests := []struct { name string @@ -349,7 +364,7 @@ func TestImportToURL(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - url, ok := importToURL(tt.input) + url, ok := packages.ImportURL(tt.input) assert.Equal(t, tt.wantOK, ok) if ok { assert.Equal(t, tt.wantURL, url) @@ -357,3 +372,24 @@ func TestImportToURL(t *testing.T) { }) } } + +func TestGenerateDevDts_EnvAcceptsBooleanDefaults(t *testing.T) { + dts := generateDevDts(nil, []string{"DEBUG"}) + + assert.Contains(t, dts, "declare function env(name: CtEnvKey, defaultValue: boolean): boolean;") + assert.Contains(t, dts, "declare function env(name: string, defaultValue: boolean): boolean;") +} + +func TestCollectUniqueWorkloadNames_UsesDevReleaseName(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "main.ct"), []byte(` +__ct_resources.push({ + apiVersion: "apps/v1", + kind: "Deployment", + metadata: { name: Release.name + "-web" }, + spec: { selector: { matchLabels: { app: "web" } } }, +}); +`), 0o644)) + + assert.Equal(t, []string{"dev-web"}, collectUniqueWorkloadNames(dir)) +} diff --git a/internal/dev/config_test.go b/internal/dev/config_test.go index 8561167..3b54d2a 100644 --- a/internal/dev/config_test.go +++ b/internal/dev/config_test.go @@ -3,7 +3,7 @@ package dev_test import ( "testing" - "github.com/cloudticon/ctts/internal/dev" + "github.com/cloudticon/ct/internal/dev" "github.com/stretchr/testify/assert" ) diff --git a/internal/dev/patch.go b/internal/dev/patch.go index ce345b1..155bdf4 100644 --- a/internal/dev/patch.go +++ b/internal/dev/patch.go @@ -1,6 +1,101 @@ package dev -import "github.com/cloudticon/ctts/pkg/engine" +import ( + "fmt" + "strings" + + "github.com/cloudticon/ct/pkg/engine" +) + +// defaultContainerAnnotation tells the API clients that honor it (kubectl, +// and ct's own log streaming) which container of a multi-container pod to +// use when none is named explicitly. +const defaultContainerAnnotation = "kubectl.kubernetes.io/default-container" + +// ResolveContainers validates the `container` option of every target backed by +// a workload rendered from main.ct and fills in the default (the first +// container) when it is not set. After this, PatchResources, the terminal and +// sync all address the same container. Targets without a rendered workload +// (external selectors) keep whatever was configured. +func ResolveContainers(targets []Target, resources []engine.Resource) error { + workloads := indexWorkloads(resources) + for i := range targets { + entry, ok := workloads[targets[i].Name] + if !ok || entry.conflict { + continue + } + names := containerNames(getContainers(entry.resource)) + if len(names) == 0 { + continue + } + if targets[i].Container == "" { + targets[i].Container = names[0] + continue + } + if containsString(names, targets[i].Container) { + continue + } + kind, _ := entry.resource["kind"].(string) + if containsString(containerNames(getInitContainers(entry.resource)), targets[i].Container) { + return fmt.Errorf("target %q: container %q is an init container of %s %q; dev mode can only target regular containers (%s)", + targets[i].Name, targets[i].Container, kind, targets[i].Name, strings.Join(names, ", ")) + } + return fmt.Errorf("target %q: container %q not found in %s %q (containers: %s)", + targets[i].Name, targets[i].Container, kind, targets[i].Name, strings.Join(names, ", ")) + } + return nil +} + +// ValidatePatches rejects workload options that PatchResources could not +// apply, instead of silently ignoring them: options on a target without a +// (unique) workload of that name in main.ct, and replicas on workloads that +// have no replica count. +func ValidatePatches(targets []Target, resources []engine.Resource) error { + workloads := indexWorkloads(resources) + for _, t := range targets { + options := patchOptions(t) + if len(options) == 0 { + continue + } + entry, ok := workloads[t.Name] + if !ok { + return fmt.Errorf("target %q: %s change the workload, but main.ct renders no Deployment/StatefulSet/DaemonSet/ReplicaSet/Job named %q; "+ + "remove them for workloads ct does not manage, or name the target after the workload", + t.Name, strings.Join(options, ", "), t.Name) + } + if entry.conflict { + return fmt.Errorf("target %q: %s cannot be applied: several workloads are named %q", t.Name, strings.Join(options, ", "), t.Name) + } + kind, _ := entry.resource["kind"].(string) + if t.Replicas != nil && (kind == "DaemonSet" || kind == "Job") { + return fmt.Errorf("target %q: replicas cannot be set on a %s", t.Name, kind) + } + } + return nil +} + +func patchOptions(t Target) []string { + var options []string + if t.Image != "" { + options = append(options, "image") + } + if len(t.Command) > 0 { + options = append(options, "command") + } + if t.Replicas != nil { + options = append(options, "replicas") + } + if len(t.Env) > 0 { + options = append(options, "env") + } + if t.WorkingDir != "" { + options = append(options, "workingDir") + } + if t.Probes != nil { + options = append(options, "probes") + } + return options +} // PatchResources modifies workload resources based on dev target config. // Called between template render and apply. @@ -8,24 +103,25 @@ import "github.com/cloudticon/ctts/pkg/engine" func PatchResources(resources []engine.Resource, targets []Target) { workloads := indexWorkloads(resources) for _, t := range targets { - if t.Selector != nil { - if _, ok := workloads[t.Name]; !ok { - continue - } - } entry, ok := workloads[t.Name] if !ok || entry.conflict { continue } res := entry.resource + if t.Replicas != nil { + setReplicas(res, *t.Replicas) + } + containerIdx := findContainer(res, t.Container) + if containerIdx < 0 { + // Unknown container name: never fall back to another container, + // that would patch e.g. a sidecar. ResolveContainers reports it. + continue + } if t.Probes == nil || !*t.Probes { removeProbes(res, containerIdx) } - if t.Replicas != nil { - setReplicas(res, *t.Replicas) - } if len(t.Env) > 0 { mergeEnvVars(res, t.Env, containerIdx) } @@ -40,12 +136,18 @@ func PatchResources(resources []engine.Resource, targets []Target) { } setContainerTTY(res, containerIdx) + setDefaultContainer(res, containerIdx) } } +// findContainer returns the index of the named container, the first container +// when name is empty, or -1 when there is no such container. func findContainer(res engine.Resource, name string) int { containers := getContainers(res) - if name == "" || len(containers) == 0 { + if len(containers) == 0 { + return -1 + } + if name == "" { return 0 } for i, c := range containers { @@ -54,7 +156,7 @@ func findContainer(res engine.Resource, name string) int { return i } } - return 0 + return -1 } func removeProbes(res engine.Resource, containerIdx int) { @@ -124,6 +226,10 @@ func setContainerCommand(res engine.Resource, command []string, containerIdx int cmdIface[i] = s } c["command"] = cmdIface + // The dev command is the full command line (dev.ct has no args option). + // Keeping the workload's args would append them to it, e.g. + // "sleep infinity --port 8080", which crashes the container. + delete(c, "args") } func setContainerWorkingDir(res engine.Resource, workingDir string, containerIdx int) { @@ -163,10 +269,70 @@ func setContainerImage(res engine.Resource, image string, containerIdx int) { c["image"] = image } +// setDefaultContainer marks the patched container as the pod's default +// container. Exec and logs requests without an explicit container are +// rejected by the API server for multi-container pods (e.g. with an injected +// service-mesh sidecar); clients resolve the default from this annotation. +func setDefaultContainer(res engine.Resource, containerIdx int) { + containers := getContainers(res) + if containerIdx >= len(containers) { + return + } + c, _ := containers[containerIdx].(map[string]interface{}) + name, _ := c["name"].(string) + if name == "" { + return + } + spec, _ := res["spec"].(map[string]interface{}) + tmpl, _ := spec["template"].(map[string]interface{}) + if tmpl == nil { + return + } + meta, _ := tmpl["metadata"].(map[string]interface{}) + if meta == nil { + meta = map[string]interface{}{} + tmpl["metadata"] = meta + } + annotations, _ := meta["annotations"].(map[string]interface{}) + if annotations == nil { + annotations = map[string]interface{}{} + meta["annotations"] = annotations + } + annotations[defaultContainerAnnotation] = name +} + func getContainers(res engine.Resource) []interface{} { + return getPodSpecList(res, "containers") +} + +func getInitContainers(res engine.Resource) []interface{} { + return getPodSpecList(res, "initContainers") +} + +func getPodSpecList(res engine.Resource, key string) []interface{} { spec, _ := res["spec"].(map[string]interface{}) tmpl, _ := spec["template"].(map[string]interface{}) tSpec, _ := tmpl["spec"].(map[string]interface{}) - containers, _ := tSpec["containers"].([]interface{}) - return containers + list, _ := tSpec[key].([]interface{}) + return list +} + +func containerNames(containers []interface{}) []string { + names := make([]string, 0, len(containers)) + for _, c := range containers { + cMap, _ := c.(map[string]interface{}) + if name, ok := cMap["name"].(string); ok && name != "" { + names = append(names, name) + } + } + return names +} + +func containsString(list []string, s string) bool { + for _, v := range list { + if v == s { + return true + } + } + return false } diff --git a/internal/dev/patch_test.go b/internal/dev/patch_test.go index 0877c04..0a7e2cf 100644 --- a/internal/dev/patch_test.go +++ b/internal/dev/patch_test.go @@ -3,8 +3,8 @@ package dev_test import ( "testing" - "github.com/cloudticon/ctts/internal/dev" - "github.com/cloudticon/ctts/pkg/engine" + "github.com/cloudticon/ct/internal/dev" + "github.com/cloudticon/ct/pkg/engine" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -344,3 +344,146 @@ func TestPatchResources_AllPatchesCombined(t *testing.T) { envs := c["env"].([]interface{}) require.Len(t, envs, 2) } + +func makeMultiContainerDeployment() engine.Resource { + return engine.Resource{ + "kind": "Deployment", + "metadata": map[string]interface{}{"name": "multi"}, + "spec": map[string]interface{}{ + "selector": map[string]interface{}{ + "matchLabels": map[string]interface{}{"app": "multi"}, + }, + "template": map[string]interface{}{ + "spec": map[string]interface{}{ + "initContainers": []interface{}{ + map[string]interface{}{"name": "migrate", "image": "migrate:latest"}, + }, + "containers": []interface{}{ + map[string]interface{}{"name": "sidecar", "image": "sidecar:latest"}, + map[string]interface{}{"name": "app", "image": "app:latest"}, + }, + }, + }, + }, + } +} + +func containerByName(t *testing.T, res engine.Resource, name string) map[string]interface{} { + t.Helper() + spec := res["spec"].(map[string]interface{}) + tmpl := spec["template"].(map[string]interface{}) + tSpec := tmpl["spec"].(map[string]interface{}) + for _, c := range tSpec["containers"].([]interface{}) { + cMap := c.(map[string]interface{}) + if cMap["name"] == name { + return cMap + } + } + t.Fatalf("container %q not found", name) + return nil +} + +// A typo in `container` used to silently patch the FIRST container (here the +// sidecar): its image/command were replaced and the pod broke. +func TestPatchResources_UnknownContainerDoesNotPatchFirstContainer(t *testing.T) { + resources := []engine.Resource{makeMultiContainerDeployment()} + targets := []dev.Target{{Name: "multi", Container: "ap", Image: "app:dev", Command: []string{"sleep", "infinity"}}} + + dev.PatchResources(resources, targets) + + sidecar := containerByName(t, resources[0], "sidecar") + assert.Equal(t, "sidecar:latest", sidecar["image"], "sidecar must not be patched for an unknown container name") + _, hasCmd := sidecar["command"] + assert.False(t, hasCmd) +} + +func TestResolveContainers_UnknownContainerIsAnError(t *testing.T) { + resources := []engine.Resource{makeMultiContainerDeployment()} + targets := []dev.Target{{Name: "multi", Container: "ap"}} + + err := dev.ResolveContainers(targets, resources) + require.Error(t, err) + assert.Contains(t, err.Error(), `container "ap" not found`) + assert.Contains(t, err.Error(), "sidecar, app") +} + +func TestResolveContainers_InitContainerIsRejected(t *testing.T) { + resources := []engine.Resource{makeMultiContainerDeployment()} + targets := []dev.Target{{Name: "multi", Container: "migrate"}} + + err := dev.ResolveContainers(targets, resources) + require.Error(t, err) + assert.Contains(t, err.Error(), "init container") +} + +func TestResolveContainers_DefaultsToFirstContainer(t *testing.T) { + resources := []engine.Resource{makeMultiContainerDeployment()} + targets := []dev.Target{ + {Name: "multi"}, + {Name: "external", Selector: map[string]string{"app": "pg"}}, + } + + require.NoError(t, dev.ResolveContainers(targets, resources)) + assert.Equal(t, "sidecar", targets[0].Container, "default container is the first one, the same one PatchResources patches") + assert.Equal(t, "", targets[1].Container, "targets without a rendered workload keep the API default") +} + +// Logs have no container parameter on the Cluster port; the pod template +// annotation makes the API default (used by logs and by kubectl) point at the +// dev container of a multi-container workload. +func TestPatchResources_MarksDevContainerAsDefault(t *testing.T) { + resources := []engine.Resource{makeMultiContainerDeployment()} + targets := []dev.Target{{Name: "multi", Container: "app"}} + + dev.PatchResources(resources, targets) + + spec := resources[0]["spec"].(map[string]interface{}) + tmpl := spec["template"].(map[string]interface{}) + meta, ok := tmpl["metadata"].(map[string]interface{}) + require.True(t, ok, "pod template metadata should be created") + annotations := meta["annotations"].(map[string]interface{}) + assert.Equal(t, "app", annotations["kubectl.kubernetes.io/default-container"]) +} + +// Overriding `command` while keeping the workload's `args` produced e.g. +// `sleep infinity --port 8080`, which crashes the dev container. +func TestPatchResources_CommandOverrideDropsArgs(t *testing.T) { + res := makeWorkloadResource("web") + c := getFirstContainer(res) + c["args"] = []interface{}{"--port", "8080"} + resources := []engine.Resource{res} + + dev.PatchResources(resources, []dev.Target{{Name: "web", Command: []string{"sleep", "infinity"}}}) + + c = getFirstContainer(resources[0]) + assert.Equal(t, []interface{}{"sleep", "infinity"}, c["command"]) + _, hasArgs := c["args"] + assert.False(t, hasArgs, "args of the original command must not be appended to the dev command") +} + +// Workload options on a target that has no workload in main.ct (an external +// selector, e.g. an operator-managed database) were silently not applied. +func TestValidatePatches_RejectsPatchesWithoutWorkload(t *testing.T) { + resources := []engine.Resource{makeWorkloadResource("web")} + err := dev.ValidatePatches([]dev.Target{ + {Name: "web", Image: "web:dev"}, + {Name: "postgres", Selector: map[string]string{"cnpg.io/cluster": "pg"}, Image: "postgres:17", Ports: []dev.PortRule{{Local: 5432, Remote: 5432}}}, + }, resources) + require.Error(t, err) + assert.Contains(t, err.Error(), `target "postgres"`) + assert.Contains(t, err.Error(), "image") + assert.Contains(t, err.Error(), "main.ct") + + require.NoError(t, dev.ValidatePatches([]dev.Target{ + {Name: "postgres", Selector: map[string]string{"cnpg.io/cluster": "pg"}, Ports: []dev.PortRule{{Local: 5432, Remote: 5432}}}, + }, resources), "port-forward/sync/terminal-only targets need no workload") +} + +func TestValidatePatches_RejectsReplicasForDaemonSet(t *testing.T) { + ds := makeWorkloadResource("agent") + ds["kind"] = "DaemonSet" + one := 1 + err := dev.ValidatePatches([]dev.Target{{Name: "agent", Replicas: &one}}, []engine.Resource{ds}) + require.Error(t, err) + assert.Contains(t, err.Error(), "DaemonSet") +} diff --git a/internal/dev/resolve.go b/internal/dev/resolve.go index 36d8738..09853aa 100644 --- a/internal/dev/resolve.go +++ b/internal/dev/resolve.go @@ -4,7 +4,7 @@ import ( "fmt" "sort" - "github.com/cloudticon/ctts/pkg/engine" + "github.com/cloudticon/ct/pkg/engine" ) var workloadKinds = map[string]bool{ @@ -85,7 +85,14 @@ func resolveSelector(name string, workloads map[string]indexedResource) (map[str "use selector: {...} to specify explicitly", name, ) } - return extractSelector(entry.resource) + selector, err := extractSelector(entry.resource) + if err != nil { + // Typical for Jobs, whose selector is generated by the API server. + kind, _ := entry.resource["kind"].(string) + return nil, fmt.Errorf("%s %q has no spec.selector.matchLabels to find its pods by; "+ + "add selector: {...} with its pod labels to dev(%q, ...): %w", kind, name, name, err) + } + return selector, nil } func extractSelector(res engine.Resource) (map[string]string, error) { diff --git a/internal/dev/resolve_test.go b/internal/dev/resolve_test.go index 2547029..06975a4 100644 --- a/internal/dev/resolve_test.go +++ b/internal/dev/resolve_test.go @@ -3,8 +3,8 @@ package dev_test import ( "testing" - "github.com/cloudticon/ctts/internal/dev" - "github.com/cloudticon/ctts/pkg/engine" + "github.com/cloudticon/ct/internal/dev" + "github.com/cloudticon/ct/pkg/engine" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -210,3 +210,20 @@ func TestUniqueWorkloadNames_Empty(t *testing.T) { names := dev.UniqueWorkloadNames(nil) assert.Empty(t, names) } + +// Jobs usually get their selector generated by the API server; the old +// error ("missing path [spec selector matchLabels] in resource") did not say +// what to do about it. +func TestResolveSelectors_MissingSelectorSuggestsExplicitSelector(t *testing.T) { + resources := []engine.Resource{{ + "kind": "Job", + "apiVersion": "batch/v1", + "metadata": map[string]interface{}{"name": "migrate"}, + "spec": map[string]interface{}{"template": map[string]interface{}{}}, + }} + err := dev.ResolveSelectors([]dev.Target{{Name: "migrate"}}, resources) + require.Error(t, err) + assert.Contains(t, err.Error(), `Job "migrate"`) + assert.Contains(t, err.Error(), "spec.selector.matchLabels") + assert.Contains(t, err.Error(), `selector: {...}`) +} diff --git a/internal/dev/runner.go b/internal/dev/runner.go index 7209433..c158627 100644 --- a/internal/dev/runner.go +++ b/internal/dev/runner.go @@ -13,10 +13,11 @@ import ( "sync" "time" - "github.com/cloudticon/ctts/pkg/engine" - "github.com/cloudticon/ctts/pkg/k8s" - ctsync "github.com/cloudticon/ctts/pkg/sync" + "github.com/cloudticon/ct/pkg/engine" + "github.com/cloudticon/ct/pkg/k8s" + ctsync "github.com/cloudticon/ct/pkg/sync" "github.com/fatih/color" + "github.com/go-logr/logr" "github.com/pterm/pterm" "k8s.io/klog/v2" ) @@ -27,9 +28,28 @@ const maxSessionRetries = 5 var sessionEstablishedThreshold = 10 * time.Second +// sessionRetryBackoff is the wait before the first reconnect; it doubles for +// every further attempt, up to maxSessionRetryBackoff. +var ( + sessionRetryBackoff = time.Second + maxSessionRetryBackoff = 8 * time.Second +) + +// podLostError marks a session that ended because the pod went away or +// became unhealthy (reported by the health watcher). It is always worth a +// reconnect, even if the message mentions an exit code of a crashed +// container. +type podLostError struct{ err error } + +func (e *podLostError) Error() string { return e.err.Error() } +func (e *podLostError) Unwrap() error { return e.err } + type RunOpts struct { - Dir string - EnvFile string + Dir string + EnvFile string + // EnvFileRequired makes a missing EnvFile an error. Set when the file + // was named explicitly; the default .env is optional. + EnvFileRequired bool KubeCtx string ReleaseName string Delete bool @@ -72,35 +92,46 @@ func (p ptermSpinnerAdapter) Fail(args ...any) { p.SpinnerPrinter.Fail(args.. // terminal exits cleanly, when ctx is cancelled, or when retries are exhausted. // // The retry policy: +// - ctx cancellation (Ctrl+C) ends the session successfully // - no retries when no target has a terminal (background features fail-fast) +// - the pod going away or becoming unhealthy (health watcher) always retries // - exit code 130 (Ctrl+C) returns success // - non-pod-kill exit codes return the error verbatim (caller-driven exit) // - exit codes 137/143 (SIGKILL/SIGTERM, i.e. pod restart) and connection -// errors retry up to maxSessionRetries; counter resets after a session -// stays up for sessionEstablishedThreshold. +// errors retry up to maxSessionRetries with exponential backoff; the +// counter resets after a session stays up for sessionEstablishedThreshold. func startDevFeatures(ctx context.Context, cluster k8s.Cluster, namespace string, targets []Target, stdout io.Writer) error { if len(targets) == 0 { return nil } hasTerminal := hasTerminalTarget(targets) + // Log streams of all targets write to stdout concurrently. + stdout = &lockedWriter{w: stdout} for attempt := 0; ; attempt++ { sessionStart := time.Now() err := runDevSession(ctx, cluster, namespace, targets, stdout, hasTerminal, attempt > 0) - if err == nil || ctx.Err() != nil { - return err - } - if !hasTerminal { - return err + if ctx.Err() != nil { + // Interrupted by the user: that is how a dev session ends. + return nil } - if isTerminalExitCode130(err) { + if err == nil { return nil } - if isCommandExit(err) && !isPodKilledExit(err) { + if !hasTerminal { return err } + var lost *podLostError + if !errors.As(err, &lost) { + if isTerminalExitCode130(err) { + return nil + } + if isCommandExit(err) && !isPodKilledExit(err) { + return err + } + } if time.Since(sessionStart) >= sessionEstablishedThreshold { attempt = 0 } @@ -110,6 +141,51 @@ func startDevFeatures(ctx context.Context, cluster k8s.Cluster, namespace string devLog.Printf("[terminal] disconnected: %v", err) devLog.Printf("[terminal] waiting for pod to restart (attempt %d/%d)...", attempt+2, maxSessionRetries) + if !sleepCtx(ctx, retryBackoff(attempt)) { + return nil + } + } +} + +// lockedWriter serializes writes to a writer shared by several goroutines. +type lockedWriter struct { + mu sync.Mutex + w io.Writer +} + +func (l *lockedWriter) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + if l.w == nil { + return len(p), nil + } + return l.w.Write(p) +} + +// retryBackoff returns the wait before reconnect attempt+1. +func retryBackoff(attempt int) time.Duration { + d := sessionRetryBackoff + for i := 0; i < attempt && d < maxSessionRetryBackoff; i++ { + d *= 2 + } + if d > maxSessionRetryBackoff { + d = maxSessionRetryBackoff + } + return d +} + +// sleepCtx waits for d and reports whether it did so without ctx ending. +func sleepCtx(ctx context.Context, d time.Duration) bool { + if d <= 0 { + return ctx.Err() == nil + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return false + case <-t.C: + return true } } @@ -132,17 +208,25 @@ func runDevSession(ctx context.Context, cluster k8s.Cluster, namespace string, t var wg sync.WaitGroup errCh := make(chan error, 1) + // fail records the first feature failure and stops the session. Errors + // returned after the session was asked to stop are consequences of the + // cancellation, not failures of their own. + fail := func(err error) { + if err == nil || errors.Is(err, context.Canceled) || featuresCtx.Err() != nil { + return + } + select { + case errCh <- err: + default: + } + cancel() + } + startFeature := func(fn func(context.Context) error) { wg.Add(1) go func() { defer wg.Done() - if err := fn(featuresCtx); err != nil && !errors.Is(err, context.Canceled) { - select { - case errCh <- err: - default: - } - cancel() - } + fail(fn(featuresCtx)) }() } @@ -165,12 +249,18 @@ func runDevSession(ctx context.Context, cluster k8s.Cluster, namespace string, t syncWg.Add(1) startFeature(func(gctx context.Context) error { syncer := ctsync.NewSyncer(cluster, namespace, target.Selector, ctsync.SyncRule{ - From: rule.From, - To: rule.To, - Exclude: append([]string(nil), rule.Exclude...), - Polling: rule.Polling, + From: rule.From, + To: rule.To, + Exclude: append([]string(nil), rule.Exclude...), + Polling: rule.Polling, + Container: target.Container, + }) + return syncer.RunWithReady(gctx, func(err error) { + // Record a failure before releasing the waiter so it can + // never mistake a failed initial sync for a completed one. + fail(err) + syncWg.Done() }) - return syncer.RunWithReady(gctx, syncWg.Done) }) } @@ -183,23 +273,23 @@ func runDevSession(ctx context.Context, cluster k8s.Cluster, namespace string, t if hasTerminal && strings.TrimSpace(target.Terminal) != "" { podName := podNames[target.Name] startFeature(func(gctx context.Context) error { - return cluster.WatchPod(gctx, namespace, podName) + if err := cluster.WatchPod(gctx, namespace, podName); err != nil { + return &podLostError{err: err} + } + return nil }) } } + // waitFeatures blocks until every feature returned and reports the first + // failure. (Selecting on errCh and a "done" channel instead would pick + // at random when both are ready and could drop the error.) waitFeatures := func() error { - done := make(chan struct{}) - go func() { - wg.Wait() - close(done) - }() - + wg.Wait() select { case err := <-errCh: - <-done return err - case <-done: + default: return nil } } @@ -214,35 +304,19 @@ func runDevSession(ctx context.Context, cluster k8s.Cluster, namespace string, t sp := startSpinner("waiting for initial sync...") select { case <-syncReady: - sp.Success("initial sync complete") case <-featuresCtx.Done(): + } + // A failed sync cancels featuresCtx before it marks itself ready. + if featuresCtx.Err() != nil { sp.Fail("sync interrupted") cancel() return waitFeatures() } + sp.Success("initial sync complete") } if hasTerminal { - origLogWriter := log.Writer() - origStderr := os.Stderr - - log.SetOutput(io.Discard) - klog.SetOutput(io.Discard) - - var devNullFile *os.File - if f, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0); err == nil { - os.Stderr = f - devNullFile = f - } - - defer func() { - if devNullFile != nil { - os.Stderr = origStderr - devNullFile.Close() - } - klog.SetOutput(origStderr) - log.SetOutput(origLogWriter) - }() + defer silenceLibraryLogs()() } for _, target := range targets { @@ -258,12 +332,15 @@ func runDevSession(ctx context.Context, cluster k8s.Cluster, namespace string, t } } - terminalErr := cluster.Exec(featuresCtx, namespace, target.Selector, k8s.ExecOpts{ - Command: []string{"/bin/sh", "-c", terminalCommand(target)}, - Stdin: os.Stdin, - Stdout: os.Stdout, - Stderr: os.Stderr, - TTY: true, + // Exec into the pod the health watcher watches; resolving it again by + // selector could pick another pod (e.g. mid-rollout). + terminalErr := cluster.ExecPod(featuresCtx, namespace, podNames[target.Name], k8s.ExecOpts{ + Container: target.Container, + Command: []string{"/bin/sh", "-c", terminalCommand(target)}, + Stdin: os.Stdin, + Stdout: os.Stdout, + Stderr: os.Stderr, + TTY: true, }) cancel() @@ -283,6 +360,21 @@ func runDevSession(ctx context.Context, cluster k8s.Cluster, namespace string, t } } +// silenceLibraryLogs mutes the standard logger and klog (client-go) so they +// do not draw over the interactive terminal, and returns a function that +// restores them. It used to swap the global os.Stderr for /dev/null, which +// raced with feature goroutines already logging through klog and closed the +// file under late writers; both loggers serialize these changes internally. +func silenceLibraryLogs() (restore func()) { + origLogWriter := log.Writer() + log.SetOutput(io.Discard) + klog.SetLogger(logr.Discard()) + return func() { + klog.ClearLogger() + log.SetOutput(origLogWriter) + } +} + func toK8sPortRules(ports []PortRule) []k8s.PortRule { out := make([]k8s.PortRule, 0, len(ports)) for _, p := range ports { @@ -336,7 +428,7 @@ func Run(ctx context.Context, opts RunOpts) error { return err } - envVars, err := loadEnvVars(normalizedOpts.Dir, normalizedOpts.EnvFile) + envVars, err := loadEnvVars(normalizedOpts.Dir, normalizedOpts.EnvFile, normalizedOpts.EnvFileRequired) if err != nil { return err } @@ -354,9 +446,12 @@ func Run(ctx context.Context, opts RunOpts) error { devResult, err := engine.ExecuteDev(engine.ExecuteDevOpts{ JSCode: devCode, EnvVars: envVars, - PromptFn: engine.MakePromptFn(promptCache, normalizedOpts.Stdin, normalizedOpts.Stdout), + PromptFn: cancellablePrompt(ctx, engine.MakePromptFn(promptCache, normalizedOpts.Stdin, normalizedOpts.Stdout)), }) if err != nil { + if ctx.Err() != nil { + return fmt.Errorf("interrupted: %w", ctx.Err()) + } return fmt.Errorf("executing dev.ct: %w", err) } @@ -373,8 +468,11 @@ func Run(ctx context.Context, opts RunOpts) error { if err != nil { return err } + if err := resolveSyncSources(normalizedOpts.Dir, targets); err != nil { + return err + } - resources, err := renderMainResources(normalizedOpts.Dir, devResult.Namespace, devResult.Values) + resources, err := renderMainResources(normalizedOpts.Dir, devResult.Namespace, normalizedOpts.ReleaseName, devResult.Values) if err != nil { return err } @@ -382,6 +480,12 @@ func Run(ctx context.Context, opts RunOpts) error { if err := ResolveSelectors(targets, resources); err != nil { return err } + if err := ResolveContainers(targets, resources); err != nil { + return err + } + if err := ValidatePatches(targets, resources); err != nil { + return err + } PatchResources(resources, targets) resources = k8s.InjectReleaseLabels(resources, normalizedOpts.ReleaseName) @@ -401,6 +505,32 @@ func Run(ctx context.Context, opts RunOpts) error { return nil } +// cancellablePrompt makes a blocking prompt give up when ctx is cancelled +// (Ctrl+C). The read itself cannot be interrupted; it is abandoned, which is +// fine because the process is about to exit. +func cancellablePrompt(ctx context.Context, prompt func(string) (string, error)) func(string) (string, error) { + type answer struct { + value string + err error + } + return func(question string) (string, error) { + if err := ctx.Err(); err != nil { + return "", err + } + ch := make(chan answer, 1) + go func() { + value, err := prompt(question) + ch <- answer{value, err} + }() + select { + case a := <-ch: + return a.value, a.err + case <-ctx.Done(): + return "", ctx.Err() + } + } +} + func ensureRunNamespace(ctx context.Context, cluster k8s.Cluster, namespace string, createNamespace bool) error { if !createNamespace || namespace == "" { return nil @@ -448,7 +578,7 @@ func normalizeRunOpts(opts RunOpts) (RunOpts, error) { return result, nil } -func loadEnvVars(dir, envFile string) (map[string]string, error) { +func loadEnvVars(dir, envFile string, required bool) (map[string]string, error) { if envFile == "" { return engine.MergeEnvWithSystem(nil), nil } @@ -460,7 +590,7 @@ func loadEnvVars(dir, envFile string) (map[string]string, error) { fileEnv, err := engine.LoadEnvFile(envPath) if err != nil { - if os.IsNotExist(err) { + if os.IsNotExist(err) && !required { return engine.MergeEnvWithSystem(nil), nil } return nil, fmt.Errorf("loading env file %s: %w", envPath, err) @@ -486,7 +616,7 @@ func bundleEntry(dir, fileName string) (string, error) { return jsCode, nil } -func renderMainResources(dir, namespace string, overlayValues map[string]interface{}) ([]engine.Resource, error) { +func renderMainResources(dir, namespace, releaseName string, overlayValues map[string]interface{}) ([]engine.Resource, error) { mainCode, err := bundleEntry(dir, "main.ct") if err != nil { return nil, fmt.Errorf("bundling main.ct: %w", err) @@ -499,9 +629,10 @@ func renderMainResources(dir, namespace string, overlayValues map[string]interfa mergedValues := DeepMergeValues(baseValues, overlayValues) resources, err := engine.Execute(engine.ExecuteOpts{ - JSCode: mainCode, - Values: mergedValues, - Namespace: namespace, + JSCode: mainCode, + Values: mergedValues, + Namespace: namespace, + ReleaseName: releaseName, // Release.name, as with ct template/apply }) if err != nil { return nil, fmt.Errorf("executing main.ct: %w", err) @@ -535,7 +666,17 @@ func resolveValuesPath(dir string) string { func convertTargets(rawTargets []engine.RawDevTarget) ([]Target, error) { targets := make([]Target, 0, len(rawTargets)) + localPortOwner := map[int]string{} + seen := map[string]bool{} for _, raw := range rawTargets { + if strings.TrimSpace(raw.Name) == "" { + return nil, errors.New("dev(): the target name (first argument) must be a non-empty string") + } + if seen[raw.Name] { + return nil, fmt.Errorf("target %q is defined more than once; merge its dev() calls", raw.Name) + } + seen[raw.Name] = true + syncRules, err := parseSyncRules(raw.Name, raw.Sync) if err != nil { return nil, err @@ -545,6 +686,13 @@ func convertTargets(rawTargets []engine.RawDevTarget) ([]Target, error) { if err != nil { return nil, err } + for _, p := range portRules { + if owner, taken := localPortOwner[p.Local]; taken { + return nil, fmt.Errorf("local port %d is forwarded twice (targets %q and %q); each local port can only be forwarded once", + p.Local, owner, raw.Name) + } + localPortOwner[p.Local] = raw.Name + } envVars, err := parseEnvVars(raw.Name, raw.Env) if err != nil { @@ -592,14 +740,26 @@ func parseSyncRules(targetName string, rawSync []map[string]interface{}) ([]Sync To: to, } - if rawExclude, ok := rawRule["exclude"].([]interface{}); ok { - rule.Exclude = make([]string, 0, len(rawExclude)) - for _, item := range rawExclude { - rule.Exclude = append(rule.Exclude, fmt.Sprint(item)) + if rawExclude, present := rawRule["exclude"]; present && rawExclude != nil { + list, ok := rawExclude.([]interface{}) + if !ok { + return nil, fmt.Errorf("target %q: sync[%d].exclude must be an array of patterns, got %T", targetName, i, rawExclude) + } + rule.Exclude = make([]string, 0, len(list)) + for j, item := range list { + pattern, ok := item.(string) + if !ok { + return nil, fmt.Errorf("target %q: sync[%d].exclude[%d] must be a string, got %T", targetName, i, j, item) + } + rule.Exclude = append(rule.Exclude, pattern) } } - if polling, ok := rawRule["polling"].(bool); ok { + if rawPolling, present := rawRule["polling"]; present && rawPolling != nil { + polling, ok := rawPolling.(bool) + if !ok { + return nil, fmt.Errorf("target %q: sync[%d].polling must be a boolean, got %T", targetName, i, rawPolling) + } rule.Polling = polling } @@ -608,6 +768,31 @@ func parseSyncRules(targetName string, rawSync []map[string]interface{}) ([]Sync return rules, nil } +// resolveSyncSources makes relative sync sources relative to the project +// directory (not the process working directory) and checks that they are +// directories, before anything is applied to the cluster. +func resolveSyncSources(dir string, targets []Target) error { + for i := range targets { + for j := range targets[i].Sync { + rule := &targets[i].Sync[j] + from := rule.From + if !filepath.IsAbs(from) { + from = filepath.Join(dir, from) + } + info, err := os.Stat(from) + if err != nil { + return fmt.Errorf("target %q: sync[%d].from %q: %w", targets[i].Name, j, rule.From, err) + } + if !info.IsDir() { + return fmt.Errorf("target %q: sync[%d].from %q is not a directory; sync copies a directory (use exclude to leave files out)", + targets[i].Name, j, rule.From) + } + rule.From = from + } + } + return nil +} + func parsePortRules(targetName string, rawPorts []interface{}) ([]PortRule, error) { rules := make([]PortRule, 0, len(rawPorts)) for i, rawPort := range rawPorts { @@ -639,6 +824,12 @@ func parsePortRules(targetName string, rawPorts []interface{}) ([]PortRule, erro default: return nil, fmt.Errorf("target %q: ports[%d] must be number or [local,remote]", targetName, i) } + last := rules[len(rules)-1] + for _, port := range []int{last.Local, last.Remote} { + if port < 1 || port > 65535 { + return nil, fmt.Errorf("target %q: ports[%d]: port %d is out of range 1-65535", targetName, i, port) + } + } } return rules, nil } @@ -651,8 +842,14 @@ func parseEnvVars(targetName string, rawEnv []map[string]interface{}) ([]EnvVar, return nil, fmt.Errorf("target %q: env[%d].name must be a non-empty string", targetName, i) } value := "" - if rawValue, exists := raw["value"]; exists { - value = fmt.Sprint(rawValue) + switch v := raw["value"].(type) { + case nil: + // Missing/undefined/null: an empty value, as in Kubernetes + // (it used to become the string ""). + case string, int64, float64, bool: + value = fmt.Sprint(v) + default: + return nil, fmt.Errorf("target %q: env[%d].value must be a string, number or boolean, got %T", targetName, i, v) } result = append(result, EnvVar{Name: name, Value: value}) } diff --git a/internal/dev/runner_test.go b/internal/dev/runner_test.go index fe8aa5d..70e35e7 100644 --- a/internal/dev/runner_test.go +++ b/internal/dev/runner_test.go @@ -1,23 +1,27 @@ package dev import ( + "archive/tar" "bytes" "context" "errors" + "fmt" "io" "log" "os" "path/filepath" + "strings" "sync" "sync/atomic" "testing" "time" - "github.com/cloudticon/ctts/pkg/engine" - "github.com/cloudticon/ctts/pkg/k8s" - "github.com/cloudticon/ctts/pkg/k8s/k8stest" + "github.com/cloudticon/ct/pkg/engine" + "github.com/cloudticon/ct/pkg/k8s" + "github.com/cloudticon/ct/pkg/k8s/k8stest" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "k8s.io/klog/v2" ) // devCluster wraps a k8stest.Fake with optional per-method hooks tailored to @@ -36,10 +40,13 @@ type devCluster struct { WatchPodFn func(ctx context.Context, ns, pod string) error ExecFn func(ctx context.Context, ns string, sel k8s.Selector, opts k8s.ExecOpts) error WaitPodFn func(ctx context.Context, ns string, sel k8s.Selector) (string, error) + ExecPodFn func(ctx context.Context, ns, pod string, opts k8s.ExecOpts) error portCalls []string logCalls []string syncCalls []string + terminalPods []string + watchedPods []string terminalCalls int32 waitCalls int32 healthCalls int32 @@ -79,6 +86,9 @@ func (d *devCluster) StreamLogs(ctx context.Context, ns, target string, sel k8s. func (d *devCluster) WatchPod(ctx context.Context, ns, pod string) error { atomic.AddInt32(&d.healthCalls, 1) + d.mu.Lock() + d.watchedPods = append(d.watchedPods, pod) + d.mu.Unlock() if d.WatchPodFn != nil { return d.WatchPodFn(ctx, ns, pod) } @@ -96,11 +106,25 @@ func (d *devCluster) Exec(ctx context.Context, ns string, sel k8s.Selector, opts // ExecPod is the route used by sync. We return success immediately so the // dev session's sync feature reports ready and unblocks the terminal. func (d *devCluster) ExecPod(ctx context.Context, ns, pod string, opts k8s.ExecOpts) error { + if opts.TTY { + // The interactive terminal. + d.mu.Lock() + d.terminalPods = append(d.terminalPods, pod) + d.mu.Unlock() + atomic.AddInt32(&d.terminalCalls, 1) + if d.ExecFn != nil { + return d.ExecFn(ctx, ns, nil, opts) + } + return d.Fake.ExecPod(ctx, ns, pod, opts) + } d.mu.Lock() if len(opts.Command) > 0 && opts.Command[0] == "tar" { d.syncCalls = append(d.syncCalls, "tar") } d.mu.Unlock() + if d.ExecPodFn != nil { + return d.ExecPodFn(ctx, ns, pod, opts) + } return nil } @@ -129,6 +153,9 @@ func silenceDevLog(t *testing.T) { origSpinner := startSpinner startSpinner = func(string) progressSpinner { return noopSpinner{} } t.Cleanup(func() { startSpinner = origSpinner }) + + // Reconnect immediately unless a test opts into a backoff. + noRetryBackoff(t) } type noopSpinner struct{} @@ -218,13 +245,13 @@ func TestLoadEnvVars_LoadsRelativeFileAndMerges(t *testing.T) { envPath := filepath.Join(dir, ".env.dev") require.NoError(t, os.WriteFile(envPath, []byte("RUNNER_ENV=value\n"), 0o644)) - env, err := loadEnvVars(dir, ".env.dev") + env, err := loadEnvVars(dir, ".env.dev", true) require.NoError(t, err) assert.Equal(t, "value", env["RUNNER_ENV"]) } func TestLoadEnvVars_MissingFileDoesNotFail(t *testing.T) { - env, err := loadEnvVars(t.TempDir(), ".env.missing") + env, err := loadEnvVars(t.TempDir(), ".env.missing", false) require.NoError(t, err) assert.NotNil(t, env) } @@ -692,3 +719,594 @@ func TestRunDevSession_CancelCascadesToAllFeatures(t *testing.T) { } assert.Equal(t, 0, fake.ActiveOps(), "no goroutines should remain active after cancel") } + +// Pods with an injected sidecar (Istio, Linkerd, ...) have several +// containers; the API server rejects exec without a container name there, so +// sync and the terminal must address the target's container explicitly. +func TestStartDevFeatures_TerminalAndSyncUseTargetContainer(t *testing.T) { + silenceDevLog(t) + + fake := k8stest.NewFake() + fake.AddPod(&k8stest.FakePod{ + Name: "web-x", Namespace: "ns", + Labels: k8s.Selector{"app": "web"}, Healthy: true, + Containers: []string{"app", "istio-proxy"}, + }) + fake.ExecHook = func(ns, pod string, opts k8s.ExecOpts) error { return nil } + + src := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(src, "main.go"), []byte("package main"), 0o644)) + + targets := []Target{{ + Name: "web", Selector: map[string]string{"app": "web"}, + Container: "app", + Sync: []SyncRule{{From: src, To: "/app"}}, + Terminal: "bash", + }} + + require.NoError(t, startDevFeatures(context.Background(), fake, "ns", targets, &bytes.Buffer{})) + + var commands []string + for _, call := range fake.ExecCalls { + commands = append(commands, call.Opts.Command[0]) + assert.Equal(t, "app", call.Opts.Container, "exec %v must target the dev container", call.Opts.Command) + } + assert.Contains(t, commands, "tar", "initial sync should have run") + assert.Contains(t, commands, "/bin/sh", "terminal should have run") +} + +// slowUnwrapError delays anyone walking the error chain (errors.Is/As). It +// widens the window between a feature returning an error and the session +// reacting to it, which makes ordering bugs deterministic. +type slowUnwrapError struct{ msg string } + +func (e slowUnwrapError) Error() string { return e.msg } +func (e slowUnwrapError) Unwrap() error { + time.Sleep(100 * time.Millisecond) + return nil +} + +// A failed initial sync used to signal "ready" before the failure was +// reported, so the session printed "initial sync complete" and started the +// terminal on top of a failed sync. +func TestStartDevFeatures_FailedInitialSyncDoesNotStartTerminal(t *testing.T) { + silenceDevLog(t) + var successes []string + var mu sync.Mutex + startSpinner = func(string) progressSpinner { + return recordingSpinner{onSuccess: func(msg string) { + mu.Lock() + successes = append(successes, msg) + mu.Unlock() + }} + } + + dc := newDevCluster() + dc.ExecPodFn = func(_ context.Context, _ string, _ string, opts k8s.ExecOpts) error { + if opts.Command[0] == "tar" { + return slowUnwrapError{msg: "command terminated with exit code 2"} + } + return nil + } + dc.ExecFn = func(ctx context.Context, _ string, _ k8s.Selector, _ k8s.ExecOpts) error { + <-ctx.Done() + return ctx.Err() + } + + src := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(src, "a.txt"), []byte("x"), 0o644)) + targets := []Target{{ + Name: "web", Selector: map[string]string{"app": "web"}, + Sync: []SyncRule{{From: src, To: "/app"}}, + Terminal: "bash", + }} + + err := startDevFeatures(context.Background(), dc, "ns", targets, &bytes.Buffer{}) + require.Error(t, err) + assert.Contains(t, err.Error(), "initial sync failed") + assert.Equal(t, 0, dc.TerminalCalls(), "terminal must not start when the initial sync failed") + mu.Lock() + defer mu.Unlock() + assert.NotContains(t, successes, "initial sync complete") +} + +type recordingSpinner struct{ onSuccess func(string) } + +func (r recordingSpinner) Success(args ...any) { + if len(args) > 0 { + if s, ok := args[0].(string); ok { + r.onSuccess(s) + } + } +} +func (recordingSpinner) Fail(_ ...any) {} + +func noRetryBackoff(t *testing.T) { + t.Helper() + orig := sessionRetryBackoff + sessionRetryBackoff = 0 + t.Cleanup(func() { sessionRetryBackoff = orig }) +} + +// The health watcher's error for a crashed container contains "exit code 1"; +// it used to be mistaken for the user's terminal command exiting, so ct dev +// quit instead of reconnecting once the container was restarted. +func TestStartDevFeatures_ReconnectsWhenContainerCrashes(t *testing.T) { + silenceDevLog(t) + + dc := newDevCluster() + var execCalls int32 + dc.ExecFn = func(ctx context.Context, _ string, _ k8s.Selector, _ k8s.ExecOpts) error { + if atomic.AddInt32(&execCalls, 1) == 1 { + <-ctx.Done() + return ctx.Err() + } + return nil + } + var watchCalls int32 + dc.WatchPodFn = func(ctx context.Context, _ string, _ string) error { + if atomic.AddInt32(&watchCalls, 1) == 1 { + return errors.New(`pod "web-x": container "app" has terminated (Error, exit code 1)`) + } + <-ctx.Done() + return ctx.Err() + } + + require.NoError(t, startDevFeatures(context.Background(), dc, "ns", + []Target{{Name: "web", Terminal: "bash"}}, &bytes.Buffer{})) + assert.Equal(t, 2, dc.TerminalCalls(), "a crashed container must lead to a reconnect, not to exiting ct dev") +} + +// "waiting for pod to restart" used to retry immediately: five attempts were +// burnt within a second, too fast to survive a network blip or a restart. +func TestStartDevFeatures_BacksOffBetweenAttempts(t *testing.T) { + silenceDevLog(t) + orig := sessionRetryBackoff + sessionRetryBackoff = 60 * time.Millisecond + t.Cleanup(func() { sessionRetryBackoff = orig }) + + dc := newDevCluster() + var mu sync.Mutex + var calls []time.Time + dc.ExecFn = func(_ context.Context, _ string, _ k8s.Selector, _ k8s.ExecOpts) error { + mu.Lock() + defer mu.Unlock() + calls = append(calls, time.Now()) + if len(calls) < 3 { + return errors.New("connection lost") + } + return nil + } + + require.NoError(t, startDevFeatures(context.Background(), dc, "ns", + []Target{{Name: "web", Terminal: "bash"}}, &bytes.Buffer{})) + require.Len(t, calls, 3) + assert.GreaterOrEqual(t, calls[1].Sub(calls[0]), 60*time.Millisecond) + assert.GreaterOrEqual(t, calls[2].Sub(calls[1]), 120*time.Millisecond, "backoff should grow") +} + +func TestStartDevFeatures_CancelDuringBackoffReturnsPromptly(t *testing.T) { + silenceDevLog(t) + orig := sessionRetryBackoff + sessionRetryBackoff = time.Hour + t.Cleanup(func() { sessionRetryBackoff = orig }) + + dc := newDevCluster() + ctx, cancel := context.WithCancel(context.Background()) + dc.ExecFn = func(_ context.Context, _ string, _ k8s.Selector, _ k8s.ExecOpts) error { + time.AfterFunc(20*time.Millisecond, cancel) + return errors.New("connection lost") + } + + done := make(chan error, 1) + go func() { + done <- startDevFeatures(ctx, dc, "ns", []Target{{Name: "web", Terminal: "bash"}}, &bytes.Buffer{}) + }() + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(2 * time.Second): + t.Fatal("startDevFeatures did not return after cancel during backoff") + } +} + +// Ctrl+C (the parent context being cancelled) is how a dev session ends; it +// used to surface as "starting dev features: context canceled" and exit 1. +func TestStartDevFeatures_CancelledWhileWaitingForPodIsNotAnError(t *testing.T) { + silenceDevLog(t) + + dc := newDevCluster() + dc.WaitPodFn = func(ctx context.Context, _ string, _ k8s.Selector) (string, error) { + <-ctx.Done() + return "", ctx.Err() + } + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(20*time.Millisecond, cancel) + + require.NoError(t, startDevFeatures(ctx, dc, "ns", []Target{{Name: "web", Terminal: "bash"}}, &bytes.Buffer{})) +} + +// With Ctrl+C cancelling ctx (instead of killing the process), a prompt() +// blocked on stdin must give up when ctx is cancelled. +func TestRun_CancelInterruptsPrompt(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "dev.ct"), + []byte(`const user = prompt("Username?") +config({ namespace: "dev-" + user }) +`), 0o644)) + + stdin, stdinWriter := io.Pipe() // never written: the prompt blocks + t.Cleanup(func() { _ = stdinWriter.Close() }) + + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(50*time.Millisecond, cancel) + + done := make(chan error, 1) + go func() { + done <- Run(ctx, RunOpts{Dir: dir, Stdin: stdin, Stdout: &bytes.Buffer{}, Stderr: &bytes.Buffer{}}) + }() + select { + case err := <-done: + require.Error(t, err) + assert.Contains(t, err.Error(), "interrupted") + case <-time.After(3 * time.Second): + t.Fatal("Run kept waiting for prompt input after ctx was cancelled") + } +} + +func TestConvertTargets_RejectsOutOfRangePorts(t *testing.T) { + for _, ports := range [][]interface{}{ + {int64(0)}, + {int64(-1)}, + {int64(70000)}, + {[]interface{}{int64(8080), int64(0)}}, + {[]interface{}{int64(65536), int64(80)}}, + } { + _, err := convertTargets([]engine.RawDevTarget{{Name: "web", Ports: ports}}) + require.Error(t, err, "ports %v", ports) + assert.Contains(t, err.Error(), "1-65535") + } +} + +// Two rules forwarding the same local port can never both listen; the +// second port-forward used to retry forever. +func TestConvertTargets_RejectsDuplicateLocalPorts(t *testing.T) { + _, err := convertTargets([]engine.RawDevTarget{ + {Name: "web", Ports: []interface{}{int64(8080)}}, + {Name: "api", Ports: []interface{}{[]interface{}{int64(8080), int64(3000)}}}, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "local port 8080") + assert.Contains(t, err.Error(), `"web"`) + assert.Contains(t, err.Error(), `"api"`) + + _, err = convertTargets([]engine.RawDevTarget{ + {Name: "web", Ports: []interface{}{int64(8080), []interface{}{int64(8080), int64(80)}}}, + }) + require.Error(t, err) +} + +func TestConvertTargets_RejectsMistypedSyncOptions(t *testing.T) { + _, err := convertTargets([]engine.RawDevTarget{{Name: "web", Sync: []map[string]interface{}{ + {"from": "./", "to": "/app", "exclude": "node_modules"}, + }}}) + require.Error(t, err) + assert.Contains(t, err.Error(), "sync[0].exclude") + + _, err = convertTargets([]engine.RawDevTarget{{Name: "web", Sync: []map[string]interface{}{ + {"from": "./", "to": "/app", "polling": "true"}, + }}}) + require.Error(t, err) + assert.Contains(t, err.Error(), "sync[0].polling") +} + +// {name: "X", value: undefined} used to set the env var to the string "". +func TestConvertTargets_EnvValues(t *testing.T) { + targets, err := convertTargets([]engine.RawDevTarget{{Name: "web", Env: []map[string]interface{}{ + {"name": "UNSET", "value": nil}, + {"name": "MISSING"}, + {"name": "PORT", "value": int64(8080)}, + {"name": "DEBUG", "value": true}, + }}}) + require.NoError(t, err) + assert.Equal(t, []EnvVar{{"UNSET", ""}, {"MISSING", ""}, {"PORT", "8080"}, {"DEBUG", "true"}}, targets[0].Env) + + _, err = convertTargets([]engine.RawDevTarget{{Name: "web", Env: []map[string]interface{}{ + {"name": "OBJ", "value": map[string]interface{}{"a": int64(1)}}, + }}}) + require.Error(t, err) + assert.Contains(t, err.Error(), "env[0].value") +} + +const webDeploymentCT = ` +__ct_resources.push({ + apiVersion: "apps/v1", + kind: "Deployment", + metadata: { name: "web" }, + spec: { + selector: { matchLabels: { app: "web" } }, + template: { + metadata: { labels: { app: "web" } }, + spec: { containers: [{ name: "app", image: "web:1" }] }, + }, + }, +}); +` + +func writeDevProject(t *testing.T, devCT string) string { + t.Helper() + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "main.ct"), []byte(webDeploymentCT), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "dev.ct"), []byte(devCT), 0o644)) + return dir +} + +func useFakeCluster(t *testing.T, cluster k8s.Cluster) { + t.Helper() + orig := newClusterFn + newClusterFn = func(string, string) (k8s.Cluster, error) { return cluster, nil } + t.Cleanup(func() { newClusterFn = orig }) +} + +// Relative sync sources were resolved against the process working directory +// instead of the project directory (RunOpts.Dir). +func TestRun_SyncFromIsRelativeToProjectDir(t *testing.T) { + silenceDevLog(t) + t.Setenv("HOME", t.TempDir()) + dir := writeDevProject(t, `config({ namespace: "dev" }) +dev("web", { sync: [{ from: "./src", to: "/app" }], terminal: "sh" }) +`) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "src"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "src", "index.js"), []byte("ok"), 0o644)) + + fake := k8stest.NewFake() + fake.AddPod(&k8stest.FakePod{Name: "web-x", Namespace: "dev", Labels: k8s.Selector{"app": "web"}, Healthy: true, Containers: []string{"app"}}) + var mu sync.Mutex + var tarred []string + fake.ExecHook = func(_, _ string, opts k8s.ExecOpts) error { + if opts.Command[0] == "tar" { + body, err := io.ReadAll(opts.Stdin) + if err != nil { + return err + } + tr := tar.NewReader(bytes.NewReader(body)) + for h, err := tr.Next(); err == nil; h, err = tr.Next() { + mu.Lock() + tarred = append(tarred, h.Name) + mu.Unlock() + } + } + return nil + } + useFakeCluster(t, fake) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + err := Run(ctx, RunOpts{Dir: dir, Stdin: strings.NewReader(""), Stdout: &bytes.Buffer{}, Stderr: &bytes.Buffer{}}) + require.NoError(t, err) + require.NoError(t, ctx.Err(), "Run should end with the terminal, not by timeout") + mu.Lock() + defer mu.Unlock() + assert.Contains(t, tarred, "index.js") +} + +// A sync source that does not exist or is a file used to fail only after the +// resources had been applied, with "stat ...: no such file or directory" or +// "watch root must be a directory" and no hint which rule was wrong. +func TestRun_InvalidSyncSourceFailsBeforeApply(t *testing.T) { + silenceDevLog(t) + t.Setenv("HOME", t.TempDir()) + dir := writeDevProject(t, `config({ namespace: "dev" }) +dev("web", { sync: [{ from: "./package.json", to: "/app/package.json" }] }) +`) + require.NoError(t, os.WriteFile(filepath.Join(dir, "package.json"), []byte("{}"), 0o644)) + + fake := k8stest.NewFake() + useFakeCluster(t, fake) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + err := Run(ctx, RunOpts{Dir: dir, Stdin: strings.NewReader(""), Stdout: &bytes.Buffer{}, Stderr: &bytes.Buffer{}}) + require.Error(t, err) + assert.Contains(t, err.Error(), `target "web": sync[0].from`) + assert.Contains(t, err.Error(), "not a directory") + assert.Empty(t, fake.ApplyCalls, "nothing should be applied for an invalid dev.ct") +} + +// runDevSession used to swap the global os.Stderr for /dev/null while the +// features were already running. client-go reports port-forward errors via +// klog, which writes to os.Stderr from those goroutines: a data race (and the +// /dev/null file was closed under late writers). +func TestRunDevSession_TerminalModeDoesNotRaceOnStderr(t *testing.T) { + silenceDevLog(t) + + dc := newDevCluster() + dc.PortForwardFn = func(ctx context.Context, _ string, _ k8s.Selector, _ []k8s.PortRule) error { + for ctx.Err() == nil { + fmt.Fprint(os.Stderr, "") // what klog's stderr output does on every log line + time.Sleep(time.Millisecond) + } + return ctx.Err() + } + dc.ExecFn = func(_ context.Context, _ string, _ k8s.Selector, _ k8s.ExecOpts) error { + time.Sleep(20 * time.Millisecond) + return nil + } + + require.NoError(t, startDevFeatures(context.Background(), dc, "ns", []Target{{ + Name: "web", Selector: map[string]string{"app": "web"}, + Ports: []PortRule{{Local: 8080, Remote: 80}}, + Terminal: "bash", + }}, &bytes.Buffer{})) +} + +// Library logging (klog from client-go, the standard logger) must not draw +// over the interactive terminal, and must work again afterwards. +func TestRunDevSession_SilencesLibraryLogsOnlyDuringTerminal(t *testing.T) { + silenceDevLog(t) + var stdLog bytes.Buffer + origLog := log.Writer() + log.SetOutput(&stdLog) + t.Cleanup(func() { log.SetOutput(origLog) }) + + klogOut := &syncBuffer{} + klog.LogToStderr(false) + klog.SetOutput(klogOut) + t.Cleanup(func() { + klog.SetOutput(io.Discard) + klog.LogToStderr(true) + }) + + dc := newDevCluster() + dc.ExecFn = func(_ context.Context, _ string, _ k8s.Selector, _ k8s.ExecOpts) error { + log.Print("std-during-terminal") + klog.Info("klog-during-terminal") + return nil + } + + require.NoError(t, startDevFeatures(context.Background(), dc, "ns", + []Target{{Name: "web", Terminal: "bash"}}, &bytes.Buffer{})) + + log.Print("std-after") + klog.Info("klog-after") + klog.Flush() + assert.NotContains(t, stdLog.String(), "during-terminal") + assert.Contains(t, stdLog.String(), "std-after") + assert.NotContains(t, klogOut.String(), "during-terminal") + assert.Contains(t, klogOut.String(), "klog-after") +} + +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// Log streams of several targets write to the same RunOpts.Stdout from +// different goroutines; any io.Writer must be safe to pass. +func TestStartDevFeatures_LogStreamsShareStdoutSafely(t *testing.T) { + silenceDevLog(t) + + fake := k8stest.NewFake() + for _, name := range []string{"api", "web"} { + fake.AddPod(&k8stest.FakePod{ + Name: name + "-x", Namespace: "ns", Labels: k8s.Selector{"app": name}, Healthy: true, + LogContent: strings.Repeat(name+" log line\n", 200), + }) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + + var out bytes.Buffer + require.NoError(t, startDevFeatures(ctx, fake, "ns", []Target{ + {Name: "api", Selector: map[string]string{"app": "api"}}, + {Name: "web", Selector: map[string]string{"app": "web"}}, + }, &out)) + assert.Equal(t, 200, strings.Count(out.String(), "api log line\n")) + assert.Equal(t, 200, strings.Count(out.String(), "web log line\n")) +} + +func TestConvertTargets_RejectsDuplicateAndEmptyNames(t *testing.T) { + _, err := convertTargets([]engine.RawDevTarget{{Name: "web"}, {Name: "web"}}) + require.Error(t, err) + assert.Contains(t, err.Error(), `"web" is defined more than once`) + + _, err = convertTargets([]engine.RawDevTarget{{Name: " "}}) + require.Error(t, err) + assert.Contains(t, err.Error(), "name") +} + +// A typo in an explicitly given --env-file used to be ignored silently, so +// env() quietly returned its defaults. +func TestLoadEnvVars_MissingRequiredFileIsAnError(t *testing.T) { + _, err := loadEnvVars(t.TempDir(), ".env.dvelopment", true) + require.Error(t, err) + assert.Contains(t, err.Error(), ".env.dvelopment") + + _, err = loadEnvVars(t.TempDir(), ".env", false) + require.NoError(t, err, "the default .env is optional") +} + +// main.ct was rendered without the release name, so `Release.name` was "" +// under ct dev while ct template/apply set it: names built from it differed +// (e.g. "-web" instead of "dev-web") and dev targets did not match. +func TestRun_MainCtSeesReleaseName(t *testing.T) { + silenceDevLog(t) + t.Setenv("HOME", t.TempDir()) + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "main.ct"), []byte(` +__ct_resources.push({ + apiVersion: "apps/v1", + kind: "Deployment", + metadata: { name: Release.name + "-web" }, + spec: { + selector: { matchLabels: { app: "web" } }, + template: { metadata: { labels: { app: "web" } }, spec: { containers: [{ name: "app", image: "web:1" }] } }, + }, +}); +`), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "dev.ct"), []byte(`config({ namespace: "dev" }) +dev("my-dev-web", { terminal: "sh" }) +`), 0o644)) + + fake := k8stest.NewFake() + fake.AddPod(&k8stest.FakePod{Name: "web-x", Namespace: "dev", Labels: k8s.Selector{"app": "web"}, Healthy: true}) + fake.ExecHook = func(_, _ string, _ k8s.ExecOpts) error { return nil } + useFakeCluster(t, fake) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + require.NoError(t, Run(ctx, RunOpts{Dir: dir, ReleaseName: "my-dev", Stdin: strings.NewReader(""), Stdout: &bytes.Buffer{}, Stderr: &bytes.Buffer{}})) + require.Len(t, fake.ApplyCalls, 1) + meta := fake.ApplyCalls[0].Resources[0]["metadata"].(map[string]interface{}) + assert.Equal(t, "my-dev-web", meta["name"]) +} + +// The health watcher watches the pod resolved when the session starts; the +// terminal used to resolve a pod again by selector and could end up in a +// different one (e.g. during the rollout triggered by ct dev's own apply), +// so the watcher killed a healthy terminal or missed its pod dying. +func TestRunDevSession_TerminalUsesTheWatchedPod(t *testing.T) { + silenceDevLog(t) + + dc := newDevCluster() + var waits int32 + dc.WaitPodFn = func(context.Context, string, k8s.Selector) (string, error) { + if atomic.AddInt32(&waits, 1) == 1 { + return "web-old", nil + } + return "web-new", nil + } + dc.ExecFn = func(context.Context, string, k8s.Selector, k8s.ExecOpts) error { + // Keep the terminal open until the health watcher has started. + for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline); time.Sleep(time.Millisecond) { + dc.mu.Lock() + started := len(dc.watchedPods) > 0 + dc.mu.Unlock() + if started { + break + } + } + return nil + } + + require.NoError(t, startDevFeatures(context.Background(), dc, "ns", + []Target{{Name: "web", Selector: map[string]string{"app": "web"}, Terminal: "bash"}}, &bytes.Buffer{})) + + dc.mu.Lock() + defer dc.mu.Unlock() + require.Equal(t, []string{"web-old"}, dc.watchedPods) + assert.Equal(t, []string{"web-old"}, dc.terminalPods, "the terminal must run in the pod the health watcher watches") +} diff --git a/internal/output/serializer.go b/internal/output/serializer.go index 4b3906a..3891bba 100644 --- a/internal/output/serializer.go +++ b/internal/output/serializer.go @@ -1,26 +1,27 @@ package output import ( + "bytes" "encoding/json" "fmt" "strings" + "github.com/cloudticon/ct/pkg/manifest" "gopkg.in/yaml.v3" ) type Resource = map[string]interface{} func Serialize(resources []Resource, format string) (string, error) { - cleaned := make([]Resource, len(resources)) - for i, r := range resources { - cleaned[i] = cleanNilFields(r).(Resource) + for _, r := range resources { + manifest.Clean(r) } switch format { case "yaml", "": - return serializeYAML(cleaned) + return serializeYAML(resources) case "json": - return serializeJSON(cleaned) + return serializeJSON(resources) default: return "", fmt.Errorf("unsupported output format: %s", format) } @@ -29,50 +30,27 @@ func Serialize(resources []Resource, format string) (string, error) { func serializeYAML(resources []Resource) (string, error) { var docs []string for _, r := range resources { - data, err := yaml.Marshal(r) - if err != nil { + var buf bytes.Buffer + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + if err := enc.Encode(r); err != nil { + return "", fmt.Errorf("yaml marshal error: %w", err) + } + if err := enc.Close(); err != nil { return "", fmt.Errorf("yaml marshal error: %w", err) } - docs = append(docs, strings.TrimRight(string(data), "\n")) + docs = append(docs, strings.TrimRight(buf.String(), "\n")) } return strings.Join(docs, "\n---\n") + "\n", nil } func serializeJSON(resources []Resource) (string, error) { + if resources == nil { + resources = []Resource{} + } data, err := json.MarshalIndent(resources, "", " ") if err != nil { return "", fmt.Errorf("json marshal error: %w", err) } return string(data) + "\n", nil } - -func cleanNilFields(v interface{}) interface{} { - switch val := v.(type) { - case map[string]interface{}: - cleaned := make(map[string]interface{}, len(val)) - for k, v := range val { - cv := cleanNilFields(v) - if cv != nil { - cleaned[k] = cv - } - } - if len(cleaned) == 0 { - return nil - } - return cleaned - case []interface{}: - cleaned := make([]interface{}, 0, len(val)) - for _, item := range val { - cv := cleanNilFields(item) - if cv != nil { - cleaned = append(cleaned, cv) - } - } - if len(cleaned) == 0 { - return nil - } - return cleaned - default: - return v - } -} diff --git a/internal/output/serializer_test.go b/internal/output/serializer_test.go index 2bb524e..327ab62 100644 --- a/internal/output/serializer_test.go +++ b/internal/output/serializer_test.go @@ -3,7 +3,7 @@ package output_test import ( "testing" - "github.com/cloudticon/ctts/internal/output" + "github.com/cloudticon/ct/internal/output" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -183,7 +183,7 @@ func TestSerialize_CleansNilInArrays(t *testing.T) { assert.NotContains(t, result, "command") } -func TestSerialize_RemovesEmptyMapsAfterCleaning(t *testing.T) { +func TestSerialize_KeepsObjectsEmptiedByNullRemoval(t *testing.T) { resources := []output.Resource{ { "apiVersion": "v1", @@ -202,8 +202,8 @@ func TestSerialize_RemovesEmptyMapsAfterCleaning(t *testing.T) { result, err := output.Serialize(resources, "yaml") require.NoError(t, err) - assert.NotContains(t, result, "selector") - assert.NotContains(t, result, "spec") + assert.Contains(t, result, "selector: {}") + assert.NotContains(t, result, "removed") } func TestSerialize_EmptyResourceList(t *testing.T) { @@ -234,3 +234,55 @@ func TestSerialize_PreservesZeroValues(t *testing.T) { assert.Contains(t, result, "enabled: false") assert.Contains(t, result, `label: ""`) } + +func TestSerialize_KeepsAuthoredEmptyObjects(t *testing.T) { + resources := []output.Resource{ + { + "apiVersion": "v1", + "kind": "Pod", + "metadata": map[string]interface{}{"name": "p"}, + "spec": map[string]interface{}{ + "volumes": []interface{}{ + map[string]interface{}{"name": "tmp", "emptyDir": map[string]interface{}{}}, + }, + }, + }, + } + + result, err := output.Serialize(resources, "yaml") + + require.NoError(t, err) + assert.Contains(t, result, "emptyDir: {}") +} + +func TestSerialize_EmptyResourceDoesNotPanic(t *testing.T) { + result, err := output.Serialize([]output.Resource{{"labels": nil}}, "yaml") + + require.NoError(t, err) + assert.Equal(t, "{}\n", result) +} + +func TestSerialize_YAMLTwoSpaceIndent(t *testing.T) { + resources := []output.Resource{ + { + "apiVersion": "v1", + "kind": "Service", + "metadata": map[string]interface{}{"name": "svc"}, + "spec": map[string]interface{}{ + "ports": []interface{}{map[string]interface{}{"port": 80}}, + }, + }, + } + + result, err := output.Serialize(resources, "yaml") + + require.NoError(t, err) + assert.Equal(t, "apiVersion: v1\nkind: Service\nmetadata:\n name: svc\nspec:\n ports:\n - port: 80\n", result) +} + +func TestSerialize_JSONEmptyListIsArray(t *testing.T) { + result, err := output.Serialize(nil, "json") + + require.NoError(t, err) + assert.Equal(t, "[]\n", result) +} diff --git a/internal/scaffold/scaffold.go b/internal/scaffold/scaffold.go index e2d8aa5..681319d 100644 --- a/internal/scaffold/scaffold.go +++ b/internal/scaffold/scaffold.go @@ -4,48 +4,109 @@ import ( "fmt" "os" "path/filepath" + "strings" ) -const mainCtTemplate = `import { deployment } from "https://github.com/cloudticon/k8s@master"; -import { service } from "https://github.com/cloudticon/k8s@master"; +const mainCtTemplate = `import { webApp } from "github.com/cloudticon/k8s-factories@master"; -const app = deployment({ - name: "web-app", +// webApp registers a Deployment and a Service (plus HPA/Ingress when asked). +// Drop down to primitives from github.com/cloudticon/k8s for anything else. +webApp({ + name: Values.name, image: Values.image, + port: Values.port, replicas: Values.replicas, - ports: [{ containerPort: 8080 }], -}); - -service({ - name: "web-app-svc", - selector: { app: app.metadata.name }, - ports: [{ port: 80, targetPort: 8080 }], }); ` const valuesJsonTemplate = `{ - "image": "nginx:1.25", - "replicas": 3 + "name": "web-app", + "image": "nginx:1.27", + "port": 80, + "replicas": 2 } ` -func Init(dir string) error { - if err := os.MkdirAll(dir, 0o755); err != nil { - return fmt.Errorf("creating project directory %s: %w", dir, err) - } +const agentsMdTemplate = "# Kubernetes manifests (ct)\n" + ` +This directory is a [ct](https://github.com/cloudticon/ct) project. ` + "`main.ct`" + ` is +TypeScript that registers Kubernetes objects; ` + "`values.json`" + ` holds settings, +read in code as ` + "`Values.`" + `. + +## Commands + +- Render and validate: ` + "`ct template . -n `" + `. On problems + it exits non-zero with ` + "`file:line:column`" + ` diagnostics pointing at the .ct + code; add ` + "`--error-format json`" + ` for machine-readable errors. +- Environments: ` + "`ct template . -f values.json -f values-prod.json`" + ` + (files deep-merge left to right); one-off overrides with ` + "`--set key=value`" + `. +- Deploy: ` + "`ct apply . -n `" + ` (server-side apply, prunes + objects removed from the code). Remove: ` + "`ct delete -n `" + `. +- Editor types: ` + "`ct types .`" + `. + +## Rules + +- Imports are URLs (` + "`github.com//@`" + `) or relative paths. + There is no npm. +- No async/await: rendering is synchronous. +- Prefer factories from github.com/cloudticon/k8s-factories (` + "`webApp`" + `, ...); + use primitives from github.com/cloudticon/k8s for other objects. +- Each object needs a unique kind + name + namespace. +- Run ` + "`ct template`" + ` after every change; it validates against the + Kubernetes API schema before anything reaches a cluster. +` + +// Options configures Init. +type Options struct { + // Force overwrites an existing main.ct and values.json. + Force bool +} +// Init writes a starter project into dir: main.ct, values.json and an +// AGENTS.md telling coding agents how to work with it. It refuses to touch an +// existing main.ct or values.json unless opts.Force is set. An existing +// AGENTS.md is never touched: it may be the repository's own. Init returns +// the files written. +func Init(dir string, opts Options) ([]string, error) { files := []struct { - path string - content string + name string + content string + optional bool // skipped when present, even with Force }{ - {filepath.Join(dir, "main.ct"), mainCtTemplate}, - {filepath.Join(dir, "values.json"), valuesJsonTemplate}, + {"main.ct", mainCtTemplate, false}, + {"values.json", valuesJsonTemplate, false}, + {"AGENTS.md", agentsMdTemplate, true}, + } + + if !opts.Force { + var existing []string + for _, f := range files { + if !f.optional && fileExists(filepath.Join(dir, f.name)) { + existing = append(existing, f.name) + } + } + if len(existing) > 0 { + return nil, fmt.Errorf("%s already exist(s) in %s; use --force to overwrite", strings.Join(existing, ", "), dir) + } } + + if err := os.MkdirAll(dir, 0o755); err != nil { + return nil, fmt.Errorf("creating project directory %s: %w", dir, err) + } + written := make([]string, 0, len(files)) for _, f := range files { - if err := os.WriteFile(f.path, []byte(f.content), 0o644); err != nil { - return fmt.Errorf("writing %s: %w", f.path, err) + path := filepath.Join(dir, f.name) + if f.optional && fileExists(path) { + continue } + if err := os.WriteFile(path, []byte(f.content), 0o644); err != nil { + return written, fmt.Errorf("writing %s: %w", path, err) + } + written = append(written, f.name) } + return written, nil +} - return nil +func fileExists(path string) bool { + _, err := os.Stat(path) + return err == nil } diff --git a/internal/scaffold/scaffold_test.go b/internal/scaffold/scaffold_test.go index 8692be3..577b6b7 100644 --- a/internal/scaffold/scaffold_test.go +++ b/internal/scaffold/scaffold_test.go @@ -5,7 +5,7 @@ import ( "path/filepath" "testing" - "github.com/cloudticon/ctts/internal/scaffold" + "github.com/cloudticon/ct/internal/scaffold" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -13,7 +13,8 @@ import ( func TestInit_CreatesDirectoryStructure(t *testing.T) { dir := filepath.Join(t.TempDir(), "project") - require.NoError(t, scaffold.Init(dir)) + _, err := scaffold.Init(dir, scaffold.Options{}) + require.NoError(t, err) info, err := os.Stat(dir) require.NoError(t, err) @@ -23,9 +24,10 @@ func TestInit_CreatesDirectoryStructure(t *testing.T) { func TestInit_CreatesStarterFiles(t *testing.T) { dir := filepath.Join(t.TempDir(), "project") - require.NoError(t, scaffold.Init(dir)) + _, err := scaffold.Init(dir, scaffold.Options{}) + require.NoError(t, err) - for _, name := range []string{"main.ct", "values.json"} { + for _, name := range []string{"main.ct", "values.json", "AGENTS.md"} { path := filepath.Join(dir, name) info, err := os.Stat(path) require.NoError(t, err, "file should exist: %s", name) @@ -36,21 +38,22 @@ func TestInit_CreatesStarterFiles(t *testing.T) { func TestInit_MainCtContainsImports(t *testing.T) { dir := filepath.Join(t.TempDir(), "project") - require.NoError(t, scaffold.Init(dir)) + _, err := scaffold.Init(dir, scaffold.Options{}) + require.NoError(t, err) content, err := os.ReadFile(filepath.Join(dir, "main.ct")) require.NoError(t, err) s := string(content) - assert.Contains(t, s, "https://github.com/cloudticon/k8s") - assert.Contains(t, s, "deployment(") - assert.Contains(t, s, "service(") + assert.Contains(t, s, `from "github.com/cloudticon/k8s-factories@master"`) + assert.Contains(t, s, "webApp(") } func TestInit_ValuesJsonHasDefaults(t *testing.T) { dir := filepath.Join(t.TempDir(), "project") - require.NoError(t, scaffold.Init(dir)) + _, err := scaffold.Init(dir, scaffold.Options{}) + require.NoError(t, err) content, err := os.ReadFile(filepath.Join(dir, "values.json")) require.NoError(t, err) @@ -60,10 +63,36 @@ func TestInit_ValuesJsonHasDefaults(t *testing.T) { assert.Contains(t, s, `"replicas"`) } +func TestInit_RefusesToOverwrite(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "main.ct"), []byte("// my work"), 0o644)) + + _, err := scaffold.Init(dir, scaffold.Options{}) + + require.Error(t, err) + assert.Contains(t, err.Error(), "main.ct already exist(s)") + content, _ := os.ReadFile(filepath.Join(dir, "main.ct")) + assert.Equal(t, "// my work", string(content)) + assert.NoFileExists(t, filepath.Join(dir, "values.json"), "nothing is written when refusing") +} + +func TestInit_ForceOverwrites(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "main.ct"), []byte("// old"), 0o644)) + + written, err := scaffold.Init(dir, scaffold.Options{Force: true}) + + require.NoError(t, err) + assert.Equal(t, []string{"main.ct", "values.json", "AGENTS.md"}, written) + content, _ := os.ReadFile(filepath.Join(dir, "main.ct")) + assert.Contains(t, string(content), "webApp(") +} + func TestInit_DoesNotCreateLegacyFiles(t *testing.T) { dir := filepath.Join(t.TempDir(), "project") - require.NoError(t, scaffold.Init(dir)) + _, err := scaffold.Init(dir, scaffold.Options{}) + require.NoError(t, err) for _, name := range []string{"tsconfig.json", ".gitignore", "ct.ts", "values.ts"} { path := filepath.Join(dir, name) @@ -71,6 +100,20 @@ func TestInit_DoesNotCreateLegacyFiles(t *testing.T) { assert.True(t, os.IsNotExist(err), "legacy file should not exist: %s", name) } - _, err := os.Stat(filepath.Join(dir, ".ctts")) + _, err = os.Stat(filepath.Join(dir, ".ctts")) assert.True(t, os.IsNotExist(err), ".ctts directory should not exist") } + +func TestInit_KeepsAnExistingAgentsMd(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "AGENTS.md"), []byte("# repo rules"), 0o644)) + + written, err := scaffold.Init(dir, scaffold.Options{}) + require.NoError(t, err, "an existing AGENTS.md doesn't block init") + assert.Equal(t, []string{"main.ct", "values.json"}, written) + + _, err = scaffold.Init(dir, scaffold.Options{Force: true}) + require.NoError(t, err) + content, _ := os.ReadFile(filepath.Join(dir, "AGENTS.md")) + assert.Equal(t, "# repo rules", string(content), "--force never overwrites AGENTS.md") +} diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index 91a4eee..0b97fed 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "os/exec" + "path" "path/filepath" "regexp" "strings" @@ -16,14 +17,53 @@ type PackageRef struct { Version string } -var packageURLRegex = regexp.MustCompile(`^https://([^/]+)/([^/]+)/([^/@]+)(?:@(.+))?$`) +var packageURLRegex = regexp.MustCompile(`^https://([^/@]+)/([^@]+)(?:@(.+))?$`) + +// IsWellKnownHost reports hosts whose packages are always host/owner/repo. +// Other hosts may use vanity paths (host/repo) or nested groups +// (host/group/subgroup/repo). +func IsWellKnownHost(host string) bool { + switch host { + case "github.com", "gitlab.com", "bitbucket.org": + return true + } + return false +} + +var ( + hostRe = regexp.MustCompile(`^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(:[0-9]+)?$`) + segmentRe = regexp.MustCompile(`^[A-Za-z0-9_.-]+$`) + versionRe = regexp.MustCompile(`^[A-Za-z0-9_.+-]+(/[A-Za-z0-9_.+-]+)*$`) +) func ParsePackageURL(rawURL string) (*PackageRef, error) { + invalid := fmt.Errorf("invalid package URL: %s (expected https://host/owner/repo[@version])", rawURL) m := packageURLRegex.FindStringSubmatch(rawURL) - if m == nil { - return nil, fmt.Errorf("invalid package URL: %s (expected https://host/owner/repo[@version])", rawURL) + if m == nil || !hostRe.MatchString(m[1]) { + return nil, invalid + } + segments := strings.Split(m[2], "/") + for _, s := range segments { + if !segmentRe.MatchString(s) || s == "." || s == ".." { + return nil, invalid + } + } + if IsWellKnownHost(m[1]) && len(segments) != 2 { + return nil, invalid + } + // Versions are git refs: they may contain '/' (feature/x) but never '..' + // or a leading '-', which would also let them escape the cache directory + // or pass for a git option. + if v := m[3]; v != "" && (!versionRe.MatchString(v) || strings.Contains(v, "..") || strings.HasPrefix(v, "-")) { + return nil, fmt.Errorf("invalid version %q in package URL %s", v, rawURL) } - return &PackageRef{Host: m[1], Owner: m[2], Repo: m[3], Version: m[4]}, nil + last := len(segments) - 1 + return &PackageRef{ + Host: m[1], + Owner: strings.Join(segments[:last], "/"), + Repo: segments[last], + Version: m[3], + }, nil } func (r *PackageRef) CacheKey() string { @@ -31,11 +71,27 @@ func (r *PackageRef) CacheKey() string { if version == "" { version = "_default" } + // Keep branch names like feature/x in one directory. + version = strings.ReplaceAll(version, "/", "%2F") return filepath.Join(r.Host, r.Owner, r.Repo+"@"+version) } +// packageDir is where a package lives in the cache. It refuses paths that +// would land outside the cache directory. +func packageDir(ref *PackageRef) (string, error) { + cacheBase, err := CacheDir() + if err != nil { + return "", err + } + dir := filepath.Join(cacheBase, ref.CacheKey()) + if rel, err := filepath.Rel(cacheBase, dir); err != nil || rel == "." || strings.HasPrefix(rel, "..") { + return "", fmt.Errorf("package %s resolves outside the cache directory", ref.GitURL()) + } + return dir, nil +} + func (r *PackageRef) GitURL() string { - return fmt.Sprintf("https://%s/%s/%s.git", r.Host, r.Owner, r.Repo) + return "https://" + path.Join(r.Host, r.Owner, r.Repo) + ".git" } func CacheDir() (string, error) { @@ -54,13 +110,11 @@ func Resolve(rawURL string) (string, error) { return "", err } - cacheBase, err := CacheDir() + pkgDir, err := packageDir(ref) if err != nil { return "", err } - pkgDir := filepath.Join(cacheBase, ref.CacheKey()) - if dirHasFiles(pkgDir) { return pkgDir, nil } @@ -79,68 +133,66 @@ func Invalidate(rawURL string) error { return err } - cacheBase, err := CacheDir() + pkgDir, err := packageDir(ref) if err != nil { return err } + return os.RemoveAll(pkgDir) +} - return os.RemoveAll(filepath.Join(cacheBase, ref.CacheKey())) +// cloneFn fetches a package into an empty directory. Tests replace it. +var cloneFn = func(ref *PackageRef, dir string) error { + args := []string{"clone", "--depth", "1"} + if ref.Version != "" { + args = append(args, "--branch", ref.Version) + } + args = append(args, ref.GitURL(), dir) + + cmd := exec.Command("git", args...) + // Fail instead of waiting for a credential prompt nobody may answer + // (CI, AI agents); credential helpers still work. + cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0") + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("git clone %s: %s: %w", ref.GitURL(), strings.TrimSpace(string(out)), err) + } + return nil } +// download clones into a temporary sibling of destDir and renames it into +// place, so an interrupted or failed clone never leaves a half-filled cache +// entry that later runs would trust. func download(ref *PackageRef, destDir string) error { - tmpDir, err := os.MkdirTemp("", "ct-download-*") + parent := filepath.Dir(destDir) + if err := os.MkdirAll(parent, 0o755); err != nil { + return fmt.Errorf("creating cache directory: %w", err) + } + tmpDir, err := os.MkdirTemp(parent, ".download-*") if err != nil { return fmt.Errorf("creating temp dir: %w", err) } defer os.RemoveAll(tmpDir) - gitURL := ref.GitURL() - - args := []string{"clone", "--depth", "1"} - if ref.Version != "" { - args = append(args, "--branch", ref.Version) + if err := cloneFn(ref, tmpDir); err != nil { + return err } - args = append(args, gitURL, tmpDir) - - if out, err := exec.Command("git", args...).CombinedOutput(); err != nil { - return fmt.Errorf("git clone %s: %s: %w", gitURL, strings.TrimSpace(string(out)), err) + if err := os.RemoveAll(filepath.Join(tmpDir, ".git")); err != nil { + return fmt.Errorf("removing .git: %w", err) } - if err := os.MkdirAll(filepath.Dir(destDir), 0o755); err != nil { - return fmt.Errorf("creating cache directory: %w", err) + // An empty directory left behind by an older ct would block the rename. + if !dirHasFiles(destDir) { + _ = os.Remove(destDir) } - - return copyDir(tmpDir, destDir) + if err := os.Rename(tmpDir, destDir); err != nil { + if dirHasFiles(destDir) { + return nil // a concurrent ct run finished the same download first + } + return fmt.Errorf("installing %s into cache: %w", ref.GitURL(), err) + } + return nil } func dirHasFiles(dir string) bool { entries, err := os.ReadDir(dir) return err == nil && len(entries) > 0 } - -func copyDir(src, dst string) error { - return filepath.WalkDir(src, func(path string, d os.DirEntry, err error) error { - if err != nil { - return err - } - - rel, _ := filepath.Rel(src, path) - if strings.HasPrefix(rel, ".git") { - if d.IsDir() { - return filepath.SkipDir - } - return nil - } - - target := filepath.Join(dst, rel) - if d.IsDir() { - return os.MkdirAll(target, 0o755) - } - - data, err := os.ReadFile(path) - if err != nil { - return fmt.Errorf("reading %s: %w", path, err) - } - return os.WriteFile(target, data, 0o644) - }) -} diff --git a/pkg/cache/cache_test.go b/pkg/cache/cache_test.go index 3f20f9d..65d23b4 100644 --- a/pkg/cache/cache_test.go +++ b/pkg/cache/cache_test.go @@ -1,9 +1,12 @@ package cache_test import ( + "errors" + "os" + "path/filepath" "testing" - "github.com/cloudticon/ctts/pkg/cache" + "github.com/cloudticon/ct/pkg/cache" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -84,10 +87,25 @@ func TestParsePackageURL_NoVersion(t *testing.T) { } } +func TestParsePackageURL_CustomHosts(t *testing.T) { + vanity, err := cache.ParsePackageURL("https://custom.dev/mylib@v1") + require.NoError(t, err) + assert.Equal(t, "https://custom.dev/mylib.git", vanity.GitURL()) + assert.Equal(t, filepath.Join("custom.dev", "mylib@v1"), vanity.CacheKey()) + + nested, err := cache.ParsePackageURL("https://git.example.com/group/team/repo@main") + require.NoError(t, err) + assert.Equal(t, "group/team", nested.Owner) + assert.Equal(t, "repo", nested.Repo) + assert.Equal(t, "https://git.example.com/group/team/repo.git", nested.GitURL()) +} + func TestParsePackageURL_Invalid(t *testing.T) { tests := []string{ "github.com/owner/repo", "https://github.com/owner", + "https://github.com/owner/repo/sub@v1", + "https://custom.dev//x", "http://github.com/owner/repo@v1", "", "not-a-url", @@ -128,3 +146,111 @@ func TestCacheDir_ReturnsPath(t *testing.T) { assert.Contains(t, dir, ".ct") assert.Contains(t, dir, "cache") } + +func stubClone(t *testing.T, fn func(ref *cache.PackageRef, dir string) error) *int { + t.Helper() + calls := 0 + restore := cache.SetCloneFunc(func(ref *cache.PackageRef, dir string) error { + calls++ + return fn(ref, dir) + }) + t.Cleanup(restore) + return &calls +} + +func TestResolve_DownloadsOnceAndStripsGitDir(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + calls := stubClone(t, func(ref *cache.PackageRef, dir string) error { + require.NoError(t, os.MkdirAll(filepath.Join(dir, ".git"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, ".github"), 0o755)) + return os.WriteFile(filepath.Join(dir, "index.ts"), []byte("export {}"), 0o644) + }) + + dir, err := cache.Resolve("https://github.com/acme/lib@v1") + require.NoError(t, err) + again, err := cache.Resolve("https://github.com/acme/lib@v1") + require.NoError(t, err) + + assert.Equal(t, dir, again) + assert.Equal(t, 1, *calls, "second resolve is served from cache") + assert.FileExists(t, filepath.Join(dir, "index.ts")) + assert.NoDirExists(t, filepath.Join(dir, ".git")) + assert.DirExists(t, filepath.Join(dir, ".github")) +} + +func TestResolve_FailedCloneLeavesNoCacheEntry(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + stubClone(t, func(ref *cache.PackageRef, dir string) error { + require.NoError(t, os.WriteFile(filepath.Join(dir, "partial.ts"), []byte("x"), 0o644)) + return errors.New("network down") + }) + + _, err := cache.Resolve("https://github.com/acme/lib@v1") + require.Error(t, err) + + cacheDir, _ := cache.CacheDir() + entries, _ := os.ReadDir(filepath.Join(cacheDir, "github.com", "acme")) + assert.Empty(t, entries, "no half-downloaded package and no temp dir left behind") +} + +func TestResolve_ReplacesEmptyLeftoverDir(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + cacheDir, _ := cache.CacheDir() + require.NoError(t, os.MkdirAll(filepath.Join(cacheDir, "github.com", "acme", "lib@v1"), 0o755)) + stubClone(t, func(ref *cache.PackageRef, dir string) error { + return os.WriteFile(filepath.Join(dir, "index.ts"), []byte("export {}"), 0o644) + }) + + dir, err := cache.Resolve("https://github.com/acme/lib@v1") + require.NoError(t, err) + assert.FileExists(t, filepath.Join(dir, "index.ts")) +} + +func TestInvalidate_ForcesRedownload(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + calls := stubClone(t, func(ref *cache.PackageRef, dir string) error { + return os.WriteFile(filepath.Join(dir, "index.ts"), []byte("export {}"), 0o644) + }) + + _, err := cache.Resolve("https://github.com/acme/lib@main") + require.NoError(t, err) + require.NoError(t, cache.Invalidate("https://github.com/acme/lib@main")) + _, err = cache.Resolve("https://github.com/acme/lib@main") + require.NoError(t, err) + + assert.Equal(t, 2, *calls) +} + +func TestParsePackageURL_RejectsPathTraversal(t *testing.T) { + for _, url := range []string{ + "https://github.com/o/r@x/../../../../tmp/victim", + "https://github.com/o/r@..", + "https://github.com/../r@v1", + "https://custom.dev/../../etc@v1", + "https://custom.dev/./x@v1", + "https://../x/y@v1", + "https://github.com/o/r@-upload-pack=evil", + "https://github.com/o/r@v1/", + } { + _, err := cache.ParsePackageURL(url) + assert.Error(t, err, url) + } +} + +func TestInvalidate_NeverLeavesTheCache(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + victim := filepath.Join(home, "victim") + require.NoError(t, os.MkdirAll(victim, 0o755)) + + err := cache.Invalidate("https://github.com/o/r@x/../../../../../victim") + + require.Error(t, err) + assert.DirExists(t, victim) +} + +func TestCacheKey_BranchWithSlashIsOneDirectory(t *testing.T) { + ref, err := cache.ParsePackageURL("https://github.com/o/r@feature/new-ui") + require.NoError(t, err) + assert.Equal(t, filepath.Join("github.com", "o", "r@feature%2Fnew-ui"), ref.CacheKey()) +} diff --git a/pkg/cache/export_test.go b/pkg/cache/export_test.go new file mode 100644 index 0000000..5f68756 --- /dev/null +++ b/pkg/cache/export_test.go @@ -0,0 +1,8 @@ +package cache + +// SetCloneFunc swaps the git clone used by Resolve and returns a restore func. +func SetCloneFunc(fn func(ref *PackageRef, dir string) error) func() { + old := cloneFn + cloneFn = fn + return func() { cloneFn = old } +} diff --git a/pkg/diag/diag.go b/pkg/diag/diag.go new file mode 100644 index 0000000..6288b2c --- /dev/null +++ b/pkg/diag/diag.go @@ -0,0 +1,173 @@ +// Package diag defines the structured errors ct reports for bad .ct code and +// bad manifests. Every diagnostic carries what a human or an AI agent needs to +// fix the problem in one step: a stable code, the source position, the object +// and field involved, and a hint. +package diag + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" +) + +// Stable diagnostic codes. Tools may match on them; don't rename. +const ( + CodeError = "error" // anything without a more specific code + CodeSyntax = "syntax" + CodeImport = "import" + CodeAsync = "async-not-supported" + CodeRuntime = "runtime" + CodeTimeout = "timeout" + CodeDuplicate = "duplicate-resource" + CodeInvalidResource = "invalid-resource" + CodeUnknownKind = "unknown-kind" + CodeUnknownField = "unknown-field" + CodeInvalidValue = "invalid-value" + CodeMissingField = "missing-field" + CodeNamespaceNotFound = "namespace-not-found" +) + +// Frame is a position in a .ct/.ts source file. +type Frame struct { + File string `json:"file"` + Line int `json:"line"` + Column int `json:"column"` + Function string `json:"function,omitempty"` +} + +func (f Frame) String() string { + pos := fmt.Sprintf("%s:%d:%d", f.File, f.Line, f.Column) + if f.Function != "" { + return fmt.Sprintf("%s (%s)", f.Function, pos) + } + return pos +} + +// Diagnostic is one problem found while bundling, running or validating. +type Diagnostic struct { + Code string `json:"code"` + Message string `json:"message"` + // File/Line/Column locate the problem in the user's sources: the bad + // line for bundle errors, the throwing line for runtime errors, or the + // call that registered the object for manifest errors. + File string `json:"file,omitempty"` + Line int `json:"line,omitempty"` + Column int `json:"column,omitempty"` + // LineText is the source line, when known. + LineText string `json:"lineText,omitempty"` + // Resource names the object involved, e.g. `Deployment "web"`. + Resource string `json:"resource,omitempty"` + // Path is the field inside Resource, e.g. `spec.template.spec.containers[0].image`. + Path string `json:"path,omitempty"` + Hint string `json:"hint,omitempty"` + Stack []Frame `json:"stack,omitempty"` +} + +// At sets the source position from a frame. +func (d Diagnostic) At(f *Frame) Diagnostic { + if f != nil { + d.File, d.Line, d.Column = f.File, f.Line, f.Column + } + return d +} + +// AtChain sets the position from the first frame of a call chain (innermost +// first) and keeps the callers as the stack, so a problem built inside a +// helper still shows which call produced it. +func (d Diagnostic) AtChain(chain []Frame) Diagnostic { + if len(chain) == 0 { + return d + } + d = d.At(&chain[0]) + if len(chain) > 1 { + d.Stack = chain[1:] + } + return d +} + +// Chain renders a call chain as "lib/app.ct:3:5 <- main.ct:10:1". +func Chain(chain []Frame) string { + parts := make([]string, len(chain)) + for i, f := range chain { + parts[i] = fmt.Sprintf("%s:%d:%d", f.File, f.Line, f.Column) + } + return strings.Join(parts, " <- ") +} + +// Location returns "file:line:col", "file:line", "file" or "". +func (d Diagnostic) Location() string { + switch { + case d.File == "": + return "" + case d.Line == 0: + return d.File + case d.Column == 0: + return fmt.Sprintf("%s:%d", d.File, d.Line) + default: + return fmt.Sprintf("%s:%d:%d", d.File, d.Line, d.Column) + } +} + +// String renders the diagnostic for a terminal: +// +// main.ct:12:3: Deployment "web": spec.image: unknown field [unknown-field] +// 12 | image: "nginx", +// hint: container fields go under spec.template.spec.containers[] +func (d Diagnostic) String() string { + var b strings.Builder + if loc := d.Location(); loc != "" { + b.WriteString(loc) + b.WriteString(": ") + } + if d.Resource != "" { + b.WriteString(d.Resource) + b.WriteString(": ") + } + if d.Path != "" { + b.WriteString(d.Path) + b.WriteString(": ") + } + b.WriteString(d.Message) + if d.Code != "" { + fmt.Fprintf(&b, " [%s]", d.Code) + } + if d.LineText != "" { + fmt.Fprintf(&b, "\n %d | %s", d.Line, d.LineText) + } + for _, f := range d.Stack { + fmt.Fprintf(&b, "\n at %s", f) + } + if d.Hint != "" { + fmt.Fprintf(&b, "\n hint: %s", d.Hint) + } + return b.String() +} + +// List is an error made of one or more diagnostics. +type List []Diagnostic + +func (l List) Error() string { + parts := make([]string, len(l)) + for i, d := range l { + parts[i] = d.String() + } + return strings.Join(parts, "\n") +} + +// Errorf wraps a single diagnostic as an error. +func Errorf(code, format string, args ...interface{}) List { + return List{{Code: code, Message: fmt.Sprintf(format, args...)}} +} + +// JSON renders diagnostics as {"errors": [...]} for machine consumers. +func JSON(l List) []byte { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + enc.SetIndent("", " ") + _ = enc.Encode(struct { + Errors List `json:"errors"` + }{l}) + return buf.Bytes() +} diff --git a/pkg/diag/diag_test.go b/pkg/diag/diag_test.go new file mode 100644 index 0000000..41b2840 --- /dev/null +++ b/pkg/diag/diag_test.go @@ -0,0 +1,56 @@ +package diag_test + +import ( + "encoding/json" + "testing" + + "github.com/cloudticon/ct/pkg/diag" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestDiagnostic_String(t *testing.T) { + d := diag.Diagnostic{ + Code: diag.CodeUnknownField, + Message: "unknown field", + File: "main.ct", + Line: 12, + Column: 3, + LineText: `deployment({ name: "web", image: "nginx" });`, + Resource: `Deployment "web"`, + Path: "spec.image", + Hint: "container fields go under spec.template.spec.containers[]", + Stack: []diag.Frame{{File: "lib/app.ct", Line: 4, Column: 1, Function: "app"}}, + } + + assert.Equal(t, `main.ct:12:3: Deployment "web": spec.image: unknown field [unknown-field] + 12 | deployment({ name: "web", image: "nginx" }); + at app (lib/app.ct:4:1) + hint: container fields go under spec.template.spec.containers[]`, d.String()) +} + +func TestDiagnostic_LocationVariants(t *testing.T) { + assert.Equal(t, "", diag.Diagnostic{}.Location()) + assert.Equal(t, "a.ct", diag.Diagnostic{File: "a.ct"}.Location()) + assert.Equal(t, "a.ct:3", diag.Diagnostic{File: "a.ct", Line: 3}.Location()) + assert.Equal(t, "a.ct:3:7", diag.Diagnostic{File: "a.ct", Line: 3, Column: 7}.Location()) +} + +func TestList_ErrorJoinsDiagnostics(t *testing.T) { + l := diag.List{{Code: "a", Message: "first"}, {Code: "b", Message: "second"}} + assert.Equal(t, "first [a]\nsecond [b]", l.Error()) +} + +func TestJSON(t *testing.T) { + out := diag.JSON(diag.List{{Code: diag.CodeRuntime, Message: "x < y", File: "main.ct", Line: 1}}) + + var parsed struct { + Errors []map[string]interface{} `json:"errors"` + } + require.NoError(t, json.Unmarshal(out, &parsed)) + require.Len(t, parsed.Errors, 1) + assert.Equal(t, "runtime", parsed.Errors[0]["code"]) + assert.Equal(t, "main.ct", parsed.Errors[0]["file"]) + assert.NotContains(t, parsed.Errors[0], "path", "empty fields are omitted") + assert.Contains(t, string(out), "x < y", "no HTML escaping") +} diff --git a/pkg/engine/devruntime.go b/pkg/engine/devruntime.go index ce7b9f3..6fe0d07 100644 --- a/pkg/engine/devruntime.go +++ b/pkg/engine/devruntime.go @@ -1,8 +1,11 @@ package engine import ( + "errors" "fmt" + "math" "strconv" + "strings" "github.com/dop251/goja" ) @@ -58,10 +61,21 @@ func ExecuteDev(opts ExecuteDevOpts) (*DevResult, error) { func registerConfigGlobal(h *JSHelper, result *DevResult) { h.DefineFunc("config", func(args *Args) (interface{}, error) { obj := args.Object(0) - if ns, ok := obj["namespace"].(string); ok { - result.Namespace = ns + // Without a usable namespace ct dev would silently fall back to the + // kubeconfig's default namespace and apply (and prune) there. + ns, err := optionalString(obj, "namespace") + if err != nil { + return nil, err } - if vals, ok := obj["values"].(map[string]interface{}); ok { + if strings.TrimSpace(ns) == "" { + return nil, errors.New("namespace must be a non-empty string (check the env()/prompt() values it is built from)") + } + result.Namespace = ns + if v, ok := option(obj, "values"); ok { + vals, isMap := v.(map[string]interface{}) + if !isMap { + return nil, fmt.Errorf("values must be an object, got %s", jsTypeName(v)) + } result.Values = vals } return nil, nil @@ -71,37 +85,58 @@ func registerConfigGlobal(h *JSHelper, result *DevResult) { func registerDevGlobal(h *JSHelper, result *DevResult) { h.DefineFunc("dev", func(args *Args) (interface{}, error) { name := args.String(0) - obj := args.Object(1) - target := RawDevTarget{Name: name} - - if sel, ok := obj["selector"]; ok && sel != nil { - target.Selector = rawToStringMap(sel) - } - if container, ok := obj["container"].(string); ok { - target.Container = container - } - if term, ok := obj["terminal"].(string); ok { - target.Terminal = term - } - - target.Sync = extractSyncRules(obj) - target.Ports = extractPorts(obj) - target.Probes = extractOptionalBool(obj, "probes") - target.Replicas = extractOptionalInt64(obj, "replicas") - target.Env = extractObjectSlice(obj, "env") - if wd, ok := obj["workingDir"].(string); ok { - target.WorkingDir = wd - } - if img, ok := obj["image"].(string); ok { - target.Image = img + target, err := parseDevTarget(name, args.Object(1)) + if err != nil { + // Options of the wrong shape used to be dropped silently (a + // string command, a "src:dst" sync string, ...), which left + // the user guessing why nothing happened. + return nil, fmt.Errorf("target %q: %w", name, err) } - target.Command = extractStringSlice(obj, "command") - result.Targets = append(result.Targets, target) return nil, nil }) } +func parseDevTarget(name string, obj map[string]interface{}) (RawDevTarget, error) { + target := RawDevTarget{Name: name} + var err error + if target.Selector, err = optionalSelector(obj); err != nil { + return target, err + } + for _, field := range []struct { + key string + dst *string + }{ + {"container", &target.Container}, + {"terminal", &target.Terminal}, + {"workingDir", &target.WorkingDir}, + {"image", &target.Image}, + } { + if *field.dst, err = optionalString(obj, field.key); err != nil { + return target, err + } + } + if target.Sync, err = optionalObjectList(obj, "sync"); err != nil { + return target, err + } + if target.Ports, err = optionalList(obj, "ports"); err != nil { + return target, err + } + if target.Env, err = optionalObjectList(obj, "env"); err != nil { + return target, err + } + if target.Command, err = optionalStringList(obj, "command"); err != nil { + return target, err + } + if target.Probes, err = optionalBool(obj, "probes"); err != nil { + return target, err + } + if target.Replicas, err = optionalInt64(obj, "replicas"); err != nil { + return target, err + } + return target, nil +} + func registerEnvGlobal(h *JSHelper, envVars map[string]string) { h.DefineFunc("env", func(args *Args) (interface{}, error) { name := args.String(0) @@ -113,7 +148,11 @@ func registerEnvGlobal(h *JSHelper, envVars map[string]string) { return "", nil } if args.HasArg(1) { - return coerceToType(val, args.Raw(1).Export()) + v, err := coerceToType(val, args.Raw(1).Export()) + if err != nil { + return nil, fmt.Errorf("%s=%q: %w", name, val, err) + } + return v, nil } return val, nil }) @@ -125,104 +164,177 @@ func registerPromptGlobal(h *JSHelper, promptFn func(string) (string, error)) { }) } -// coerceToType parses val string to match the type of defaultVal. +// coerceToType parses val to the type of defaultVal (number or boolean; any +// other default returns val unchanged). An empty value means "not set" for +// typed defaults (`PORT=` placeholders in .env files). A value that cannot be +// parsed is an error: returning the raw string would only fail later and far +// away, and the string "false" is truthy in JS. func coerceToType(val string, defaultVal interface{}) (interface{}, error) { switch defaultVal.(type) { - case int64: - if n, err := strconv.ParseInt(val, 10, 64); err == nil { + case int64, float64: + s := strings.TrimSpace(val) + if s == "" { + return defaultVal, nil + } + if n, err := strconv.ParseInt(s, 10, 64); err == nil { return n, nil } - case float64: - if f, err := strconv.ParseFloat(val, 64); err == nil { + if f, err := strconv.ParseFloat(s, 64); err == nil && !math.IsInf(f, 0) && !math.IsNaN(f) { return f, nil } + return nil, fmt.Errorf("value is not a number (the default %v is a number)", defaultVal) + case bool: + switch strings.ToLower(strings.TrimSpace(val)) { + case "": + return defaultVal, nil + case "true", "1", "yes", "on": + return true, nil + case "false", "0", "no", "off": + return false, nil + } + return nil, fmt.Errorf("value is not a boolean (use true/false, 1/0, yes/no or on/off; the default %v is a boolean)", defaultVal) } return val, nil } -func rawToStringMap(v interface{}) map[string]string { - raw, ok := v.(map[string]interface{}) +// option returns obj[key]; JS undefined and null count as absent. +func option(obj map[string]interface{}, key string) (interface{}, bool) { + v, ok := obj[key] + return v, ok && v != nil +} + +func optionalSelector(obj map[string]interface{}) (map[string]string, error) { + v, ok := option(obj, "selector") if !ok { - return nil + return nil, nil + } + raw, isMap := v.(map[string]interface{}) + if !isMap { + return nil, fmt.Errorf("selector must be an object of labels, got %s", jsTypeName(v)) + } + if len(raw) == 0 { + return nil, errors.New("selector must not be empty (an empty selector matches every pod in the namespace)") } result := make(map[string]string, len(raw)) for k, val := range raw { - result[k] = fmt.Sprint(val) + s, ok := scalarString(val) + if !ok { + return nil, fmt.Errorf("selector %q must be a string, got %s", k, jsTypeName(val)) + } + result[k] = s } - return result + return result, nil } -func extractSyncRules(obj map[string]interface{}) []map[string]interface{} { - raw, ok := obj["sync"].([]interface{}) +func optionalString(obj map[string]interface{}, key string) (string, error) { + v, ok := option(obj, key) if !ok { - return nil + return "", nil } - rules := make([]map[string]interface{}, 0, len(raw)) - for _, item := range raw { - if m, ok := item.(map[string]interface{}); ok { - rules = append(rules, m) - } + s, isString := v.(string) + if !isString { + return "", fmt.Errorf("%s must be a string, got %s", key, jsTypeName(v)) } - return rules + return s, nil } -func extractPorts(obj map[string]interface{}) []interface{} { - raw, ok := obj["ports"].([]interface{}) +func optionalList(obj map[string]interface{}, key string) ([]interface{}, error) { + v, ok := option(obj, key) if !ok { - return nil + return nil, nil + } + list, isList := v.([]interface{}) + if !isList { + return nil, fmt.Errorf("%s must be an array, got %s", key, jsTypeName(v)) } - return raw + return list, nil } -func extractOptionalBool(obj map[string]interface{}, key string) *bool { - v, ok := obj[key] - if !ok || v == nil { - return nil +func optionalObjectList(obj map[string]interface{}, key string) ([]map[string]interface{}, error) { + list, err := optionalList(obj, key) + if err != nil || list == nil { + return nil, err + } + result := make([]map[string]interface{}, 0, len(list)) + for i, item := range list { + m, isMap := item.(map[string]interface{}) + if !isMap { + return nil, fmt.Errorf("%s[%d] must be an object, got %s", key, i, jsTypeName(item)) + } + result = append(result, m) + } + return result, nil +} + +func optionalStringList(obj map[string]interface{}, key string) ([]string, error) { + list, err := optionalList(obj, key) + if err != nil || list == nil { + return nil, err + } + result := make([]string, 0, len(list)) + for i, item := range list { + s, ok := scalarString(item) + if !ok { + return nil, fmt.Errorf("%s[%d] must be a string, got %s", key, i, jsTypeName(item)) + } + result = append(result, s) } - b, ok := v.(bool) + return result, nil +} + +func optionalBool(obj map[string]interface{}, key string) (*bool, error) { + v, ok := option(obj, key) if !ok { - return nil + return nil, nil } - return &b + b, isBool := v.(bool) + if !isBool { + return nil, fmt.Errorf("%s must be a boolean, got %s", key, jsTypeName(v)) + } + return &b, nil } -func extractOptionalInt64(obj map[string]interface{}, key string) *int64 { - v, ok := obj[key] - if !ok || v == nil { - return nil +func optionalInt64(obj map[string]interface{}, key string) (*int64, error) { + v, ok := option(obj, key) + if !ok { + return nil, nil } switch n := v.(type) { case int64: - return &n + return &n, nil case float64: i := int64(n) - return &i + if float64(i) != n { + return nil, fmt.Errorf("%s must be an integer, got %v", key, n) + } + return &i, nil } - return nil + return nil, fmt.Errorf("%s must be a number, got %s", key, jsTypeName(v)) } -func extractObjectSlice(obj map[string]interface{}, key string) []map[string]interface{} { - raw, ok := obj[key].([]interface{}) - if !ok { - return nil +// scalarString converts strings, numbers and booleans to their string form. +func scalarString(v interface{}) (string, bool) { + switch v.(type) { + case string, int64, float64, bool: + return fmt.Sprint(v), true } - result := make([]map[string]interface{}, 0, len(raw)) - for _, item := range raw { - if m, ok := item.(map[string]interface{}); ok { - result = append(result, m) - } - } - return result + return "", false } -func extractStringSlice(obj map[string]interface{}, key string) []string { - raw, ok := obj[key].([]interface{}) - if !ok { - return nil - } - result := make([]string, 0, len(raw)) - for _, item := range raw { - result = append(result, fmt.Sprint(item)) +func jsTypeName(v interface{}) string { + switch v.(type) { + case nil: + return "null/undefined" + case string: + return "string" + case int64, float64: + return "number" + case bool: + return "boolean" + case []interface{}: + return "array" + case map[string]interface{}: + return "object" } - return result + return fmt.Sprintf("%T", v) } diff --git a/pkg/engine/devruntime_test.go b/pkg/engine/devruntime_test.go index db7acc1..0ebdd82 100644 --- a/pkg/engine/devruntime_test.go +++ b/pkg/engine/devruntime_test.go @@ -3,7 +3,7 @@ package engine_test import ( "testing" - "github.com/cloudticon/ctts/pkg/engine" + "github.com/cloudticon/ct/pkg/engine" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -398,3 +398,128 @@ func TestExecuteDev_FullScenario(t *testing.T) { assert.Equal(t, int64(43291), pgPort[0]) assert.Equal(t, int64(5432), pgPort[1]) } + +func runEnvJS(t *testing.T, js string, env map[string]string) (*engine.DevResult, error) { + t.Helper() + return engine.ExecuteDev(engine.ExecuteDevOpts{JSCode: js, EnvVars: env, PromptFn: noopPrompt}) +} + +// env("DEBUG", false) returned the string "false" when DEBUG=false was set, +// and every non-empty string is truthy in JS. +func TestExecuteDev_EnvBooleanDefault(t *testing.T) { + js := ` + const debug = env("DEBUG", false) + config({ namespace: "ns", values: { debug: debug, branch: debug ? "on" : "off" } }) + ` + for value, want := range map[string]bool{"false": false, "0": false, "no": false, "true": true, "1": true, "YES": true, " on ": true} { + result, err := runEnvJS(t, js, map[string]string{"DEBUG": value}) + require.NoError(t, err, value) + assert.Equal(t, want, result.Values["debug"], "DEBUG=%q", value) + assert.Equal(t, map[bool]string{true: "on", false: "off"}[want], result.Values["branch"], "DEBUG=%q", value) + } + + result, err := runEnvJS(t, js, map[string]string{}) + require.NoError(t, err) + assert.Equal(t, false, result.Values["debug"]) +} + +func TestExecuteDev_EnvInvalidBooleanIsAnError(t *testing.T) { + _, err := runEnvJS(t, `env("DEBUG", false)`, map[string]string{"DEBUG": "maybe"}) + require.Error(t, err) + assert.Contains(t, err.Error(), "DEBUG") + assert.Contains(t, err.Error(), "boolean") +} + +// An unparsable number used to come back as a string and only failed later, +// far away ("ports[0][0]: expected number, got string"). +func TestExecuteDev_EnvInvalidNumberIsAnError(t *testing.T) { + _, err := runEnvJS(t, `env("PORT", 3000)`, map[string]string{"PORT": "30o0"}) + require.Error(t, err) + assert.Contains(t, err.Error(), "PORT") + assert.Contains(t, err.Error(), `"30o0"`) + assert.Contains(t, err.Error(), "number") +} + +// `PORT=` is a common .env placeholder; with a typed default it means unset. +func TestExecuteDev_EnvEmptyValueUsesTypedDefault(t *testing.T) { + js := `config({ namespace: "ns", values: { port: env("PORT", 3000), debug: env("DEBUG", true), name: env("NAME", "web") } })` + result, err := runEnvJS(t, js, map[string]string{"PORT": "", "DEBUG": " ", "NAME": ""}) + require.NoError(t, err) + assert.Equal(t, int64(3000), result.Values["port"]) + assert.Equal(t, true, result.Values["debug"]) + assert.Equal(t, "", result.Values["name"], "an explicitly empty string stays empty") +} + +func TestExecuteDev_EnvNumberDefaultAcceptsDecimals(t *testing.T) { + js := `config({ namespace: "ns", values: { ratio: env("RATIO", 1), port: env("PORT", 3000) } })` + result, err := runEnvJS(t, js, map[string]string{"RATIO": "0.25", "PORT": " 8080 "}) + require.NoError(t, err) + assert.Equal(t, 0.25, result.Values["ratio"]) + assert.Equal(t, int64(8080), result.Values["port"]) +} + +// Options of the wrong shape used to be ignored silently: e.g. a string +// command left the original command running, a DevSpace-style "src:dst" +// sync string meant no sync at all, and a null selector value became the +// label value "" so ct dev waited for a pod forever. +func TestExecuteDev_RejectsMistypedOptions(t *testing.T) { + cases := map[string]struct { + js string + want []string + }{ + "command string": {`dev("web", { command: "npm run dev" })`, []string{`"web"`, "command", "array"}}, + "command null item": {`dev("web", { command: ["npm", null] })`, []string{"command[1]"}}, + "sync string": {`dev("web", { sync: ["./:/app"] })`, []string{"sync[0]", "object"}}, + "sync not array": {`dev("web", { sync: { from: "./", to: "/app" } })`, []string{"sync", "array"}}, + "env string": {`dev("web", { env: ["FOO=bar"] })`, []string{"env[0]", "object"}}, + "ports not array": {`dev("web", { ports: 3000 })`, []string{"ports", "array"}}, + "selector not object": {`dev("web", { selector: "app=web" })`, []string{"selector", "object"}}, + "selector empty": {`dev("web", { selector: {} })`, []string{"selector", "empty"}}, + "selector undefined": {`const v = {}; dev("web", { selector: { app: v.missing } })`, []string{`selector "app"`}}, + "terminal not string": {`dev("web", { terminal: ["bash"] })`, []string{"terminal", "string"}}, + "container not string": {`dev("web", { container: 1 })`, []string{"container", "string"}}, + "image not string": {`dev("web", { image: { name: "x" } })`, []string{"image", "string"}}, + "workingDir not string": {`dev("web", { workingDir: 1 })`, []string{"workingDir", "string"}}, + "probes not bool": {`dev("web", { probes: "true" })`, []string{"probes", "boolean"}}, + "replicas not number": {`dev("web", { replicas: "1" })`, []string{"replicas", "number"}}, + "replicas fraction": {`dev("web", { replicas: 1.5 })`, []string{"replicas", "integer"}}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + _, err := engine.ExecuteDev(engine.ExecuteDevOpts{JSCode: tc.js, EnvVars: map[string]string{}, PromptFn: noopPrompt}) + require.Error(t, err) + for _, want := range tc.want { + assert.Contains(t, err.Error(), want) + } + }) + } +} + +func TestExecuteDev_UndefinedOptionsAreIgnored(t *testing.T) { + js := `const v = {}; dev("web", { terminal: v.t, command: v.c, sync: v.s, ports: v.p, selector: v.sel, probes: v.pr, replicas: v.r })` + result, err := engine.ExecuteDev(engine.ExecuteDevOpts{JSCode: js, EnvVars: map[string]string{}, PromptFn: noopPrompt}) + require.NoError(t, err) + require.Len(t, result.Targets, 1) + assert.Nil(t, result.Targets[0].Selector) + assert.Nil(t, result.Targets[0].Probes) + assert.Nil(t, result.Targets[0].Replicas) +} + +// An empty or mistyped namespace used to fall back silently to the +// kubeconfig's default namespace, applying (and pruning) dev resources there. +func TestExecuteDev_ConfigRejectsMissingOrMistypedNamespace(t *testing.T) { + for _, js := range []string{ + `config({ namespace: "" })`, + `const v = {}; config({ namespace: v.missing })`, + `config({ values: { a: 1 } })`, + `config({ namespace: 5 })`, + } { + _, err := engine.ExecuteDev(engine.ExecuteDevOpts{JSCode: js, EnvVars: map[string]string{}, PromptFn: noopPrompt}) + require.Error(t, err, js) + assert.Contains(t, err.Error(), "namespace", js) + } + + _, err := engine.ExecuteDev(engine.ExecuteDevOpts{JSCode: `config({ namespace: "ns", values: "x" })`, EnvVars: map[string]string{}, PromptFn: noopPrompt}) + require.Error(t, err) + assert.Contains(t, err.Error(), "values") +} diff --git a/pkg/engine/envloader.go b/pkg/engine/envloader.go index 17a0519..20e6f72 100644 --- a/pkg/engine/envloader.go +++ b/pkg/engine/envloader.go @@ -1,50 +1,100 @@ package engine import ( - "bufio" "os" "strings" ) // LoadEnvFile parses a .env file into a map of key-value pairs. -// Supports KEY=VALUE, KEY="VALUE", KEY='VALUE' formats. -// Lines starting with # and empty lines are skipped. +// Supports KEY=VALUE, KEY="VALUE", KEY='VALUE' and an optional `export ` +// prefix. Lines starting with # and empty lines are skipped; in unquoted +// values " #" starts a comment. Double-quoted values interpret \n, \r, \t, +// \" and \\ (other backslashes are kept); single-quoted values are literal. func LoadEnvFile(path string) (map[string]string, error) { - f, err := os.Open(path) + data, err := os.ReadFile(path) if err != nil { return nil, err } - defer f.Close() env := make(map[string]string) - scanner := bufio.NewScanner(f) - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) + content := strings.TrimPrefix(string(data), "\ufeff") // BOM from Windows editors + for _, rawLine := range strings.Split(content, "\n") { + line := strings.TrimSpace(rawLine) // also drops the \r of CRLF files if line == "" || strings.HasPrefix(line, "#") { continue } + if rest, ok := strings.CutPrefix(line, "export"); ok && rest != "" && (rest[0] == ' ' || rest[0] == '\t') { + line = strings.TrimSpace(rest) + } key, value, ok := strings.Cut(line, "=") if !ok { continue } key = strings.TrimSpace(key) - value = strings.TrimSpace(value) - value = unquoteEnvValue(value) - env[key] = value + if key == "" { + continue + } + env[key] = parseEnvValue(strings.TrimSpace(value)) } - return env, scanner.Err() + return env, nil } -func unquoteEnvValue(s string) string { - if len(s) >= 2 { - if (s[0] == '"' && s[len(s)-1] == '"') || (s[0] == '\'' && s[len(s)-1] == '\'') { - return s[1 : len(s)-1] +func parseEnvValue(s string) string { + if s == "" { + return "" + } + switch s[0] { + case '\'': + if end := strings.IndexByte(s[1:], '\''); end >= 0 { + return s[1 : 1+end] + } + case '"': + if v, ok := parseDoubleQuoted(s); ok { + return v + } + } + // Unquoted (or unterminated quote): whitespace followed by # starts a + // comment; a # inside the value (COLOR=#fff, URL=...#anchor) does not. + for i := 1; i < len(s); i++ { + if s[i] == '#' && (s[i-1] == ' ' || s[i-1] == '\t') { + return strings.TrimSpace(s[:i]) } } return s } +// parseDoubleQuoted returns the content of the leading double-quoted string +// of s, ignoring anything after the closing quote (e.g. a comment). +func parseDoubleQuoted(s string) (string, bool) { + var b strings.Builder + for i := 1; i < len(s); i++ { + c := s[i] + switch { + case c == '\\' && i+1 < len(s): + i++ + switch s[i] { + case 'n': + b.WriteByte('\n') + case 'r': + b.WriteByte('\r') + case 't': + b.WriteByte('\t') + case '"', '\\': + b.WriteByte(s[i]) + default: + b.WriteByte('\\') + b.WriteByte(s[i]) + } + case c == '"': + return b.String(), true + default: + b.WriteByte(c) + } + } + return "", false +} + // MergeEnvWithSystem merges file env vars on top of system env. // File env vars take precedence over system env. func MergeEnvWithSystem(fileEnv map[string]string) map[string]string { diff --git a/pkg/engine/envloader_test.go b/pkg/engine/envloader_test.go index 4e3f17f..aa0dfe0 100644 --- a/pkg/engine/envloader_test.go +++ b/pkg/engine/envloader_test.go @@ -3,9 +3,10 @@ package engine_test import ( "os" "path/filepath" + "strings" "testing" - "github.com/cloudticon/ctts/pkg/engine" + "github.com/cloudticon/ct/pkg/engine" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -116,3 +117,62 @@ func TestMergeEnvWithSystem_FileWinsOverSystem(t *testing.T) { result := engine.MergeEnvWithSystem(fileEnv) assert.Equal(t, "from_file", result["TEST_MERGE_VAR"]) } + +func loadEnvString(t *testing.T, content string) map[string]string { + t.Helper() + f := filepath.Join(t.TempDir(), ".env") + require.NoError(t, os.WriteFile(f, []byte(content), 0o644)) + env, err := engine.LoadEnvFile(f) + require.NoError(t, err) + return env +} + +// .env files are often also `source`d by shells and use `export`. +func TestLoadEnvFile_ExportPrefix(t *testing.T) { + env := loadEnvString(t, "export FOO=bar\nexport\tTAB=1\nexporter=keep\n") + assert.Equal(t, "bar", env["FOO"]) + assert.Equal(t, "1", env["TAB"]) + assert.Equal(t, "keep", env["exporter"]) + _, bogus := env["export FOO"] + assert.False(t, bogus) +} + +func TestLoadEnvFile_InlineComments(t *testing.T) { + env := loadEnvString(t, "PORT=3000 # web port\nCOLOR=#fff\nURL=http://x/#anchor\nTABBED=1\t# c\n") + assert.Equal(t, "3000", env["PORT"]) + assert.Equal(t, "#fff", env["COLOR"], "# without preceding whitespace is part of the value") + assert.Equal(t, "http://x/#anchor", env["URL"]) + assert.Equal(t, "1", env["TABBED"]) +} + +func TestLoadEnvFile_QuotedValuesWithTrailingComment(t *testing.T) { + env := loadEnvString(t, "A=\"a # b\" # comment\nB='x' # c\n") + assert.Equal(t, "a # b", env["A"]) + assert.Equal(t, "x", env["B"]) +} + +func TestLoadEnvFile_DoubleQuoteEscapes(t *testing.T) { + env := loadEnvString(t, `MULTI="line1\nline2"`+"\n"+ + `QUOTED="say \"hi\""`+"\n"+ + `WIN="C:\Users\me"`+"\n"+ + `RAW='a\nb'`+"\n") + assert.Equal(t, "line1\nline2", env["MULTI"]) + assert.Equal(t, `say "hi"`, env["QUOTED"]) + assert.Equal(t, `C:\Users\me`, env["WIN"], "unknown escapes are kept") + assert.Equal(t, `a\nb`, env["RAW"], "single quotes are literal") +} + +func TestLoadEnvFile_BOMAndCRLF(t *testing.T) { + env := loadEnvString(t, "\ufeffFOO=bar\r\nBAZ=\"q\"\r\nEMPTY=\r\n") + assert.Equal(t, "bar", env["FOO"]) + assert.Equal(t, "q", env["BAZ"]) + assert.Equal(t, "", env["EMPTY"]) +} + +func TestLoadEnvFile_LongLinesAndEmptyKeys(t *testing.T) { + long := strings.Repeat("a", 200*1024) + env := loadEnvString(t, "CERT="+long+"\n=orphan\n") + assert.Equal(t, long, env["CERT"]) + _, empty := env[""] + assert.False(t, empty) +} diff --git a/pkg/engine/export_test.go b/pkg/engine/export_test.go new file mode 100644 index 0000000..f864210 --- /dev/null +++ b/pkg/engine/export_test.go @@ -0,0 +1,4 @@ +package engine + +// UserChain exposes userChain to tests. +var UserChain = userChain diff --git a/pkg/engine/integration_test.go b/pkg/engine/integration_test.go index 393aaaa..e28e5c7 100644 --- a/pkg/engine/integration_test.go +++ b/pkg/engine/integration_test.go @@ -5,7 +5,7 @@ import ( "path/filepath" "testing" - "github.com/cloudticon/ctts/pkg/engine" + "github.com/cloudticon/ct/pkg/engine" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/engine/jsargs.go b/pkg/engine/jsargs.go index dee0d37..e689b76 100644 --- a/pkg/engine/jsargs.go +++ b/pkg/engine/jsargs.go @@ -14,7 +14,7 @@ type Args struct { fnName string } -func (a *Args) Len() int { return len(a.call.Arguments) } +func (a *Args) Len() int { return len(a.call.Arguments) } func (a *Args) Raw(idx int) goja.Value { return a.call.Argument(idx) } func (a *Args) HasArg(idx int) bool { diff --git a/pkg/engine/jshelper_test.go b/pkg/engine/jshelper_test.go index d0edd0d..2f898f9 100644 --- a/pkg/engine/jshelper_test.go +++ b/pkg/engine/jshelper_test.go @@ -4,7 +4,7 @@ import ( "fmt" "testing" - "github.com/cloudticon/ctts/pkg/engine" + "github.com/cloudticon/ct/pkg/engine" "github.com/dop251/goja" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/engine/promptcache.go b/pkg/engine/promptcache.go index c4ce155..8f039e6 100644 --- a/pkg/engine/promptcache.go +++ b/pkg/engine/promptcache.go @@ -5,6 +5,7 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "os" @@ -28,33 +29,24 @@ func NewPromptCache(projectDir string) (*PromptCache, error) { return nil, fmt.Errorf("getting home dir: %w", err) } + // Answers may be secrets: keep the cache private to the user. cacheDir := filepath.Join(homeDir, ".ct", "prompt_cache") - if err := os.MkdirAll(cacheDir, 0o755); err != nil { + if err := os.MkdirAll(cacheDir, 0o700); err != nil { return nil, fmt.Errorf("creating cache dir: %w", err) } - cachePath := filepath.Join(cacheDir, hexHash+".json") - c := &PromptCache{ - path: cachePath, - data: make(map[string]string), - } - - if raw, err := os.ReadFile(cachePath); err == nil { - _ = json.Unmarshal(raw, &c.data) - } - - return c, nil + return NewPromptCacheFromPath(filepath.Join(cacheDir, hexHash+".json")), nil } // NewPromptCacheFromPath creates a cache using an explicit file path (for testing). func NewPromptCacheFromPath(cachePath string) *PromptCache { - c := &PromptCache{ - path: cachePath, - data: make(map[string]string), - } + c := &PromptCache{path: cachePath} if raw, err := os.ReadFile(cachePath); err == nil { _ = json.Unmarshal(raw, &c.data) } + if c.data == nil { // missing, corrupt or "null" file + c.data = make(map[string]string) + } return c } @@ -70,20 +62,37 @@ func (c *PromptCache) Set(question, answer string) error { if err != nil { return err } - return os.WriteFile(c.path, raw, 0o644) + if err := os.WriteFile(c.path, raw, 0o600); err != nil { + return err + } + // WriteFile keeps the mode of an existing file; tighten older caches. + return os.Chmod(c.path, 0o600) } // MakePromptFn returns a prompt function that reads stdin with cache support. func MakePromptFn(cache *PromptCache, reader io.Reader, writer io.Writer) func(string) (string, error) { + // One buffered reader for all prompts: a reader per prompt reads ahead + // and swallows the answers to the following prompts when stdin is piped. + in := bufio.NewReader(reader) return func(question string) (string, error) { if cached, ok := cache.Get(question); ok { - fmt.Fprintf(writer, "%s [cached: %s]\n", question, cached) + fmt.Fprintf(writer, "%s [cached: %s] (change it in %s)\n", question, cached, cache.path) return cached, nil } fmt.Fprintf(writer, "%s: ", question) - scanner := bufio.NewScanner(reader) - scanner.Scan() - answer := strings.TrimSpace(scanner.Text()) + line, err := in.ReadString('\n') + if err != nil && (line == "" || !errors.Is(err, io.EOF)) { + if errors.Is(err, io.EOF) { + // Do not cache anything: an empty answer would be reused + // silently by every later run. + key, _ := json.Marshal(question) + return "", fmt.Errorf("no answer for prompt %q: stdin is closed or not a terminal; "+ + "run ct dev interactively, pipe the answers to stdin, or add %s: \"\" to the JSON object in %s", + question, key, cache.path) + } + return "", fmt.Errorf("reading answer for prompt %q: %w", question, err) + } + answer := strings.TrimSpace(line) if err := cache.Set(question, answer); err != nil { return "", fmt.Errorf("saving prompt cache: %w", err) } diff --git a/pkg/engine/promptcache_test.go b/pkg/engine/promptcache_test.go index 5570f71..87f0aff 100644 --- a/pkg/engine/promptcache_test.go +++ b/pkg/engine/promptcache_test.go @@ -4,10 +4,11 @@ import ( "bytes" "os" "path/filepath" + "runtime" "strings" "testing" - "github.com/cloudticon/ctts/pkg/engine" + "github.com/cloudticon/ct/pkg/engine" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -131,3 +132,73 @@ func TestMakePromptFn_TrimWhitespace(t *testing.T) { require.NoError(t, err) assert.Equal(t, "spaced", answer) } + +// Each prompt created its own bufio.Scanner, which reads ahead: with piped +// stdin the first prompt swallowed the answers of all following prompts. +func TestMakePromptFn_MultiplePromptsFromPipedInput(t *testing.T) { + cache := engine.NewPromptCacheFromPath(filepath.Join(t.TempDir(), "cache.json")) + fn := engine.MakePromptFn(cache, strings.NewReader("alice\nbob\n"), &bytes.Buffer{}) + + first, err := fn("Username?") + require.NoError(t, err) + second, err := fn("Team?") + require.NoError(t, err) + assert.Equal(t, "alice", first) + assert.Equal(t, "bob", second) +} + +// Without input (stdin closed, not a terminal) the prompt used to return "" +// and cache it, so every later run silently reused the empty answer. +func TestMakePromptFn_NoInputIsAnErrorAndNotCached(t *testing.T) { + cachePath := filepath.Join(t.TempDir(), "cache.json") + cache := engine.NewPromptCacheFromPath(cachePath) + fn := engine.MakePromptFn(cache, strings.NewReader(""), &bytes.Buffer{}) + + _, err := fn("Username?") + require.Error(t, err) + assert.Contains(t, err.Error(), "Username?") + assert.Contains(t, err.Error(), cachePath, "the error must say how to answer non-interactively") + _, cached := cache.Get("Username?") + assert.False(t, cached) +} + +func TestMakePromptFn_LastLineWithoutNewline(t *testing.T) { + cache := engine.NewPromptCacheFromPath(filepath.Join(t.TempDir(), "cache.json")) + fn := engine.MakePromptFn(cache, strings.NewReader("alice"), &bytes.Buffer{}) + answer, err := fn("Username?") + require.NoError(t, err) + assert.Equal(t, "alice", answer) +} + +func TestMakePromptFn_CachedAnswerSaysWhereToChangeIt(t *testing.T) { + cachePath := filepath.Join(t.TempDir(), "cache.json") + cache := engine.NewPromptCacheFromPath(cachePath) + require.NoError(t, cache.Set("Username?", "alice")) + + var out bytes.Buffer + _, err := engine.MakePromptFn(cache, strings.NewReader(""), &out)("Username?") + require.NoError(t, err) + assert.Contains(t, out.String(), cachePath) +} + +func TestPromptCache_NullFileDoesNotPanic(t *testing.T) { + cachePath := filepath.Join(t.TempDir(), "cache.json") + require.NoError(t, os.WriteFile(cachePath, []byte("null"), 0o600)) + + cache := engine.NewPromptCacheFromPath(cachePath) + require.NoError(t, cache.Set("q", "a")) +} + +// Answers can be secrets (tokens, passwords). +func TestPromptCache_FileIsPrivate(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("unix permissions") + } + cachePath := filepath.Join(t.TempDir(), "cache.json") + cache := engine.NewPromptCacheFromPath(cachePath) + require.NoError(t, cache.Set("token?", "secret")) + + info, err := os.Stat(cachePath) + require.NoError(t, err) + assert.Zero(t, info.Mode().Perm()&0o077, "prompt cache must not be readable by other users, got %v", info.Mode().Perm()) +} diff --git a/pkg/engine/runtime.go b/pkg/engine/runtime.go index 13392e5..23b62e8 100644 --- a/pkg/engine/runtime.go +++ b/pkg/engine/runtime.go @@ -1,8 +1,15 @@ package engine import ( + "errors" "fmt" + "path/filepath" + "reflect" + "strings" + "time" + "github.com/cloudticon/ct/pkg/diag" + "github.com/cloudticon/ct/pkg/manifest" "github.com/dop251/goja" ) @@ -13,37 +20,275 @@ type ExecuteOpts struct { Values map[string]interface{} Namespace string ReleaseName string + // SourceDir is the project directory; source positions in errors are + // shown relative to it. + SourceDir string + // Timeout aborts scripts that run longer, e.g. an endless loop. Zero + // means no limit. + Timeout time.Duration } +// Result is a rendered release. +type Result struct { + Resources []Resource + // Origins[i] is the call chain in the user's own files (innermost first, + // imported packages left out) that registered Resources[i]. + Origins [][]diag.Frame +} + +// Origin returns the call chain that registered resource i, or nil. +func (r *Result) Origin(i int) []diag.Frame { + if i < len(r.Origins) { + return r.Origins[i] + } + return nil +} + +// Execute runs a bundle and returns the registered resources. func Execute(opts ExecuteOpts) ([]Resource, error) { + result, err := Render(opts) + if err != nil { + return nil, err + } + return result.Resources, nil +} + +// Render runs a bundle and returns the registered resources together with +// their source origins. Errors are diag.List values with .ct positions. +func Render(opts ExecuteOpts) (*Result, error) { vm := goja.New() + // Endless recursion fails fast with a RangeError and a short stack + // instead of growing until the timeout. + vm.SetMaxCallStackSize(maxCallStackSize) + origins := injectGlobals(vm, opts) - injectGlobals(vm, opts.Values, opts.ReleaseName, opts.Namespace) + prg, err := goja.Compile(bundleName, opts.JSCode, false) + if err != nil { + return nil, diag.Errorf(diag.CodeSyntax, "compiling bundle: %v", err) + } - if _, err := vm.RunString(opts.JSCode); err != nil { - return nil, fmt.Errorf("JS execution error: %w", err) + if opts.Timeout > 0 { + timer := time.AfterFunc(opts.Timeout, func() { vm.Interrupt(opts.Timeout) }) + defer timer.Stop() + } + + if _, err := vm.RunProgram(prg); err != nil { + return nil, runtimeDiagnostics(err, opts.SourceDir) } resources, err := extractResources(vm) if err != nil { - return nil, fmt.Errorf("failed to extract resources: %w", err) + return nil, diag.Errorf(diag.CodeInvalidResource, "%v", err) } - postProcess(resources, opts.Namespace) - return resources, nil + result := &Result{Resources: resources} + if len(*origins) == len(resources) { + result.Origins = *origins + } + + manifest.Normalize(resources, opts.Namespace) + if err := checkDuplicates(result); err != nil { + return nil, err + } + return result, nil +} + +const ( + bundleName = "ct-bundle.js" + maxCallStackSize = 10000 + // maxStackFrames bounds the stack shown in a diagnostic. + maxStackFrames = 20 +) + +func capFrames(frames []diag.Frame) []diag.Frame { + if len(frames) > maxStackFrames { + return frames[:maxStackFrames] + } + return frames +} + +func checkDuplicates(result *Result) error { + dups := manifest.FindDuplicates(result.Resources) + if len(dups) == 0 { + return nil + } + list := make(diag.List, 0, len(dups)) + for _, d := range dups { + var where []string + for _, idx := range d.Indexes { + if o := result.Origin(idx); o != nil { + where = append(where, diag.Chain(o)) + } else { + where = append(where, fmt.Sprintf("resource #%d", idx+1)) + } + } + list = append(list, diag.Diagnostic{ + Code: diag.CodeDuplicate, + Message: fmt.Sprintf("registered %d times (%s)", len(d.Indexes), strings.Join(where, "; ")), + Resource: d.Ref, + Hint: "each object must be registered once; give the copies different names or namespaces, or register it in one place", + }.AtChain(result.Origin(d.Indexes[len(d.Indexes)-1]))) + } + return list } -func injectGlobals(vm *goja.Runtime, values map[string]interface{}, releaseName, namespace string) { +func injectGlobals(vm *goja.Runtime, opts ExecuteOpts) *[][]diag.Frame { h := NewJSHelper(vm) h.DefineArray("__ct_resources") + values := opts.Values if values == nil { values = map[string]interface{}{} } h.DefineValue("Values", values) h.DefineValue("Release", map[string]interface{}{ - "name": releaseName, - "namespace": namespace, + "name": opts.ReleaseName, + "namespace": opts.Namespace, }) + return trackRegistrations(vm, opts.SourceDir) +} + +// trackRegistrations wraps __ct_resources.push to remember which line of the +// user's code registered each object, so later errors can point there. +func trackRegistrations(vm *goja.Runtime, sourceDir string) *[][]diag.Frame { + origins := &[][]diag.Frame{} + arr := vm.Get("__ct_resources").ToObject(vm) + arrayPush, ok := goja.AssertFunction(vm.Get("Array").ToObject(vm).Get("prototype").ToObject(vm).Get("push")) + if !ok { + return origins + } + _ = arr.DefineDataProperty("push", vm.ToValue(func(call goja.FunctionCall) goja.Value { + origin := capFrames(userChain(sourceFrames(vm.CaptureCallStack(0, nil), sourceDir))) + for range call.Arguments { + *origins = append(*origins, origin) + } + res, err := arrayPush(call.This, call.Arguments...) + if err != nil { + panic(err) + } + return res + }), goja.FLAG_TRUE, goja.FLAG_FALSE, goja.FLAG_FALSE) + return origins +} + +// userChain picks the call chain to blame for a registration, innermost +// first: frames in the project directory, else any frames outside imported +// packages, else the innermost frame. +func userChain(frames []diag.Frame) []diag.Frame { + for _, keep := range []func(string) bool{isProjectPath, func(p string) bool { return !isPackagePath(p) }} { + var chain []diag.Frame + for _, f := range frames { + if keep(f.File) { + chain = append(chain, f) + } + } + if len(chain) > 0 { + return chain + } + } + if len(frames) > 0 { + return frames[:1] + } + return nil +} + +// sourceFrames converts goja frames (already mapped through the bundle's +// source map) to diag frames, dropping native and bundle-wrapper frames. +func sourceFrames(stack []goja.StackFrame, sourceDir string) []diag.Frame { + var frames []diag.Frame + for _, f := range stack { + pos := f.Position() + if pos.Filename == "" || pos.Filename == bundleName || pos.Line == 0 { + continue + } + fn := f.FuncName() + if fn == "" { + fn = "" + } + frames = append(frames, diag.Frame{ + File: DisplayPath(pos.Filename, sourceDir), + Line: pos.Line, + Column: pos.Column, + Function: fn, + }) + } + return frames +} + +// isPackagePath reports whether a display path points into an imported +// package (DisplayPath renders those as host/owner/repo@version/...). +func isPackagePath(p string) bool { + host, _, _ := strings.Cut(p, "/") + return strings.Contains(host, ".") && strings.Contains(p, "@") +} + +// isProjectPath reports whether a display path is inside the project +// (DisplayPath renders those relative to it). +func isProjectPath(p string) bool { + return p != "" && !filepath.IsAbs(p) && !strings.HasPrefix(p, "..") && !isPackagePath(p) +} + +func runtimeDiagnostics(err error, sourceDir string) error { + var interrupted *goja.InterruptedError + if errors.As(err, &interrupted) { + frames := sourceFrames(interrupted.Stack(), sourceDir) + d := diag.Diagnostic{ + Code: diag.CodeTimeout, + Message: fmt.Sprintf("rendering did not finish within %v", interrupted.Value()), + Hint: "look for an endless loop or recursion around the frames below", + Stack: capFrames(frames), + } + return diag.List{d.At(userFrame(frames))} + } + + var overflow *goja.StackOverflowError + if errors.As(err, &overflow) { + frames := sourceFrames(overflow.Stack(), sourceDir) + d := diag.Diagnostic{ + Code: diag.CodeRuntime, + Message: "Maximum call stack size exceeded", + Hint: "a function calls itself without end; check the recursion around the frames below", + Stack: capFrames(frames), + } + return diag.List{d.At(userFrame(frames))} + } + + var ex *goja.Exception + if errors.As(err, &ex) { + frames := sourceFrames(ex.Stack(), sourceDir) + d := diag.Diagnostic{ + Code: diag.CodeRuntime, + Message: exceptionMessage(ex), + Stack: capFrames(frames), + } + if strings.Contains(d.Message, "of undefined") || strings.Contains(d.Message, "of null") { + d.Hint = "something on that line is undefined; missing Values keys are a common cause: add them to values.json/values.yaml or pass --set, and use ?. for optional ones" + } + return diag.List{d.At(userFrame(frames))} + } + return diag.Errorf(diag.CodeRuntime, "%v", err) +} + +// userFrame is where an error is best fixed: the innermost frame of the +// user's call chain. +func userFrame(frames []diag.Frame) *diag.Frame { + if chain := userChain(frames); len(chain) > 0 { + return &chain[0] + } + return nil +} + +func exceptionMessage(ex *goja.Exception) (msg string) { + // Converting some thrown values to a string throws again (e.g. + // Object.create(null) has no toString); don't let that crash ct. + defer func() { + if recover() != nil { + msg = "uncaught exception (the thrown value has no message)" + } + }() + if v := ex.Value(); v != nil { + return v.String() + } + return ex.Error() } func extractResources(vm *goja.Runtime) ([]Resource, error) { @@ -64,68 +309,50 @@ func extractResources(vm *goja.Runtime) ([]Resource, error) { if !ok { return nil, fmt.Errorf("resource at index %d is not an object", i) } - resources = append(resources, res) - } - - return resources, nil -} - -func postProcess(resources []Resource, namespace string) { - for _, res := range resources { - scope, _ := res["__ctts_scope"].(string) - delete(res, "__ctts_scope") - - if scope != "cluster" && namespace != "" { - applyNamespaceDefault(res, namespace) + // goja exports one JS object as one Go map wherever it appears, and + // Values maps are shared with the script. Copy, so normalizing one + // object (e.g. defaulting its namespace) can't leak into another. + copied, err := copyValue(res, map[uintptr]bool{}) + if err != nil { + return nil, fmt.Errorf("resource at index %d: %w", i, err) } - - cleanNilFields(res) + resources = append(resources, copied.(map[string]interface{})) } -} -func applyNamespaceDefault(res Resource, namespace string) { - meta, ok := res["metadata"].(map[string]interface{}) - if !ok { - return - } - if ns, exists := meta["namespace"]; !exists || ns == nil || ns == "" { - meta["namespace"] = namespace - } + return resources, nil } -func cleanNilFields(obj map[string]interface{}) { - for k, v := range obj { - if v == nil { - delete(obj, k) - continue +// copyValue deep-copies maps and slices, rejecting cycles (which can't be +// rendered as YAML/JSON anyway). +func copyValue(v interface{}, onPath map[uintptr]bool) (interface{}, error) { + switch val := v.(type) { + case map[string]interface{}: + id := reflect.ValueOf(val).Pointer() + if onPath[id] { + return nil, fmt.Errorf("object contains a reference to itself") } - switch val := v.(type) { - case map[string]interface{}: - cleanNilFields(val) - if len(val) == 0 { - delete(obj, k) - } - case []interface{}: - cleaned := cleanNilSlice(val) - if len(cleaned) == 0 { - delete(obj, k) - } else { - obj[k] = cleaned + onPath[id] = true + defer delete(onPath, id) + out := make(map[string]interface{}, len(val)) + for k, item := range val { + c, err := copyValue(item, onPath) + if err != nil { + return nil, err } + out[k] = c } - } -} - -func cleanNilSlice(arr []interface{}) []interface{} { - result := make([]interface{}, 0, len(arr)) - for _, item := range arr { - if item == nil { - continue - } - if m, ok := item.(map[string]interface{}); ok { - cleanNilFields(m) + return out, nil + case []interface{}: + out := make([]interface{}, len(val)) + for i, item := range val { + c, err := copyValue(item, onPath) + if err != nil { + return nil, err + } + out[i] = c } - result = append(result, item) + return out, nil + default: + return v, nil } - return result } diff --git a/pkg/engine/runtime_test.go b/pkg/engine/runtime_test.go index 8f6de64..e2bdae6 100644 --- a/pkg/engine/runtime_test.go +++ b/pkg/engine/runtime_test.go @@ -2,8 +2,10 @@ package engine_test import ( "testing" + "time" - "github.com/cloudticon/ctts/pkg/engine" + "github.com/cloudticon/ct/pkg/diag" + "github.com/cloudticon/ct/pkg/engine" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -218,3 +220,77 @@ func TestExecute_NoNamespaceFlag(t *testing.T) { _, hasNamespace := meta["namespace"] assert.False(t, hasNamespace, "no namespace flag means no namespace added") } + +func TestUserChain_PrefersProjectFrames(t *testing.T) { + frames := []diag.Frame{ + {File: "github.com/cloudticon/k8s@master/resource.ts", Line: 1}, + {File: "/home/me/shared/k8s/resource.ts", Line: 2}, + {File: "lib/app.ct", Line: 3}, + {File: "main.ct", Line: 4}, + } + assert.Equal(t, frames[2:], engine.UserChain(frames)) + + outsideOnly := []diag.Frame{frames[0], frames[1]} + assert.Equal(t, frames[1:2], engine.UserChain(outsideOnly), "outside the project but not a package") + + assert.Equal(t, frames[:1], engine.UserChain(frames[:1]), "packages only: innermost frame") + assert.Nil(t, engine.UserChain(nil)) +} + +func TestExecute_SharedObjectsAreCopied(t *testing.T) { + // One metadata object used by a cluster-scoped and a namespaced kind: + // defaulting the Role's namespace must not leak into the ClusterRole. + js := ` + const meta = { name: "reader" }; + globalThis.__ct_resources.push({ apiVersion: "rbac.authorization.k8s.io/v1", kind: "ClusterRole", metadata: meta }); + globalThis.__ct_resources.push({ apiVersion: "rbac.authorization.k8s.io/v1", kind: "Role", metadata: meta }); + ` + resources, err := engine.Execute(engine.ExecuteOpts{JSCode: js, Namespace: "prod"}) + require.NoError(t, err) + + assert.NotContains(t, resources[0]["metadata"], "namespace") + assert.Equal(t, "prod", resources[1]["metadata"].(map[string]interface{})["namespace"]) +} + +func TestExecute_ValuesAreNotMutated(t *testing.T) { + values := map[string]interface{}{"labels": map[string]interface{}{"team": "a", "gone": nil}} + js := `globalThis.__ct_resources.push({ apiVersion: "v1", kind: "ConfigMap", metadata: { name: "c", labels: Values.labels } });` + + _, err := engine.Execute(engine.ExecuteOpts{JSCode: js, Values: values}) + require.NoError(t, err) + + assert.Contains(t, values["labels"], "gone", "cleaning a rendered object must not touch Values") +} + +func TestExecute_RejectsCyclicObjects(t *testing.T) { + js := ` + const o = { apiVersion: "v1", kind: "ConfigMap", metadata: { name: "c" } }; + o.self = o; + globalThis.__ct_resources.push(o); + ` + _, err := engine.Execute(engine.ExecuteOpts{JSCode: js}) + require.Error(t, err) + assert.Contains(t, err.Error(), "reference to itself") +} + +func TestRender_EndlessRecursionFailsFastWithShortStack(t *testing.T) { + _, err := engine.Render(engine.ExecuteOpts{ + JSCode: `function f(n) { return f(n + 1); } f(0);`, + Timeout: 30 * time.Second, + }) + + var list diag.List + require.ErrorAs(t, err, &list) + assert.Equal(t, diag.CodeRuntime, list[0].Code) + assert.Contains(t, list[0].Message, "Maximum call stack size exceeded") + assert.LessOrEqual(t, len(list[0].Stack), 20) + assert.Less(t, len(list.Error()), 10_000) +} + +func TestRender_ThrowingAValueWithoutToStringDoesNotPanic(t *testing.T) { + _, err := engine.Render(engine.ExecuteOpts{JSCode: `throw Object.create(null);`}) + + var list diag.List + require.ErrorAs(t, err, &list) + assert.Equal(t, diag.CodeRuntime, list[0].Code) +} diff --git a/pkg/engine/transpiler.go b/pkg/engine/transpiler.go index 1d7c25a..ed0aff8 100644 --- a/pkg/engine/transpiler.go +++ b/pkg/engine/transpiler.go @@ -1,20 +1,40 @@ package engine import ( - "bytes" "fmt" "os" "path/filepath" - "regexp" + "slices" "strings" + "sync" - "github.com/cloudticon/ctts/pkg/cache" - "github.com/cloudticon/ctts/pkg/packages" + "github.com/cloudticon/ct/pkg/cache" + "github.com/cloudticon/ct/pkg/diag" + "github.com/cloudticon/ct/pkg/packages" "github.com/evanw/esbuild/pkg/api" ) type Transpiler struct { projectDir string + // RefreshPackages re-downloads every imported package once instead of + // trusting the cache; branch versions like @master otherwise stay at + // whatever was fetched first. + RefreshPackages bool + + mu sync.Mutex + refreshed map[string]bool +} + +// MarkFresh records that a package URL was already re-downloaded in this run +// (e.g. the remote source being rendered), so RefreshPackages doesn't delete +// it again while it is being bundled. +func (t *Transpiler) MarkFresh(url string) { + t.mu.Lock() + defer t.mu.Unlock() + if t.refreshed == nil { + t.refreshed = map[string]bool{} + } + t.refreshed[url] = true } func NewTranspiler(projectDir string) *Transpiler { @@ -26,38 +46,62 @@ func NewTranspiler(projectDir string) *Transpiler { return &Transpiler{projectDir: projectDir} } +// Bundle bundles entryPoint and its imports into one IIFE script with an +// inline source map, so runtime errors point at .ct lines. Failures are +// returned as diag.List with file:line:column positions. func (t *Transpiler) Bundle(entryPoint string) (string, error) { + absEntry, err := filepath.Abs(entryPoint) + if err != nil { + return "", diag.Errorf(diag.CodeImport, "resolving entry point %s: %v", entryPoint, err) + } + baseDir := t.projectDir + if baseDir == "" { + baseDir = filepath.Dir(absEntry) + } + result := api.Build(api.BuildOptions{ - EntryPoints: []string{entryPoint}, - Bundle: true, - Format: api.FormatIIFE, - Platform: api.PlatformNeutral, - Write: false, + EntryPoints: []string{absEntry}, + AbsWorkingDir: baseDir, + Bundle: true, + Format: api.FormatIIFE, + Platform: api.PlatformNeutral, + Write: false, + Sourcemap: api.SourceMapInline, + SourcesContent: api.SourcesContentExclude, + ResolveExtensions: []string{".ts", ".ct", ".tsx", ".js", ".json"}, Loader: map[string]api.Loader{ ".ts": api.LoaderTS, ".ct": api.LoaderTS, }, - Plugins: []api.Plugin{t.asyncDetectPlugin(), t.urlResolverPlugin()}, + Plugins: []api.Plugin{asyncDetectPlugin(), t.urlResolverPlugin()}, }) if len(result.Errors) > 0 { - msgs := make([]string, len(result.Errors)) - for i, e := range result.Errors { - msgs[i] = e.Text - } - return "", fmt.Errorf("esbuild errors: %s", strings.Join(msgs, "; ")) + return "", bundleDiagnostics(result.Errors, baseDir) } - if len(result.OutputFiles) == 0 { - return "", fmt.Errorf("esbuild produced no output") + return "", diag.Errorf(diag.CodeSyntax, "esbuild produced no output for %s", entryPoint) } - return string(result.OutputFiles[0].Contents), nil } -var asyncAwaitRe = regexp.MustCompile(`\b(async|await)\b`) +// asyncFeaturesOff makes esbuild's parser reject every async construct with +// a precise location. Generators are turned off too, otherwise esbuild would +// quietly lower async functions to generators instead of failing. +var asyncFeaturesOff = map[string]bool{ + "async-await": false, + "async-generator": false, + "for-await": false, + "top-level-await": false, + "generator": false, +} -func (t *Transpiler) asyncDetectPlugin() api.Plugin { +const asyncMessage = "async/await is not supported: .ct code runs synchronously" + +// asyncDetectPlugin rejects async/await in .ct/.ts files. It parses each file +// instead of grepping, so comments, strings and names like "async-worker" +// don't trip it. +func asyncDetectPlugin() api.Plugin { return api.Plugin{ Name: "async-detect", Setup: func(build api.PluginBuild) { @@ -67,30 +111,65 @@ func (t *Transpiler) asyncDetectPlugin() api.Plugin { if err != nil { return api.OnLoadResult{}, nil } + contents := string(data) - loc := asyncAwaitRe.FindIndex(data) - if loc == nil { - return api.OnLoadResult{}, nil + check := api.Transform(contents, api.TransformOptions{ + Loader: api.LoaderTS, + Sourcefile: args.Path, + Supported: asyncFeaturesOff, + }) + var errs []api.Message + for _, m := range check.Errors { + if isAsyncError(m.Text) { + errs = append(errs, api.Message{Text: asyncMessage, Location: m.Location}) + } } - - line := 1 + bytes.Count(data[:loc[0]], []byte("\n")) - keyword := string(data[loc[0]:loc[1]]) - return api.OnLoadResult{}, fmt.Errorf( - "async/await is not supported ('%s' at line %d in %s); Goja runtime is synchronous, use sync alternatives", - keyword, line, filepath.Base(args.Path), - ) + if len(errs) > 0 { + return api.OnLoadResult{Errors: errs}, nil + } + return api.OnLoadResult{Contents: &contents, Loader: api.LoaderTS}, nil }) }, } } +// isAsyncError matches esbuild's messages for async constructs it was told +// not to support. Other errors (plain syntax errors) are left to the main +// build, which reports them as they are. +func isAsyncError(text string) bool { + return strings.HasPrefix(text, "Transforming async") || + strings.HasPrefix(text, "Transforming for-await") || + strings.HasPrefix(text, "Top-level await") +} + func (t *Transpiler) urlResolverPlugin() api.Plugin { + // esbuild resolves imports in parallel. When refreshing, invalidate and + // re-download under one lock so no resolver hands out a directory that + // another one is deleting. + resolve := func(url string) (string, error) { + if !t.RefreshPackages { + return cache.Resolve(url) + } + t.mu.Lock() + defer t.mu.Unlock() + if t.refreshed == nil { + t.refreshed = map[string]bool{} + } + if !t.refreshed[url] { + t.refreshed[url] = true + if err := cache.Invalidate(url); err != nil { + return "", err + } + } + return cache.Resolve(url) + } + return api.Plugin{ Name: "url-resolver", Setup: func(build api.PluginBuild) { build.OnResolve(api.OnResolveOptions{Filter: `^https://`}, func(args api.OnResolveArgs) (api.OnResolveResult, error) { - pkgDir, err := cache.Resolve(args.Path) + pkgDir, err := resolve(args.Path) if err != nil { return api.OnResolveResult{}, err } @@ -101,19 +180,16 @@ func (t *Transpiler) urlResolverPlugin() api.Plugin { build.OnResolve(api.OnResolveOptions{Filter: `^[a-zA-Z0-9]`}, func(args api.OnResolveArgs) (api.OnResolveResult, error) { - if !packages.IsGitPackage(args.Path) { + url, ok := packages.ImportURL(args.Path) + if !ok { return api.OnResolveResult{}, nil } - - pkgWithVersion, subPath := packages.SplitPackagePath(args.Path) - pkg, version := packages.SplitPackageVersion(pkgWithVersion) - - url := "https://" + pkg - if version != "" { - url += "@" + version + _, subPath := packages.SplitPackagePath(args.Path) + if slices.Contains(strings.Split(subPath, "/"), "..") { + return api.OnResolveResult{}, fmt.Errorf("import %q leaves its package", args.Path) } - pkgDir, err := cache.Resolve(url) + pkgDir, err := resolve(url) if err != nil { return api.OnResolveResult{}, err } @@ -150,3 +226,68 @@ func resolveIndex(dir string) string { } return filepath.Join(dir, "index.ts") } + +func bundleDiagnostics(msgs []api.Message, baseDir string) diag.List { + list := make(diag.List, 0, len(msgs)) + for _, m := range msgs { + d := diag.Diagnostic{Code: diag.CodeSyntax, Message: m.Text} + switch { + case m.Text == asyncMessage: + d.Code = diag.CodeAsync + d.Hint = "rendering is synchronous; call functions directly and drop async/await" + case m.PluginName == "url-resolver": + d.Code = diag.CodeImport + d.Hint = "check the package URL and version (github.com//@); private repositories need git credentials for https, e.g. `gh auth setup-git`" + case strings.HasPrefix(m.Text, "Could not resolve"): + d.Code = diag.CodeImport + d.Hint = importHint(m.Text) + } + if loc := m.Location; loc != nil { + d.File = DisplayPath(loc.File, baseDir) + d.Line = loc.Line + d.Column = loc.Column + 1 + d.LineText = loc.LineText + } + list = append(list, d) + } + return list +} + +func importHint(text string) string { + spec := text + if i := strings.IndexByte(text, '"'); i >= 0 { + spec = strings.Trim(text[i:], `"`) + if j := strings.IndexByte(spec, '"'); j >= 0 { + spec = spec[:j] + } + } + if strings.HasPrefix(spec, ".") || strings.HasPrefix(spec, "/") { + return "paths are relative to the importing file; .ts and .ct extensions are added automatically" + } + return "ct doesn't use npm; import packages by URL, e.g. github.com/cloudticon/k8s@master" +} + +// DisplayPath shortens a source path for messages: files in the project +// become relative ("lib/app.ct"), files from the package cache become their +// import path ("github.com/cloudticon/k8s@master/resource.ts"). +func DisplayPath(path, baseDir string) string { + if path == "" { + return path + } + abs := path + if !filepath.IsAbs(abs) { + abs = filepath.Join(baseDir, path) + } + // The project first: a remote source is itself inside the cache. + if baseDir != "" { + if rel, err := filepath.Rel(baseDir, abs); err == nil && !strings.HasPrefix(rel, "..") { + return filepath.ToSlash(rel) + } + } + if cacheDir, err := cache.CacheDir(); err == nil { + if rel, err := filepath.Rel(cacheDir, abs); err == nil && !strings.HasPrefix(rel, "..") { + return filepath.ToSlash(rel) + } + } + return abs +} diff --git a/pkg/engine/transpiler_test.go b/pkg/engine/transpiler_test.go index 4e5a088..1da13f3 100644 --- a/pkg/engine/transpiler_test.go +++ b/pkg/engine/transpiler_test.go @@ -5,7 +5,8 @@ import ( "path/filepath" "testing" - "github.com/cloudticon/ctts/pkg/engine" + "github.com/cloudticon/ct/pkg/diag" + "github.com/cloudticon/ct/pkg/engine" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -45,7 +46,8 @@ func TestBundle_InvalidTS(t *testing.T) { tr := engine.NewTranspiler("") _, err = tr.Bundle(entry) assert.Error(t, err) - assert.Contains(t, err.Error(), "esbuild") + assert.Contains(t, err.Error(), "main.ts:1:6") + assert.Contains(t, err.Error(), "[syntax]") } func TestBundle_IIFEFormat(t *testing.T) { @@ -266,7 +268,7 @@ func TestBundle_RejectsAsyncFunction(t *testing.T) { _, err = tr.Bundle(entry) assert.Error(t, err) assert.Contains(t, err.Error(), "async") - assert.Contains(t, err.Error(), "line 1") + assert.Contains(t, err.Error(), "main.ct:1:1") } func TestBundle_RejectsAwait(t *testing.T) { @@ -279,7 +281,7 @@ func TestBundle_RejectsAwait(t *testing.T) { _, err = tr.Bundle(entry) assert.Error(t, err) assert.Contains(t, err.Error(), "await") - assert.Contains(t, err.Error(), "line 2") + assert.Contains(t, err.Error(), "main.ct:2:14") } func TestBundle_RejectsAsyncArrow(t *testing.T) { @@ -340,3 +342,159 @@ console.log(entry); require.NoError(t, err) assert.Contains(t, js, "ts-wins") } + +func TestBundle_AsyncWordsInCommentsStringsAndNamesAreFine(t *testing.T) { + dir := t.TempDir() + entry := filepath.Join(dir, "main.ct") + require.NoError(t, os.WriteFile(entry, []byte(`// we never await anything here +/* async is mentioned in a comment */ +const name = "async-worker"; +const awaitingApproval = true; +const tpl = `+"`await ${name}`"+`; +function* gen() { yield 1; } +console.log(name, awaitingApproval, tpl, [...gen()]); +`), 0o644)) + + _, err := engine.NewTranspiler(dir).Bundle(entry) + require.NoError(t, err) +} + +func TestBundle_ResolvesRelativeImportsWithoutExtension(t *testing.T) { + dir := t.TempDir() + writeTS(t, dir, "lib/helper.ct", `export const helper = () => "from-ct";`) + writeTS(t, dir, "lib/util/index.ts", `export const util = () => "from-index";`) + entry := filepath.Join(dir, "main.ct") + require.NoError(t, os.WriteFile(entry, []byte(`import { helper } from "./lib/helper"; +import { util } from "./lib/util"; +console.log(helper(), util()); +`), 0o644)) + + js, err := engine.NewTranspiler(dir).Bundle(entry) + require.NoError(t, err) + assert.Contains(t, js, "from-ct") + assert.Contains(t, js, "from-index") +} + +func TestBundle_ReportsUnresolvedImportsWithHints(t *testing.T) { + dir := t.TempDir() + entry := filepath.Join(dir, "main.ct") + require.NoError(t, os.WriteFile(entry, []byte(`import _ from "lodash"; +import { x } from "./missing"; +console.log(_, x); +`), 0o644)) + + _, err := engine.NewTranspiler(dir).Bundle(entry) + + var list diag.List + require.ErrorAs(t, err, &list) + require.Len(t, list, 2) + assert.Equal(t, diag.CodeImport, list[0].Code) + assert.Equal(t, "main.ct", list[0].File) + assert.Equal(t, 1, list[0].Line) + assert.Contains(t, list[0].Hint, "doesn't use npm") + assert.Equal(t, 2, list[1].Line) + assert.Contains(t, list[1].Hint, "relative to the importing file") +} + +func TestBundle_RelativeEntryPointAndProjectDir(t *testing.T) { + dir := t.TempDir() + writeTS(t, dir, "app/main.ct", `import { v } from "./v"; console.log(v);`) + writeTS(t, dir, "app/v.ct", `export const v = "relative-ok";`) + t.Chdir(dir) + + js, err := engine.NewTranspiler("app").Bundle(filepath.Join("app", "main.ct")) + require.NoError(t, err) + assert.Contains(t, js, "relative-ok") +} + +func TestBundle_RefreshPackagesInvalidatesCacheOncePerBundle(t *testing.T) { + // invalid.invalid never resolves, so the re-download fails fast offline. + pkgDir := setupFakeCache(t, "invalid.invalid", "someone", "fresh", "main") + writeTS(t, pkgDir, "index.ts", `export const v = "stale";`) + + dir := t.TempDir() + entry := filepath.Join(dir, "main.ct") + require.NoError(t, os.WriteFile(entry, []byte(`import { v } from "invalid.invalid/someone/fresh@main"; console.log(v);`), 0o644)) + + tr := engine.NewTranspiler(dir) + js, err := tr.Bundle(entry) + require.NoError(t, err) + assert.Contains(t, js, "stale", "cache is trusted by default") + + tr.RefreshPackages = true + _, err = tr.Bundle(entry) + require.Error(t, err, "the stale copy is dropped and a re-download is attempted") + assert.NoDirExists(t, pkgDir) +} + +func TestBundle_PackageSubPathCannotLeaveThePackage(t *testing.T) { + pkgDir := setupFakeCache(t, "github.com", "someone", "pkg", "v1") + writeTS(t, pkgDir, "index.ts", `export const ok = 1;`) + writeTS(t, filepath.Dir(pkgDir), "secret.ts", `export const secret = "leaked";`) + + dir := t.TempDir() + entry := filepath.Join(dir, "main.ct") + require.NoError(t, os.WriteFile(entry, []byte(`import { secret } from "github.com/someone/pkg@v1/../secret"; console.log(secret);`), 0o644)) + + _, err := engine.NewTranspiler(dir).Bundle(entry) + require.Error(t, err) + assert.Contains(t, err.Error(), "leaves its package") +} + +func TestBundle_SyntaxErrorNextToAsyncLikeNameIsASyntaxError(t *testing.T) { + dir := t.TempDir() + entry := filepath.Join(dir, "main.ct") + require.NoError(t, os.WriteFile(entry, []byte("const o = { name: workerName asyncWorker: true };\n"), 0o644)) + + _, err := engine.NewTranspiler(dir).Bundle(entry) + + var list diag.List + require.ErrorAs(t, err, &list) + assert.Equal(t, diag.CodeSyntax, list[0].Code) + assert.Contains(t, list[0].Message, `Expected "}" but found "asyncWorker"`) +} + +func TestBundle_RejectsEveryAsyncForm(t *testing.T) { + for _, src := range []string{ + "async function f() {}", + "const f = async () => 1;", + "const x = await g();", + "async function* gen() {}", + "class A { async m() {} }", + } { + dir := t.TempDir() + entry := filepath.Join(dir, "main.ct") + require.NoError(t, os.WriteFile(entry, []byte(src+"\n"), 0o644)) + + _, err := engine.NewTranspiler(dir).Bundle(entry) + + var list diag.List + require.ErrorAs(t, err, &list, src) + assert.Equal(t, diag.CodeAsync, list[0].Code, src) + } +} + +func TestDisplayPath_ProjectInsideCacheStaysRelative(t *testing.T) { + pkgDir := setupFakeCache(t, "github.com", "acme", "infra", "v1") + other := filepath.Join(filepath.Dir(filepath.Dir(pkgDir)), "cloudticon", "k8s@master", "resource.ts") + + assert.Equal(t, "main.ct", engine.DisplayPath(filepath.Join(pkgDir, "main.ct"), pkgDir)) + assert.Equal(t, "github.com/cloudticon/k8s@master/resource.ts", engine.DisplayPath(other, pkgDir)) +} + +func TestBundle_RefreshKeepsPackagesMarkedFresh(t *testing.T) { + // A remote source importing its own repository: the CLI already + // re-downloaded it, so refreshing must not delete it mid-bundle. + pkgDir := setupFakeCache(t, "github.com", "acme", "infra", "v1") + writeTS(t, pkgDir, "lib/x.ts", `export const x = "from-self";`) + writeTS(t, pkgDir, "main.ct", `import { x } from "github.com/acme/infra@v1/lib/x"; console.log(x);`) + + tr := engine.NewTranspiler(pkgDir) + tr.RefreshPackages = true + tr.MarkFresh("https://github.com/acme/infra@v1") + js, err := tr.Bundle(filepath.Join(pkgDir, "main.ct")) + + require.NoError(t, err) + assert.Contains(t, js, "from-self") + assert.DirExists(t, pkgDir) +} diff --git a/pkg/engine/values.go b/pkg/engine/values.go index 3826dc6..1c3704e 100644 --- a/pkg/engine/values.go +++ b/pkg/engine/values.go @@ -3,6 +3,7 @@ package engine import ( "encoding/json" "fmt" + "math" "os" "path/filepath" "strconv" @@ -11,7 +12,45 @@ import ( "gopkg.in/yaml.v3" ) +// ValuesOpts lists value sources in precedence order: Files are deep-merged +// left to right (maps merge, everything else is replaced), then Set and +// SetString overrides are applied in order. +type ValuesOpts struct { + Files []string + // Set holds key=value overrides; values that look like numbers, booleans + // or null are typed (see parseValue). + Set []string + // SetString holds key=value overrides that always stay strings. + SetString []string +} + +// LoadValues builds the Values object for a render. With no sources it +// returns an empty map. +func LoadValues(opts ValuesOpts) (map[string]interface{}, error) { + values := map[string]interface{}{} + for _, path := range opts.Files { + fileValues, err := readValuesFile(path) + if err != nil { + return nil, err + } + mergeValues(values, fileValues) + } + + if err := applySetOverrides(values, "--set", opts.Set, parseValue); err != nil { + return nil, err + } + if err := applySetOverrides(values, "--set-string", opts.SetString, func(s string) interface{} { return s }); err != nil { + return nil, err + } + return values, nil +} + +// LoadValuesFile loads a single values file and applies --set overrides. func LoadValuesFile(path string, setOverrides []string) (map[string]interface{}, error) { + return LoadValues(ValuesOpts{Files: []string{path}, Set: setOverrides}) +} + +func readValuesFile(path string) (map[string]interface{}, error) { data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("reading values file %s: %w", path, err) @@ -33,13 +72,26 @@ func LoadValuesFile(path string, setOverrides []string) (map[string]interface{}, return nil, fmt.Errorf("unsupported values file format: %s (expected .json, .yaml, or .yml)", ext) } + // An empty YAML file or a JSON `null` decodes to a nil map. + if values == nil { + values = map[string]interface{}{} + } normalizeNumbers(values) + return values, nil +} - if err := applySetOverrides(values, setOverrides); err != nil { - return nil, fmt.Errorf("applying --set overrides: %w", err) +// mergeValues deep-merges src into dst. Nested maps merge key by key; any +// other value (including arrays) replaces what dst had, like Helm. +func mergeValues(dst, src map[string]interface{}) { + for k, v := range src { + srcMap, srcIsMap := v.(map[string]interface{}) + dstMap, dstIsMap := dst[k].(map[string]interface{}) + if srcIsMap && dstIsMap { + mergeValues(dstMap, srcMap) + continue + } + dst[k] = v } - - return values, nil } // normalizeNumbers converts float64 whole numbers (from JSON) and int (from YAML) @@ -72,18 +124,48 @@ func normalizeValue(v interface{}) interface{} { } } -func applySetOverrides(values map[string]interface{}, overrides []string) error { +func applySetOverrides(values map[string]interface{}, flag string, overrides []string, parse func(string) interface{}) error { for _, override := range overrides { - parts := strings.SplitN(override, "=", 2) - if len(parts) != 2 { - return fmt.Errorf("invalid --set format: %q (expected key=value)", override) + key, rawValue, ok := strings.Cut(override, "=") + if !ok || key == "" { + return fmt.Errorf("invalid %s format: %q (expected key=value)", flag, override) } - key, rawValue := parts[0], parts[1] - setNestedValue(values, strings.Split(key, "."), parseValue(rawValue)) + path, err := splitKeyPath(key) + if err != nil { + return fmt.Errorf("invalid %s key in %q: %w", flag, override, err) + } + setNestedValue(values, path, parse(rawValue)) } return nil } +// splitKeyPath splits a --set key on dots. A backslash escapes a dot, so +// `annotations.nginx\.ingress\.kubernetes\.io/rewrite-target` addresses one +// annotation key. +func splitKeyPath(key string) ([]string, error) { + var path []string + var cur strings.Builder + for i := 0; i < len(key); i++ { + switch c := key[i]; { + case c == '\\' && i+1 < len(key) && key[i+1] == '.': + cur.WriteByte('.') + i++ + case c == '.': + path = append(path, cur.String()) + cur.Reset() + default: + cur.WriteByte(c) + } + } + path = append(path, cur.String()) + for _, segment := range path { + if segment == "" { + return nil, fmt.Errorf("empty path segment in %q", key) + } + } + return path, nil +} + func setNestedValue(obj map[string]interface{}, keys []string, value interface{}) { for i, k := range keys { if i == len(keys)-1 { @@ -99,20 +181,23 @@ func setNestedValue(obj map[string]interface{}, keys []string, value interface{} } } +// parseValue types a --set value. Numbers are only typed when they survive a +// round trip unchanged, so image tags like "1.10" or "1.0" and zero-padded +// strings like "0123" stay strings instead of silently becoming 1.1, 1 or 123. func parseValue(s string) interface{} { - if s == "true" { + switch s { + case "true": return true - } - if s == "false" { + case "false": return false - } - if s == "null" { + case "null": return nil } - if i, err := strconv.ParseInt(s, 10, 64); err == nil { + if i, err := strconv.ParseInt(s, 10, 64); err == nil && strconv.FormatInt(i, 10) == s { return i } - if f, err := strconv.ParseFloat(s, 64); err == nil { + if f, err := strconv.ParseFloat(s, 64); err == nil && !math.IsNaN(f) && !math.IsInf(f, 0) && + strconv.FormatFloat(f, 'f', -1, 64) == s { return f } return s diff --git a/pkg/engine/values_test.go b/pkg/engine/values_test.go index aa38ec6..a4c018b 100644 --- a/pkg/engine/values_test.go +++ b/pkg/engine/values_test.go @@ -5,7 +5,7 @@ import ( "path/filepath" "testing" - "github.com/cloudticon/ctts/pkg/engine" + "github.com/cloudticon/ct/pkg/engine" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -164,3 +164,114 @@ func TestLoadValuesFile_FloatPreserved(t *testing.T) { require.NoError(t, err) assert.Equal(t, 0.75, values["ratio"]) } + +func TestLoadValues_NoSources(t *testing.T) { + values, err := engine.LoadValues(engine.ValuesOpts{}) + require.NoError(t, err) + assert.Equal(t, map[string]interface{}{}, values) +} + +func TestLoadValues_SetWithoutValuesFile(t *testing.T) { + values, err := engine.LoadValues(engine.ValuesOpts{Set: []string{"image.tag=v2", "replicas=3"}}) + require.NoError(t, err) + assert.Equal(t, map[string]interface{}{ + "image": map[string]interface{}{"tag": "v2"}, + "replicas": int64(3), + }, values) +} + +func TestLoadValues_EmptyYAMLFileWithSet(t *testing.T) { + // A values.yaml with only comments decodes to a nil map; --set used to + // panic writing into it. + path := filepath.Join(t.TempDir(), "values.yaml") + require.NoError(t, os.WriteFile(path, []byte("# all defaults commented out\n"), 0o644)) + + values, err := engine.LoadValues(engine.ValuesOpts{Files: []string{path}, Set: []string{"a=1"}}) + require.NoError(t, err) + assert.Equal(t, map[string]interface{}{"a": int64(1)}, values) +} + +func TestLoadValues_JSONNullFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "values.json") + require.NoError(t, os.WriteFile(path, []byte("null"), 0o644)) + + values, err := engine.LoadValues(engine.ValuesOpts{Files: []string{path}, Set: []string{"a=b"}}) + require.NoError(t, err) + assert.Equal(t, map[string]interface{}{"a": "b"}, values) +} + +func TestLoadValues_MultipleFilesDeepMerge(t *testing.T) { + dir := t.TempDir() + base := filepath.Join(dir, "values.yaml") + prod := filepath.Join(dir, "values-prod.json") + require.NoError(t, os.WriteFile(base, []byte(` +image: { repository: nginx, tag: "1.25" } +replicas: 1 +hosts: [a.example.com, b.example.com] +debug: true +`), 0o644)) + require.NoError(t, os.WriteFile(prod, []byte(`{"image":{"tag":"1.27"},"replicas":3,"hosts":["prod.example.com"]}`), 0o644)) + + values, err := engine.LoadValues(engine.ValuesOpts{Files: []string{base, prod}}) + require.NoError(t, err) + assert.Equal(t, map[string]interface{}{ + "image": map[string]interface{}{"repository": "nginx", "tag": "1.27"}, + "replicas": int64(3), + "hosts": []interface{}{"prod.example.com"}, + "debug": true, + }, values) +} + +func TestLoadValues_SetKeepsNonCanonicalNumbersAsStrings(t *testing.T) { + values, err := engine.LoadValues(engine.ValuesOpts{Set: []string{ + "tag=1.10", "minor=1.0", "zip=0123", "exp=1e3", "plus=+1", + "int=42", "neg=-7", "float=0.5", "on=true", "off=false", "nothing=null", + "nan=NaN", "inf=+Inf", "ninf=-Inf", + }}) + require.NoError(t, err) + assert.Equal(t, "1.10", values["tag"]) + assert.Equal(t, "1.0", values["minor"]) + assert.Equal(t, "0123", values["zip"]) + assert.Equal(t, "1e3", values["exp"]) + assert.Equal(t, "+1", values["plus"]) + assert.Equal(t, "NaN", values["nan"], "NaN and infinities can't be rendered as JSON numbers") + assert.Equal(t, "+Inf", values["inf"]) + assert.Equal(t, "-Inf", values["ninf"]) + assert.Equal(t, int64(42), values["int"]) + assert.Equal(t, int64(-7), values["neg"]) + assert.Equal(t, 0.5, values["float"]) + assert.Equal(t, true, values["on"]) + assert.Equal(t, false, values["off"]) + assert.Contains(t, values, "nothing") + assert.Nil(t, values["nothing"]) +} + +func TestLoadValues_SetString(t *testing.T) { + values, err := engine.LoadValues(engine.ValuesOpts{ + Set: []string{"replicas=3", "flag=true"}, + SetString: []string{"flag=true", "port=8080"}, + }) + require.NoError(t, err) + assert.Equal(t, int64(3), values["replicas"]) + assert.Equal(t, "true", values["flag"], "--set-string wins and stays a string") + assert.Equal(t, "8080", values["port"]) +} + +func TestLoadValues_SetEscapedDots(t *testing.T) { + values, err := engine.LoadValues(engine.ValuesOpts{Set: []string{ + `annotations.nginx\.ingress\.kubernetes\.io/rewrite-target=/`, + "url=https://example.com/a=b", + }}) + require.NoError(t, err) + assert.Equal(t, map[string]interface{}{ + "nginx.ingress.kubernetes.io/rewrite-target": "/", + }, values["annotations"]) + assert.Equal(t, "https://example.com/a=b", values["url"], "only the first = separates key and value") +} + +func TestLoadValues_SetRejectsEmptyKeySegments(t *testing.T) { + for _, bad := range []string{"=x", "a..b=x", ".a=x", "a.=x"} { + _, err := engine.LoadValues(engine.ValuesOpts{Set: []string{bad}}) + assert.Error(t, err, bad) + } +} diff --git a/pkg/k8s/apply.go b/pkg/k8s/apply.go index 1a661a0..b6ba10e 100644 --- a/pkg/k8s/apply.go +++ b/pkg/k8s/apply.go @@ -5,7 +5,10 @@ import ( "encoding/json" "fmt" "log" + "slices" + "time" + "github.com/cloudticon/ct/pkg/manifest" "github.com/fatih/color" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -17,19 +20,54 @@ import ( type Resource = map[string]interface{} +// crdEstablishTimeout bounds how long apply waits for discovery to serve a +// kind whose CRD was applied earlier in the same run. +var ( + crdEstablishTimeout = 30 * time.Second + crdPollInterval = 500 * time.Millisecond +) + +// apply server-side-applies resources in Helm install order (namespaces and +// CRDs first). Custom resources whose CRD is part of the same release wait +// until the API server starts serving the new kind. func (c *client) apply(ctx context.Context, resources []Resource) error { - for _, res := range resources { - if err := c.applyOne(ctx, res); err != nil { + ordered := slices.Clone(resources) + manifest.SortForApply(ordered) + + newKinds := map[string]bool{} + for _, res := range ordered { + if err := c.applyOne(ctx, res, newKinds); err != nil { return err } + if groupKind, ok := crdGroupKind(res); ok { + newKinds[groupKind] = true + } } return nil } -func (c *client) applyOne(ctx context.Context, res Resource) error { +// crdGroupKind returns "group/Kind" served by a CustomResourceDefinition. +func crdGroupKind(res Resource) (string, bool) { + if res["kind"] != "CustomResourceDefinition" { + return "", false + } + spec, _ := res["spec"].(map[string]interface{}) + group, _ := spec["group"].(string) + names, _ := spec["names"].(map[string]interface{}) + kind, _ := names["kind"].(string) + if group == "" || kind == "" { + return "", false + } + return group + "/" + kind, true +} + +func (c *client) applyOne(ctx context.Context, res Resource, newKinds map[string]bool) error { obj := toUnstructured(res) info, err := c.resolveResourceInfo(obj.GetAPIVersion(), obj.GetKind()) + if err != nil && newKinds[manifest.Group(obj.GetAPIVersion())+"/"+obj.GetKind()] { + info, err = c.waitForKind(ctx, obj.GetAPIVersion(), obj.GetKind()) + } if err != nil { return fmt.Errorf("resolving resource info for %s %s: %w", obj.GetAPIVersion(), obj.GetKind(), err) } @@ -63,6 +101,23 @@ func (c *client) applyOne(ctx context.Context, res Resource) error { return nil } +// waitForKind polls discovery until a freshly created CRD's kind is served. +func (c *client) waitForKind(ctx context.Context, apiVersion, kind string) (*resourceInfo, error) { + ctx, cancel := context.WithTimeout(ctx, crdEstablishTimeout) + defer cancel() + for { + info, err := c.resolveResourceInfo(apiVersion, kind) + if err == nil { + return info, nil + } + select { + case <-ctx.Done(): + return nil, fmt.Errorf("waiting for CRD to serve %s %s: %w", apiVersion, kind, err) + case <-time.After(crdPollInterval): + } + } +} + func toUnstructured(res Resource) *unstructured.Unstructured { return &unstructured.Unstructured{Object: res} } diff --git a/pkg/k8s/apply_test.go b/pkg/k8s/apply_test.go index 333727f..f60a44b 100644 --- a/pkg/k8s/apply_test.go +++ b/pkg/k8s/apply_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -11,6 +12,7 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/discovery" dynamicfake "k8s.io/client-go/dynamic/fake" "k8s.io/client-go/kubernetes/fake" k8stesting "k8s.io/client-go/testing" @@ -314,3 +316,115 @@ func TestApply_MixedScopes(t *testing.T) { assert.Equal(t, "", actions[0].GetNamespace()) assert.Equal(t, "my-ns", actions[1].GetNamespace()) } + +func patchedKinds(actions []k8stesting.Action) []string { + var kinds []string + for _, a := range actions { + if p, ok := a.(k8stesting.PatchAction); ok { + obj := map[string]interface{}{} + _ = json.Unmarshal(p.GetPatch(), &obj) + kinds = append(kinds, obj["kind"].(string)) + } + } + return kinds +} + +func TestApply_UsesHelmInstallOrder(t *testing.T) { + c, dynClient := newTestClient(t, []*metav1.APIResourceList{ + { + GroupVersion: "v1", + APIResources: []metav1.APIResource{ + {Name: "namespaces", Kind: "Namespace", Namespaced: false}, + {Name: "services", Kind: "Service", Namespaced: true}, + {Name: "configmaps", Kind: "ConfigMap", Namespaced: true}, + }, + }, + }) + + resources := []Resource{ + {"apiVersion": "v1", "kind": "Service", "metadata": map[string]interface{}{"name": "svc", "namespace": "team"}}, + {"apiVersion": "v1", "kind": "ConfigMap", "metadata": map[string]interface{}{"name": "cfg", "namespace": "team"}}, + {"apiVersion": "v1", "kind": "Namespace", "metadata": map[string]interface{}{"name": "team"}}, + } + + require.NoError(t, c.apply(context.Background(), resources)) + + assert.Equal(t, []string{"Namespace", "ConfigMap", "Service"}, patchedKinds(dynClient.Actions())) + assert.Equal(t, "Service", resources[0]["kind"], "caller's slice keeps its order") +} + +func TestApply_WaitsForKindOfCRDAppliedInSameRun(t *testing.T) { + oldTimeout, oldInterval := crdEstablishTimeout, crdPollInterval + crdEstablishTimeout, crdPollInterval = 2*time.Second, time.Millisecond + t.Cleanup(func() { crdEstablishTimeout, crdPollInterval = oldTimeout, oldInterval }) + + fakeClient := fake.NewSimpleClientset() + fakeClient.Fake.Resources = []*metav1.APIResourceList{{ + GroupVersion: "apiextensions.k8s.io/v1", + APIResources: []metav1.APIResource{{Name: "customresourcedefinitions", Kind: "CustomResourceDefinition"}}, + }} + dynClient := dynamicfake.NewSimpleDynamicClient(runtime.NewScheme()) + discoveryCalls := 0 + dynClient.PrependReactor("patch", "*", func(action k8stesting.Action) (bool, runtime.Object, error) { + return true, &unstructured.Unstructured{Object: map[string]interface{}{}}, nil + }) + c := &client{ + CoreV1: fakeClient.CoreV1(), + Discovery: &countingDiscovery{DiscoveryInterface: fakeClient.Discovery(), calls: &discoveryCalls}, + Dynamic: dynClient, + Namespace: "default", + gvrCache: make(map[string]*resourceInfo), + } + // The API server starts serving the new kind only after a few discovery + // round-trips, like a real CRD becoming Established. + c.Discovery.(*countingDiscovery).onCall = func(n int) { + if n == 4 { + fakeClient.Fake.Resources = append(fakeClient.Fake.Resources, &metav1.APIResourceList{ + GroupVersion: "example.com/v1", + APIResources: []metav1.APIResource{{Name: "widgets", Kind: "Widget", Namespaced: true}}, + }) + } + } + + resources := []Resource{ + {"apiVersion": "example.com/v1", "kind": "Widget", "metadata": map[string]interface{}{"name": "w"}}, + { + "apiVersion": "apiextensions.k8s.io/v1", + "kind": "CustomResourceDefinition", + "metadata": map[string]interface{}{"name": "widgets.example.com"}, + "spec": map[string]interface{}{ + "group": "example.com", + "names": map[string]interface{}{"kind": "Widget", "plural": "widgets"}, + }, + }, + } + + require.NoError(t, c.apply(context.Background(), resources)) + assert.Equal(t, []string{"CustomResourceDefinition", "Widget"}, patchedKinds(dynClient.Actions())) +} + +func TestApply_UnknownKindWithoutCRDFailsFast(t *testing.T) { + c, _ := newTestClient(t, nil) + + start := time.Now() + err := c.apply(context.Background(), []Resource{ + {"apiVersion": "example.com/v1", "kind": "Widget", "metadata": map[string]interface{}{"name": "w"}}, + }) + + require.Error(t, err) + assert.Less(t, time.Since(start), time.Second, "no CRD in the release, so no waiting") +} + +type countingDiscovery struct { + discovery.DiscoveryInterface + calls *int + onCall func(n int) +} + +func (d *countingDiscovery) ServerResourcesForGroupVersion(gv string) (*metav1.APIResourceList, error) { + *d.calls++ + if d.onCall != nil { + d.onCall(*d.calls) + } + return d.DiscoveryInterface.ServerResourcesForGroupVersion(gv) +} diff --git a/pkg/k8s/container_test.go b/pkg/k8s/container_test.go new file mode 100644 index 0000000..f578bf2 --- /dev/null +++ b/pkg/k8s/container_test.go @@ -0,0 +1,100 @@ +package k8s + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" +) + +func sidecarPod(annotations map[string]string) *corev1.Pod { + return &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{Name: "web-1", Namespace: "dev-ns", Annotations: annotations}, + Spec: corev1.PodSpec{Containers: []corev1.Container{ + {Name: "istio-proxy"}, + {Name: "app"}, + }}, + Status: corev1.PodStatus{Phase: corev1.PodRunning}, + } +} + +func TestDefaultContainerName(t *testing.T) { + assert.Equal(t, "app", defaultContainerName(sidecarPod(map[string]string{ + "kubectl.kubernetes.io/default-container": "app", + }))) + assert.Equal(t, "istio-proxy", defaultContainerName(sidecarPod(nil)), "first container without annotation") + assert.Equal(t, "istio-proxy", defaultContainerName(sidecarPod(map[string]string{ + "kubectl.kubernetes.io/default-container": "missing", + })), "stale annotation falls back to the first container") + assert.Equal(t, "", defaultContainerName(&corev1.Pod{})) +} + +// The API server rejects exec without a container for multi-container pods; +// the live adapter must pick the default container like kubectl does. +func TestLiveExecPod_DefaultsContainerForMultiContainerPod(t *testing.T) { + origRunner := execStreamRunnerFn + t.Cleanup(func() { execStreamRunnerFn = origRunner }) + + var got execStreamOpts + execStreamRunnerFn = func(_ context.Context, _ *client, _ string, _ []string, opts execStreamOpts) error { + got = opts + return nil + } + + clientset := fake.NewSimpleClientset(sidecarPod(map[string]string{ + "kubectl.kubernetes.io/default-container": "app", + })) + lc := &liveCluster{client: newClientFromInterfaces(clientset.CoreV1(), clientset.Discovery(), nil, "dev-ns")} + + require.NoError(t, lc.ExecPod(context.Background(), "dev-ns", "web-1", ExecOpts{Command: []string{"ls"}})) + assert.Equal(t, "app", got.Container) + + require.NoError(t, lc.ExecPod(context.Background(), "dev-ns", "web-1", ExecOpts{Command: []string{"ls"}, Container: "istio-proxy"})) + assert.Equal(t, "istio-proxy", got.Container, "an explicit container wins") +} + +func TestStreamPodLogs_UsesDefaultContainer(t *testing.T) { + clientset := fake.NewSimpleClientset(sidecarPod(map[string]string{ + "kubectl.kubernetes.io/default-container": "app", + })) + c := newClientFromInterfaces(clientset.CoreV1(), clientset.Discovery(), nil, "dev-ns") + + stream, err := streamPodLogs(context.Background(), c, "web-1", nil) + require.NoError(t, err) + _ = stream.Close() + + opts := lastLogOptions(t, clientset) + assert.Equal(t, "app", opts.Container) + assert.True(t, opts.Follow) + assert.True(t, opts.Timestamps, "timestamps are needed to resume without replaying") + assert.Nil(t, opts.SinceTime) + + since := time.Date(2026, 10, 5, 10, 0, 2, 0, time.UTC) + stream, err = streamPodLogs(context.Background(), c, "web-1", &since) + require.NoError(t, err) + _ = stream.Close() + opts = lastLogOptions(t, clientset) + require.NotNil(t, opts.SinceTime) + assert.True(t, opts.SinceTime.Time.Equal(since)) +} + +func lastLogOptions(t *testing.T, clientset *fake.Clientset) *corev1.PodLogOptions { + t.Helper() + var opts *corev1.PodLogOptions + for _, action := range clientset.Actions() { + if action.GetSubresource() != "log" { + continue + } + generic, ok := action.(k8stesting.GenericAction) + require.True(t, ok) + opts, _ = generic.GetValue().(*corev1.PodLogOptions) + } + require.NotNil(t, opts, "no logs request recorded") + return opts +} diff --git a/pkg/k8s/delete.go b/pkg/k8s/delete.go index 99c136c..73f050f 100644 --- a/pkg/k8s/delete.go +++ b/pkg/k8s/delete.go @@ -5,8 +5,10 @@ import ( "errors" "fmt" "log" + "sort" "strings" + "github.com/cloudticon/ct/pkg/manifest" "github.com/fatih/color" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -96,6 +98,17 @@ func orderForDelete(resources []ResourceRef) []ResourceRef { } } + // Undo the install order: custom resources first (while their CRD and + // controller still exist), then known kinds in reverse install order. + sort.SliceStable(regular, func(i, j int) bool { + ri, iok := manifest.InstallRank(regular[i].APIVersion, regular[i].Kind) + rj, jok := manifest.InstallRank(regular[j].APIVersion, regular[j].Kind) + if iok != jok { + return !iok + } + return iok && ri > rj + }) + ordered := make([]ResourceRef, 0, len(resources)) ordered = append(ordered, regular...) ordered = append(ordered, namespaces...) diff --git a/pkg/k8s/delete_test.go b/pkg/k8s/delete_test.go index e6d9a34..f876221 100644 --- a/pkg/k8s/delete_test.go +++ b/pkg/k8s/delete_test.go @@ -31,6 +31,30 @@ func TestOrderForDelete_SafetyOrder(t *testing.T) { }, ordered) } +func TestOrderForDelete_ReversesInstallOrderWithCustomResourcesFirst(t *testing.T) { + ref := func(apiVersion, kind, name string) ResourceRef { + return ResourceRef{APIVersion: apiVersion, Kind: kind, Name: name, Namespace: "team"} + } + input := []ResourceRef{ + {APIVersion: "v1", Kind: "Namespace", Name: "team"}, + ref("v1", "ConfigMap", "cfg"), + {APIVersion: "apiextensions.k8s.io/v1", Kind: "CustomResourceDefinition", Name: "widgets.example.com"}, + ref("v1", "Service", "web"), + ref("apps/v1", "Deployment", "web"), + ref("example.com/v1", "Widget", "w1"), + ref("v1", "ConfigMap", "ct-inventory-e2e"), + } + + var kinds []string + for _, r := range orderForDelete(input) { + kinds = append(kinds, r.Kind+"/"+r.Name) + } + assert.Equal(t, []string{ + "Widget/w1", "Deployment/web", "Service/web", "CustomResourceDefinition/widgets.example.com", + "ConfigMap/cfg", "Namespace/team", "ConfigMap/ct-inventory-e2e", + }, kinds) +} + func TestDelete_ContinuesOnNotFound(t *testing.T) { c, dynClient := newTestClient(t, []*metav1.APIResourceList{ { diff --git a/pkg/k8s/exec.go b/pkg/k8s/exec.go index adfe887..d67fd50 100644 --- a/pkg/k8s/exec.go +++ b/pkg/k8s/exec.go @@ -4,22 +4,22 @@ import ( "context" "errors" "fmt" - "io" - "net/http" - "net/url" - "os" "golang.org/x/term" + "io" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/tools/remotecommand" + "net/http" + "net/url" + "os" ) var ( - waitForPodForExecFn = waitForPod - execStreamRunnerFn = execStream - buildExecURLFn = buildExecURL - newExecExecutorForURL = remotecommand.NewSPDYExecutor - parameterCodec runtime.ParameterCodec = func() runtime.ParameterCodec { + waitForPodForExecFn = waitForPod + execStreamRunnerFn = execStream + buildExecURLFn = buildExecURL + newExecExecutorForURL = remotecommand.NewSPDYExecutor + parameterCodec runtime.ParameterCodec = func() runtime.ParameterCodec { s := runtime.NewScheme() _ = corev1.AddToScheme(s) return runtime.NewParameterCodec(s) @@ -71,10 +71,7 @@ func (q *termSizeQueue) monitor(fd int) { select { case <-q.sigCh: if w, h, err := getTermSizeFn(fd); err == nil { - select { - case q.resizeCh <- remotecommand.TerminalSize{Width: uint16(w), Height: uint16(h)}: - default: - } + q.offer(remotecommand.TerminalSize{Width: uint16(w), Height: uint16(h)}) } case <-q.done: return @@ -82,6 +79,23 @@ func (q *termSizeQueue) monitor(fd int) { } } +// offer queues size, replacing a size that has not been consumed yet: only +// the latest dimensions matter. (Dropping the new size instead lost the +// final size of a quick series of resizes.) Only the monitor goroutine sends. +func (q *termSizeQueue) offer(size remotecommand.TerminalSize) { + for { + select { + case q.resizeCh <- size: + return + default: + } + select { + case <-q.resizeCh: // discard the stale pending size + default: + } + } +} + func (q *termSizeQueue) Next() *remotecommand.TerminalSize { select { case size, ok := <-q.resizeCh: diff --git a/pkg/k8s/exec_test.go b/pkg/k8s/exec_test.go index fd091e8..509c9fc 100644 --- a/pkg/k8s/exec_test.go +++ b/pkg/k8s/exec_test.go @@ -6,6 +6,8 @@ import ( "errors" "net/http" "net/url" + "os" + "sync" "testing" "time" @@ -302,3 +304,46 @@ type staticSizeQueue struct { } func (q *staticSizeQueue) Next() *remotecommand.TerminalSize { return &q.size } + +// Resizing a window sends bursts of SIGWINCH. When a size was still pending, +// the newer size was dropped and the stale one kept, so the remote terminal +// could end up with the wrong dimensions until the next resize. +func TestTermSizeQueue_KeepsLatestSize(t *testing.T) { + origGetSize := getTermSizeFn + t.Cleanup(func() { getTermSizeFn = origGetSize }) + + var mu sync.Mutex + current := [2]int{80, 24} + calls := 0 + getTermSizeFn = func(int) (int, int, error) { + mu.Lock() + defer mu.Unlock() + calls++ + return current[0], current[1], nil + } + resize := func(w, h int) { + mu.Lock() + current = [2]int{w, h} + mu.Unlock() + } + sizeCalls := func() int { + mu.Lock() + defer mu.Unlock() + return calls + } + + q := newTermSizeQueue(0) // initial 80x24 is pending + defer q.stop() + + resize(100, 30) + q.sigCh <- os.Interrupt // the monitor ignores the value (SIGWINCH is not portable) + require.Eventually(t, func() bool { return sizeCalls() == 2 }, time.Second, time.Millisecond) + resize(120, 40) + q.sigCh <- os.Interrupt + require.Eventually(t, func() bool { return sizeCalls() == 3 }, time.Second, time.Millisecond) + time.Sleep(20 * time.Millisecond) // let the monitor finish queueing + + size := q.Next() + require.NotNil(t, size) + assert.Equal(t, remotecommand.TerminalSize{Width: 120, Height: 40}, *size, "the latest size must win over a stale pending one") +} diff --git a/pkg/k8s/inventory_test.go b/pkg/k8s/inventory_test.go index c3197e5..ab11d46 100644 --- a/pkg/k8s/inventory_test.go +++ b/pkg/k8s/inventory_test.go @@ -226,6 +226,21 @@ func TestListReleases_Namespace(t *testing.T) { }, metav1.CreateOptions{}) require.NoError(t, err) + // A ConfigMap the release itself renders carries the same labels as the + // inventory but is not one. + _, err = client.CoreV1.ConfigMaps("prod").Create(ctx, &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{ + Name: "app-config", + Namespace: "prod", + Labels: map[string]string{ + managedByLabelKey: "ct", + instanceLabelKey: "my-release", + }, + }, + Data: map[string]string{"LOG_LEVEL": "info"}, + }, metav1.CreateOptions{}) + require.NoError(t, err) + releases, err := listReleases(ctx, client, "prod", false) require.NoError(t, err) assert.Equal(t, []ReleaseInfo{ diff --git a/pkg/k8s/k8stest/fake.go b/pkg/k8s/k8stest/fake.go index 034b327..03473f7 100644 --- a/pkg/k8s/k8stest/fake.go +++ b/pkg/k8s/k8stest/fake.go @@ -13,7 +13,7 @@ import ( "sync/atomic" "time" - "github.com/cloudticon/ctts/pkg/k8s" + "github.com/cloudticon/ct/pkg/k8s" ) // FakePod is the in-memory pod fixture. Healthy=true means WaitPod returns @@ -28,6 +28,11 @@ type FakePod struct { // LogContent, when non-empty, is written to streamLogs' writer once and // the call then blocks on ctx until cancellation. LogContent string + + // Containers lists the pod's container names. When set, Exec/ExecPod + // validate ExecOpts.Container the way the API server does: an unknown + // name is rejected, and so is an empty name for a multi-container pod. + Containers []string } // ApplyCall records one ApplyRelease invocation. @@ -266,8 +271,16 @@ func (f *Fake) execPod(ctx context.Context, ns, pod string, sel k8s.Selector, op f.mu.Lock() f.ExecCalls = append(f.ExecCalls, ExecCall{Namespace: ns, Selector: sel, Pod: pod, Opts: opts}) + var containers []string + if p := f.Pods[ns][pod]; p != nil { + containers = append(containers, p.Containers...) + } f.mu.Unlock() + if err := validateExecContainer(pod, containers, opts.Container); err != nil { + return err + } + if f.ExecHook != nil { return f.ExecHook(ns, pod, opts) } @@ -327,6 +340,25 @@ func (f *Fake) findHealthyPod(ns string, sel k8s.Selector) string { return "" } +// validateExecContainer mirrors the API server's container check for exec. +func validateExecContainer(pod string, containers []string, container string) error { + if len(containers) == 0 { + return nil + } + if container == "" { + if len(containers) == 1 { + return nil + } + return fmt.Errorf("a container name must be specified for pod %s, choose one of: %v", pod, containers) + } + for _, c := range containers { + if c == container { + return nil + } + } + return fmt.Errorf("container %s is not valid for pod %s", container, pod) +} + func matchLabels(labels, sel k8s.Selector) bool { for k, v := range sel { if labels[k] != v { diff --git a/pkg/k8s/k8stest/fake_test.go b/pkg/k8s/k8stest/fake_test.go index dabf594..4d0163b 100644 --- a/pkg/k8s/k8stest/fake_test.go +++ b/pkg/k8s/k8stest/fake_test.go @@ -8,8 +8,8 @@ import ( "testing" "time" - "github.com/cloudticon/ctts/pkg/k8s" - "github.com/cloudticon/ctts/pkg/k8s/k8stest" + "github.com/cloudticon/ct/pkg/k8s" + "github.com/cloudticon/ct/pkg/k8s/k8stest" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -182,3 +182,23 @@ func TestFake_ExecHook_DrivesBehavior(t *testing.T) { func TestFake_SatisfiesPodExecutor(t *testing.T) { var _ k8s.PodExecutor = k8stest.NewFake() } + +func TestFake_ExecValidatesContainerLikeAPIServer(t *testing.T) { + f := k8stest.NewFake() + f.AddPod(&k8stest.FakePod{ + Name: "app-x", Namespace: "demo", + Labels: k8s.Selector{"app": "demo"}, Healthy: true, + Containers: []string{"app", "istio-proxy"}, + }) + f.ExecHook = func(ns, pod string, opts k8s.ExecOpts) error { return nil } + + err := f.ExecPod(context.Background(), "demo", "app-x", k8s.ExecOpts{Command: []string{"ls"}}) + require.Error(t, err) + assert.Contains(t, err.Error(), "a container name must be specified") + + err = f.ExecPod(context.Background(), "demo", "app-x", k8s.ExecOpts{Command: []string{"ls"}, Container: "nope"}) + require.Error(t, err) + assert.Contains(t, err.Error(), "not valid") + + require.NoError(t, f.ExecPod(context.Background(), "demo", "app-x", k8s.ExecOpts{Command: []string{"ls"}, Container: "app"})) +} diff --git a/pkg/k8s/labels_test.go b/pkg/k8s/labels_test.go index 633f6bd..55cd9e5 100644 --- a/pkg/k8s/labels_test.go +++ b/pkg/k8s/labels_test.go @@ -39,7 +39,7 @@ func TestInjectReleaseLabels_DoesNotOverrideExistingLabels(t *testing.T) { "metadata": map[string]interface{}{ "name": "cfg", "labels": map[string]interface{}{ - "custom": "value", + "custom": "value", "app.kubernetes.io/managed-by": "helm", "ct.cloudticon.com/instance": "existing-release", }, diff --git a/pkg/k8s/live_cluster.go b/pkg/k8s/live_cluster.go index 702b9e7..aef3fc6 100644 --- a/pkg/k8s/live_cluster.go +++ b/pkg/k8s/live_cluster.go @@ -122,7 +122,7 @@ func (lc *liveCluster) execPodOn(ctx context.Context, c *client, pod string, opt } streamOpts := execStreamOpts{ - Container: opts.Container, + Container: resolveContainer(ctx, c, pod, opts.Container), Stdin: opts.Stdin, Stdout: opts.Stdout, Stderr: opts.Stderr, diff --git a/pkg/k8s/logs.go b/pkg/k8s/logs.go index 316c638..e30cd90 100644 --- a/pkg/k8s/logs.go +++ b/pkg/k8s/logs.go @@ -8,10 +8,12 @@ import ( "hash/fnv" "io" "log" + "strings" "time" "github.com/fatih/color" corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) var logColorFns = []*color.Color{ @@ -23,9 +25,10 @@ var logColorFns = []*color.Color{ } var ( - waitForPodForLogsFn = waitForPod - streamPodLogsForLogsFn = streamPodLogs - sleepForLogReconnectsFn = time.Sleep + waitForPodForLogsFn = waitForPod + streamPodLogsForLogsFn = streamPodLogs + sleepForLogReconnectsFn = sleepContext + logReconnectDelay = 2 * time.Second ) // streamLogs streams pod logs for a selected target and reconnects on pod/log stream churn. @@ -38,6 +41,8 @@ func streamLogs(ctx context.Context, c *client, targetName string, selector map[ } prefix := logPrefix(targetName) + var lastPod string + var lastSeen time.Time // kubelet timestamp of the last line printed for lastPod for { pod, err := waitForPodForLogsFn(ctx, c, selector) if err != nil { @@ -47,46 +52,107 @@ func streamLogs(ctx context.Context, c *client, targetName string, selector map[ return err } - stream, err := streamPodLogsForLogsFn(ctx, c, pod) + // Reconnecting to the same pod (dropped connection, API server + // timeout) must not print its whole log again: ask only for newer + // lines and drop the ones already printed. + var since *time.Time + if pod == lastPod && !lastSeen.IsZero() { + s := lastSeen + since = &s + } else { + lastPod, lastSeen = pod, time.Time{} + } + + stream, err := streamPodLogsForLogsFn(ctx, c, pod, since) if err != nil { if ctx.Err() != nil { return nil } log.Printf("%s failed to open stream for %s (%s), reconnecting: %v", color.YellowString("[logs]"), targetName, pod, err) - sleepForLogReconnectsFn(2 * time.Second) + if !sleepForLogReconnectsFn(ctx, logReconnectDelay) { + return nil + } continue } - scanner := bufio.NewScanner(stream) - for scanner.Scan() { - fmt.Fprintf(w, "%s%s\n", prefix, scanner.Text()) - } + readErr := copyLogLines(stream, w, prefix, &lastSeen) _ = stream.Close() + if ctx.Err() != nil { + return nil + } + if readErr != nil { + log.Printf("%s stream interrupted for %s (%s), reconnecting: %v", color.YellowString("[logs]"), targetName, pod, readErr) + } + // Also pause after a clean end of stream (container restarting, pod + // going away) so a stream that ends right away cannot spin. + if !sleepForLogReconnectsFn(ctx, logReconnectDelay) { + return nil + } + } +} - if scanErr := scanner.Err(); scanErr != nil { - if ctx.Err() != nil { +// copyLogLines writes every line of r to w with prefix. Lines may be of any +// length (bufio.Scanner stops at 64 KiB). Lines carrying a kubelet timestamp +// have it stripped; lines not newer than *lastSeen are skipped (already +// printed before a reconnect) and *lastSeen tracks the newest line printed. +func copyLogLines(r io.Reader, w io.Writer, prefix string, lastSeen *time.Time) error { + br := bufio.NewReader(r) + printedUpTo := *lastSeen + for { + line, err := br.ReadString('\n') + if line != "" { + writeLogLine(w, prefix, line, printedUpTo, lastSeen) + } + if err != nil { + if errors.Is(err, io.EOF) { return nil } - log.Printf("%s stream interrupted for %s (%s), reconnecting: %v", color.YellowString("[logs]"), targetName, pod, scanErr) - sleepForLogReconnectsFn(2 * time.Second) - continue + return err } + } +} - if ctx.Err() != nil { - return nil +func writeLogLine(w io.Writer, prefix, line string, printedUpTo time.Time, lastSeen *time.Time) { + text := strings.TrimRight(line, "\r\n") + if ts, msg, ok := splitLogTimestamp(text); ok { + if !printedUpTo.IsZero() && !ts.After(printedUpTo) { + return // printed before the reconnect } + *lastSeen = ts + text = msg } + fmt.Fprintf(w, "%s%s\n", prefix, text) } -func streamPodLogs(ctx context.Context, c *client, pod string) (io.ReadCloser, error) { +// splitLogTimestamp splits the RFC3339 timestamp the kubelet prepends to each +// line when PodLogOptions.Timestamps is set. +func splitLogTimestamp(line string) (time.Time, string, bool) { + i := strings.IndexByte(line, ' ') + if i <= 0 { + return time.Time{}, line, false + } + ts, err := time.Parse(time.RFC3339Nano, line[:i]) + if err != nil { + return time.Time{}, line, false + } + return ts, line[i+1:], true +} + +func streamPodLogs(ctx context.Context, c *client, pod string, since *time.Time) (io.ReadCloser, error) { if c.CoreV1 == nil { return nil, errors.New("kubernetes core/v1 client is required") } - req := c.CoreV1.Pods(c.Namespace).GetLogs(pod, &corev1.PodLogOptions{ - Follow: true, - }) - stream, err := req.Stream(ctx) + opts := &corev1.PodLogOptions{ + Container: resolveContainer(ctx, c, pod, ""), + Follow: true, + Timestamps: true, + } + if since != nil { + t := metav1.NewTime(*since) + opts.SinceTime = &t + } + stream, err := c.CoreV1.Pods(c.Namespace).GetLogs(pod, opts).Stream(ctx) if err != nil { return nil, fmt.Errorf("opening logs stream for pod %s: %w", pod, err) } diff --git a/pkg/k8s/logs_test.go b/pkg/k8s/logs_test.go index 4510cd1..d38a502 100644 --- a/pkg/k8s/logs_test.go +++ b/pkg/k8s/logs_test.go @@ -5,8 +5,10 @@ import ( "context" "errors" "io" + "regexp" "strings" "testing" + "testing/iotest" "time" "github.com/stretchr/testify/assert" @@ -35,7 +37,7 @@ func TestStreamLogs_ReconnectsAndWritesPrefixedLines(t *testing.T) { sleepForLogReconnectsFn = origSleep }) - sleepForLogReconnectsFn = func(time.Duration) {} + sleepForLogReconnectsFn = func(ctx context.Context, _ time.Duration) bool { return ctx.Err() == nil } ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -44,7 +46,7 @@ func TestStreamLogs_ReconnectsAndWritesPrefixedLines(t *testing.T) { } streamCalls := 0 - streamPodLogsForLogsFn = func(_ context.Context, _ *client, _ string) (io.ReadCloser, error) { + streamPodLogsForLogsFn = func(_ context.Context, _ *client, _ string, _ *time.Time) (io.ReadCloser, error) { streamCalls++ switch streamCalls { case 1: @@ -103,3 +105,104 @@ func TestLogPrefix_IsStableForTarget(t *testing.T) { assert.Equal(t, prefixA, prefixB) assert.Contains(t, prefixA, "[service-a]") } + +func stubLogs(t *testing.T) { + t.Helper() + origWait, origStream, origSleep, origDelay := waitForPodForLogsFn, streamPodLogsForLogsFn, sleepForLogReconnectsFn, logReconnectDelay + t.Cleanup(func() { + waitForPodForLogsFn, streamPodLogsForLogsFn, sleepForLogReconnectsFn, logReconnectDelay = origWait, origStream, origSleep, origDelay + }) + waitForPodForLogsFn = func(_ context.Context, _ *client, _ map[string]string) (string, error) { + return "pod-1", nil + } + sleepForLogReconnectsFn = func(ctx context.Context, _ time.Duration) bool { return ctx.Err() == nil } +} + +// bufio.Scanner gives up on lines over 64 KiB ("token too long"): the stream +// was treated as interrupted, reconnected and replayed the whole log, hitting +// the same line again - forever. +func TestStreamLogs_HandlesVeryLongLines(t *testing.T) { + stubLogs(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + long := strings.Repeat("x", 200*1024) + calls := 0 + streamPodLogsForLogsFn = func(_ context.Context, _ *client, _ string, _ *time.Time) (io.ReadCloser, error) { + calls++ + if calls > 1 { + cancel() + return nil, context.Canceled + } + return io.NopCloser(strings.NewReader(long + "\nnext\n")), nil + } + + var out bytes.Buffer + require.NoError(t, streamLogs(ctx, &client{}, "web", map[string]string{"app": "web"}, &out)) + assert.Contains(t, out.String(), long) + assert.Contains(t, out.String(), "[web] next\n") +} + +// Reconnecting to the same pod (dropped connection, API server timeout) +// requested the full log again and printed every line a second time. +func TestStreamLogs_ReconnectToSamePodDoesNotReplay(t *testing.T) { + stubLogs(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + var sinceOnReconnect *time.Time + calls := 0 + streamPodLogsForLogsFn = func(_ context.Context, _ *client, _ string, since *time.Time) (io.ReadCloser, error) { + calls++ + switch calls { + case 1: + return io.NopCloser(io.MultiReader( + strings.NewReader("2026-10-05T10:00:01.000000001Z first\n2026-10-05T10:00:02.000000002Z second\n"), + iotest.ErrReader(errors.New("http2: stream reset")), + )), nil + case 2: + sinceOnReconnect = since + // The server resolves SinceTime to whole seconds and may resend + // lines that were already printed. + return &readCloserWithCloseFn{ + Reader: strings.NewReader("2026-10-05T10:00:02.000000002Z second\n2026-10-05T10:00:03.000000003Z third\r\n"), + closeFn: func() error { + cancel() + return nil + }, + }, nil + default: + return nil, context.Canceled + } + } + + var out bytes.Buffer + require.NoError(t, streamLogs(ctx, &client{}, "web", map[string]string{"app": "web"}, &out)) + assert.Equal(t, "[web] first\n[web] second\n[web] third\n", stripANSI(out.String())) + require.NotNil(t, sinceOnReconnect, "reconnect must ask only for newer lines") + assert.Equal(t, "2026-10-05T10:00:02.000000002Z", sinceOnReconnect.Format(time.RFC3339Nano)) +} + +func TestStreamLogs_CancelDuringReconnectWaitReturnsPromptly(t *testing.T) { + stubLogs(t) + sleepForLogReconnectsFn = sleepContext + logReconnectDelay = time.Hour + ctx, cancel := context.WithCancel(context.Background()) + streamPodLogsForLogsFn = func(_ context.Context, _ *client, _ string, _ *time.Time) (io.ReadCloser, error) { + time.AfterFunc(20*time.Millisecond, cancel) + return nil, errors.New("temporary") + } + + done := make(chan error, 1) + go func() { done <- streamLogs(ctx, &client{}, "web", nil, io.Discard) }() + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(2 * time.Second): + t.Fatal("streamLogs did not return after cancel") + } +} + +func stripANSI(s string) string { + return regexp.MustCompile("\x1b\\[[0-9;]*m").ReplaceAllString(s, "") +} diff --git a/pkg/k8s/pod.go b/pkg/k8s/pod.go index 951c161..614aeb2 100644 --- a/pkg/k8s/pod.go +++ b/pkg/k8s/pod.go @@ -7,6 +7,7 @@ import ( "io" "log" "os" + "sync" "time" "github.com/fatih/color" @@ -14,6 +15,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/watch" ) // waitLog writes directly to stderr so messages are visible even when the @@ -45,7 +47,48 @@ func containerProblem(pod *corev1.Pod) string { return "" } +// rewatchDelay is the pause before listing again after the API server closed +// the pod watch. +var rewatchDelay = time.Second + +// pendingProblemReasons are waiting reasons that keep a pod from ever +// becoming ready without the user changing something (image, config, ...). +var pendingProblemReasons = map[string]bool{ + "ImagePullBackOff": true, + "ErrImagePull": true, + "InvalidImageName": true, + "CreateContainerConfigError": true, + "CreateContainerError": true, + "CrashLoopBackOff": true, +} + +// pendingProblem explains why a pod that is not running cannot start, or +// returns "" when it is just on its way. +func pendingProblem(pod *corev1.Pod) string { + for _, statuses := range [][]corev1.ContainerStatus{pod.Status.InitContainerStatuses, pod.Status.ContainerStatuses} { + for _, cs := range statuses { + waiting := cs.State.Waiting + if waiting == nil || !pendingProblemReasons[waiting.Reason] { + continue + } + if waiting.Message != "" { + return fmt.Sprintf("container %q is in %s: %s", cs.Name, waiting.Reason, waiting.Message) + } + return fmt.Sprintf("container %q is in %s", cs.Name, waiting.Reason) + } + } + for _, cond := range pod.Status.Conditions { + if cond.Type == corev1.PodScheduled && cond.Status == corev1.ConditionFalse && cond.Reason == corev1.PodReasonUnschedulable { + return "cannot be scheduled: " + cond.Message + } + } + return "" +} + // waitForPod blocks until a healthy running pod matching selector is available. +// While waiting it reports why pending pods cannot start (image pull errors, +// missing config, unschedulable), which would otherwise look like an endless +// "waiting for pod". func waitForPod(ctx context.Context, c *client, selector map[string]string) (string, error) { if c.CoreV1 == nil { return "", errors.New("kubernetes core/v1 client is required") @@ -54,6 +97,19 @@ func waitForPod(ctx context.Context, c *client, selector map[string]string) (str labelSelector := labels.Set(selector).String() podsClient := c.CoreV1.Pods(c.Namespace) + reported := map[string]string{} + reportPending := func(pod *corev1.Pod) { + if pod.DeletionTimestamp != nil || pod.Status.Phase == corev1.PodRunning { + return + } + problem := pendingProblem(pod) + if problem == "" || reported[pod.Name] == problem { + return + } + reported[pod.Name] = problem + waitLog.Printf("%s pod %q: %s (still waiting)", color.YellowString("[wait]"), pod.Name, problem) + } + for { list, err := podsClient.List(ctx, metav1.ListOptions{LabelSelector: labelSelector}) if err != nil { @@ -71,6 +127,9 @@ func waitForPod(ctx context.Context, c *client, selector map[string]string) (str } continue } + for i := range list.Items { + reportPending(&list.Items[i]) + } // No running pods — fall back to watch (original behavior). watcher, err := podsClient.Watch(ctx, metav1.ListOptions{LabelSelector: labelSelector}) @@ -78,25 +137,37 @@ func waitForPod(ctx context.Context, c *client, selector map[string]string) (str return "", fmt.Errorf("watching pods for selector %q: %w", labelSelector, err) } - for { - select { - case <-ctx.Done(): - watcher.Stop() - return "", ctx.Err() - case event, ok := <-watcher.ResultChan(): - if !ok { - watcher.Stop() - return "", errors.New("pod watch channel closed before a running pod appeared") - } - pod, ok := event.Object.(*corev1.Pod) - if !ok || pod == nil || pod.DeletionTimestamp != nil { - continue - } - if pod.Status.Phase == corev1.PodRunning { - watcher.Stop() - return pod.Name, nil - } + if name, err := waitForRunningPod(ctx, watcher, reportPending); err != nil || name != "" { + return name, err + } + // The API server closed the watch (timeouts after 30-60 minutes, + // restarts): list again instead of failing. + if !sleepContext(ctx, rewatchDelay) { + return "", ctx.Err() + } + } +} + +// waitForRunningPod consumes watch events until a pod is running. It returns +// ("", nil) when the watch was closed by the server. +func waitForRunningPod(ctx context.Context, watcher watch.Interface, reportPending func(*corev1.Pod)) (string, error) { + defer watcher.Stop() + for { + select { + case <-ctx.Done(): + return "", ctx.Err() + case event, ok := <-watcher.ResultChan(): + if !ok { + return "", nil } + pod, ok := event.Object.(*corev1.Pod) + if !ok || pod == nil || pod.DeletionTimestamp != nil { + continue + } + if pod.Status.Phase == corev1.PodRunning { + return pod.Name, nil + } + reportPending(pod) } } } @@ -125,7 +196,67 @@ func firstRunningPodName(pods []corev1.Pod) (name, problem string) { return name, problem } +// defaultContainerAnnotation names the container kubectl uses when a command +// does not specify one. ct dev sets it on patched workloads; service meshes +// set it when they inject a sidecar. +const defaultContainerAnnotation = "kubectl.kubernetes.io/default-container" + +// resolveContainer returns container when it is set. Otherwise it returns +// the pod's default container the way kubectl resolves it, because the API +// server rejects exec and log requests without a container name for pods +// with more than one container (e.g. an injected sidecar). It returns "" when +// the pod cannot be read, leaving the choice to the API server. +func resolveContainer(ctx context.Context, c *client, podName, container string) string { + if container != "" || c == nil || c.CoreV1 == nil { + return container + } + pod, err := c.CoreV1.Pods(c.Namespace).Get(ctx, podName, metav1.GetOptions{}) + if err != nil { + return "" + } + return defaultContainerName(pod) +} + +// defaultContainerName returns the container named by the default-container +// annotation when it exists in the pod, else the first container. +func defaultContainerName(pod *corev1.Pod) string { + if name := pod.Annotations[defaultContainerAnnotation]; name != "" { + for _, c := range pod.Spec.Containers { + if c.Name == name { + return name + } + } + } + if len(pod.Spec.Containers) > 0 { + return pod.Spec.Containers[0].Name + } + return "" +} + +// problemReports remembers when a pod problem was last printed. Several +// features wait for the same pod concurrently (session, port-forward, logs, +// sync); without this each printed the same crash logs every retry. +var ( + problemReportsMu sync.Mutex + problemReports = map[string]time.Time{} + problemReportsEvery = 30 * time.Second +) + +func shouldReportProblem(podName, problem string) bool { + problemReportsMu.Lock() + defer problemReportsMu.Unlock() + key := podName + "\x00" + problem + if last, ok := problemReports[key]; ok && time.Since(last) < problemReportsEvery { + return false + } + problemReports[key] = time.Now() + return true +} + func logContainerProblem(ctx context.Context, c *client, podName, problem string) { + if !shouldReportProblem(podName, problem) { + return + } waitLog.Printf("%s pod %q: %s, fetching crash logs...", color.YellowString("[wait]"), podName, problem) if logs := fetchPreviousLogsFn(ctx, c, podName); logs != "" { waitLog.Printf("%s previous logs for %q:\n%s", color.YellowString("[wait]"), podName, logs) @@ -136,6 +267,7 @@ func logContainerProblem(ctx context.Context, c *client, podName, problem string func fetchPreviousLogs(ctx context.Context, c *client, podName string) string { tailLines := int64(20) req := c.CoreV1.Pods(c.Namespace).GetLogs(podName, &corev1.PodLogOptions{ + Container: resolveContainer(ctx, c, podName, ""), Previous: true, TailLines: &tailLines, }) @@ -192,7 +324,6 @@ func watchPodHealth(ctx context.Context, c *client, podName string) error { } } - func defaultRetrySleep(ctx context.Context) error { select { case <-ctx.Done(): diff --git a/pkg/k8s/pod_test.go b/pkg/k8s/pod_test.go index 739ee67..27f7f51 100644 --- a/pkg/k8s/pod_test.go +++ b/pkg/k8s/pod_test.go @@ -1,8 +1,12 @@ package k8s import ( + "bytes" "context" "errors" + "log" + "strings" + "sync" "testing" "time" @@ -474,7 +478,6 @@ func TestWatchPodHealth_ReturnsWhenPodNotRunning(t *testing.T) { assert.Contains(t, err.Error(), "is no longer running") } - func TestFirstRunningPodName_EmptyWhenAllTerminating(t *testing.T) { now := metav1.Now() pods := []corev1.Pod{ @@ -492,3 +495,158 @@ func TestFirstRunningPodName_EmptyWhenAllTerminating(t *testing.T) { assert.Empty(t, name) assert.Empty(t, problem) } + +func captureWaitLog(t *testing.T) *syncBuffer { + t.Helper() + buf := &syncBuffer{} + orig := waitLog + waitLog = log.New(buf, "", 0) + t.Cleanup(func() { waitLog = orig }) + return buf +} + +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +func pendingPod(name string, mutate func(*corev1.Pod)) *corev1.Pod { + p := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "dev-ns", Labels: map[string]string{"app": "web"}}, + Status: corev1.PodStatus{Phase: corev1.PodPending}, + } + mutate(p) + return p +} + +// Image pull and config errors keep the pod Pending; they were only reported +// for Running pods, so a typo in `image:` left the user staring at +// "waiting for pod web..." forever. +func TestWaitForPod_ReportsWhyPendingPodDoesNotStart(t *testing.T) { + logs := captureWaitLog(t) + clientset := fake.NewSimpleClientset(pendingPod("web-1", func(p *corev1.Pod) { + p.Status.ContainerStatuses = []corev1.ContainerStatus{{Name: "app", State: corev1.ContainerState{ + Waiting: &corev1.ContainerStateWaiting{Reason: "ImagePullBackOff", Message: `Back-off pulling image "web:dve"`}, + }}} + })) + w := watch.NewFake() + clientset.Fake.PrependWatchReactor("pods", func(k8stesting.Action) (bool, watch.Interface, error) { return true, w, nil }) + c := newClientFromInterfaces(clientset.CoreV1(), clientset.Discovery(), nil, "dev-ns") + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + result := make(chan error, 1) + go func() { + _, err := waitForPod(ctx, c, map[string]string{"app": "web"}) + result <- err + }() + + require.Eventually(t, func() bool { return strings.Contains(logs.String(), "ImagePullBackOff") }, 2*time.Second, 10*time.Millisecond, + "the reason the pod does not start must be shown while waiting") + assert.Contains(t, logs.String(), `pod "web-1": container "app" is in ImagePullBackOff: Back-off pulling image "web:dve"`) + + w.Modify(pendingPod("web-1", func(p *corev1.Pod) { + p.Status.Conditions = []corev1.PodCondition{{ + Type: corev1.PodScheduled, Status: corev1.ConditionFalse, Reason: "Unschedulable", + Message: "0/3 nodes are available: 3 Insufficient cpu.", + }} + })) + require.Eventually(t, func() bool { return strings.Contains(logs.String(), "Insufficient cpu") }, 2*time.Second, 10*time.Millisecond) + + w.Modify(&corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{Name: "web-1", Namespace: "dev-ns", Labels: map[string]string{"app": "web"}}, + Status: corev1.PodStatus{Phase: corev1.PodRunning}, + }) + require.NoError(t, <-result) +} + +// The API server closes watches routinely (timeouts after 30-60 minutes, +// restarts); that used to abort the wait with an error. +func TestWaitForPod_RewatchesWhenWatchCloses(t *testing.T) { + origDelay := rewatchDelay + rewatchDelay = time.Millisecond + t.Cleanup(func() { rewatchDelay = origDelay }) + + clientset := fake.NewSimpleClientset() + watches := 0 + first := watch.NewFake() + clientset.Fake.PrependWatchReactor("pods", func(k8stesting.Action) (bool, watch.Interface, error) { + watches++ + if watches == 1 { + return true, first, nil + } + w := watch.NewFake() + go w.Add(&corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{Name: "web-2", Namespace: "dev-ns", Labels: map[string]string{"app": "web"}}, + Status: corev1.PodStatus{Phase: corev1.PodRunning}, + }) + return true, w, nil + }) + c := newClientFromInterfaces(clientset.CoreV1(), clientset.Discovery(), nil, "dev-ns") + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + type res struct { + pod string + err error + } + result := make(chan res, 1) + go func() { + pod, err := waitForPod(ctx, c, map[string]string{"app": "web"}) + result <- res{pod, err} + }() + time.Sleep(50 * time.Millisecond) + first.Stop() + + r := <-result + require.NoError(t, r.err) + assert.Equal(t, "web-2", r.pod) +} + +// Port-forward, log streaming, sync and the session all wait for the same +// pod; during a crash loop each of them printed the same crash logs every +// five seconds. +func TestLogContainerProblem_DedupesAcrossWaiters(t *testing.T) { + resetProblemReports(t) + logs := captureWaitLog(t) + origFetch := fetchPreviousLogsFn + t.Cleanup(func() { fetchPreviousLogsFn = origFetch }) + fetches := 0 + fetchPreviousLogsFn = func(context.Context, *client, string) string { + fetches++ + return "panic: boom" + } + + for i := 0; i < 4; i++ { + logContainerProblem(context.Background(), &client{}, "web-dedupe-1", `container "app" is in CrashLoopBackOff`) + } + assert.Equal(t, 1, strings.Count(logs.String(), "panic: boom")) + assert.Equal(t, 1, fetches) + + logContainerProblem(context.Background(), &client{}, "web-dedupe-1", `container "app" has terminated (Error, exit code 1)`) + assert.Equal(t, 2, strings.Count(logs.String(), "panic: boom"), "a different problem is reported") +} + +func resetProblemReports(t *testing.T) { + t.Helper() + problemReportsMu.Lock() + problemReports = map[string]time.Time{} + problemReportsMu.Unlock() + t.Cleanup(func() { + problemReportsMu.Lock() + problemReports = map[string]time.Time{} + problemReportsMu.Unlock() + }) +} diff --git a/pkg/k8s/portforward.go b/pkg/k8s/portforward.go index 755498a..40f346c 100644 --- a/pkg/k8s/portforward.go +++ b/pkg/k8s/portforward.go @@ -7,6 +7,9 @@ import ( "io" "log" "net/http" + "strconv" + "strings" + "time" "github.com/fatih/color" @@ -23,6 +26,13 @@ type PortRule struct { var ( waitForPodFn = waitForPod forwardPortsFn = forwardPorts + + // portForwardBackoff is the wait before the first reconnect; it doubles + // up to maxPortForwardBackoff and resets once a forward stayed up for + // portForwardStableAfter. + portForwardBackoff = time.Second + maxPortForwardBackoff = 10 * time.Second + portForwardStableAfter = 10 * time.Second ) // portForward starts port forwarding for the selected workload and reconnects on connection loss. @@ -34,6 +44,7 @@ func portForward(ctx context.Context, c *client, selector map[string]string, por return errors.New("at least one port rule is required") } + backoff := portForwardBackoff for { pod, err := waitForPodFn(ctx, c, selector) if err != nil { @@ -43,14 +54,62 @@ func portForward(ctx context.Context, c *client, selector map[string]string, por return err } - if err := forwardPortsFn(ctx, c, pod, ports); err != nil { - if ctx.Err() != nil { - return nil - } - log.Printf("%s connection lost for pod %s, reconnecting: %v", color.YellowString("[port-forward]"), pod, err) - continue + started := time.Now() + err = forwardPortsFn(ctx, c, pod, ports) + if err == nil || ctx.Err() != nil { + return nil + } + if isLocalListenError(err) { + return fmt.Errorf("port-forward to pod %s: could not listen on local port(s) %s - already in use by another process (or another ct dev session)? %w", + pod, localPorts(ports), err) + } + if isAccessDenied(err) { + return fmt.Errorf("port-forward to pod %s denied (port-forwarding needs create on pods/portforward): %w", pod, err) + } + if time.Since(started) >= portForwardStableAfter { + backoff = portForwardBackoff + } + log.Printf("%s connection lost for pod %s, reconnecting in %s: %v", color.YellowString("[port-forward]"), pod, backoff, err) + if !sleepContext(ctx, backoff) { + return nil + } + backoff *= 2 + if backoff > maxPortForwardBackoff { + backoff = maxPortForwardBackoff } - return nil + } +} + +// isLocalListenError reports client-go's "no local port could be opened" +// failure, which reconnecting cannot fix. +func isLocalListenError(err error) bool { + return strings.Contains(err.Error(), "unable to listen on any of the requested ports") +} + +// isAccessDenied reports an RBAC/authentication refusal of the upgrade. +// client-go flattens the API status into the message, so match on it. +func isAccessDenied(err error) bool { + msg := err.Error() + return strings.Contains(msg, "is forbidden") || strings.Contains(msg, "Unauthorized") +} + +func localPorts(ports []PortRule) string { + parts := make([]string, 0, len(ports)) + for _, p := range ports { + parts = append(parts, strconv.Itoa(p.Local)) + } + return strings.Join(parts, ", ") +} + +// sleepContext waits for d and reports whether it did so before ctx ended. +func sleepContext(ctx context.Context, d time.Duration) bool { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return false + case <-t.C: + return true } } @@ -78,22 +137,33 @@ func forwardPorts(ctx context.Context, c *client, pod string, ports []PortRule) dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, http.MethodPost, reqURL) stopCh := make(chan struct{}) readyCh := make(chan struct{}) + // done ends the helper goroutines below when ForwardPorts returns, + // whatever the reason; they used to leak on every failed attempt. + done := make(chan struct{}) + defer close(done) go func() { select { case <-ctx.Done(): close(stopCh) - case <-stopCh: + case <-done: } }() - forwarder, err := portforward.New(dialer, toPFPorts(ports), stopCh, readyCh, io.Discard, io.Discard) + // client-go reports ports it could not listen on to errOut; a partially + // working forward must not fail silently. + errOut := &lineLogger{prefix: color.YellowString("[port-forward]")} + forwarder, err := portforward.New(dialer, toPFPorts(ports), stopCh, readyCh, io.Discard, errOut) if err != nil { return fmt.Errorf("creating port forwarder: %w", err) } go func() { - <-readyCh + select { + case <-readyCh: + case <-done: + return + } for _, p := range ports { log.Printf("%s localhost:%d -> %s:%d", color.CyanString("[port-forward]"), p.Local, pod, p.Remote) } @@ -106,6 +176,20 @@ func forwardPorts(ctx context.Context, c *client, pod string, ports []PortRule) return nil } +// lineLogger forwards every line written to it to the standard logger. +type lineLogger struct { + prefix string +} + +func (l *lineLogger) Write(p []byte) (int, error) { + for _, line := range strings.Split(strings.TrimRight(string(p), "\n"), "\n") { + if strings.TrimSpace(line) != "" { + log.Printf("%s %s", l.prefix, line) + } + } + return len(p), nil +} + func toPFPorts(ports []PortRule) []string { result := make([]string, 0, len(ports)) for _, p := range ports { @@ -113,4 +197,3 @@ func toPFPorts(ports []PortRule) []string { } return result } - diff --git a/pkg/k8s/portforward_test.go b/pkg/k8s/portforward_test.go index 498d917..f2c4abc 100644 --- a/pkg/k8s/portforward_test.go +++ b/pkg/k8s/portforward_test.go @@ -1,15 +1,26 @@ package k8s import ( + "bytes" "context" "errors" + "fmt" + "log" + "net/http" + "net/http/httptest" + "runtime" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + corev1client "k8s.io/client-go/kubernetes/typed/core/v1" + "k8s.io/client-go/rest" ) func TestPortForward_ReconnectsAfterForwardError(t *testing.T) { + stubPortForward(t) + portForwardBackoff = time.Millisecond origWaitForPodFn := waitForPodFn origForwardPortsFn := forwardPortsFn t.Cleanup(func() { @@ -97,3 +108,145 @@ func TestToPFPorts(t *testing.T) { assert.Equal(t, []string{"3000:3000", "15432:5432"}, ports) } + +func stubPortForward(t *testing.T) { + t.Helper() + origWait, origForward := waitForPodFn, forwardPortsFn + origBackoff, origMax := portForwardBackoff, maxPortForwardBackoff + t.Cleanup(func() { + waitForPodFn, forwardPortsFn = origWait, origForward + portForwardBackoff, maxPortForwardBackoff = origBackoff, origMax + }) + waitForPodFn = func(_ context.Context, _ *client, _ map[string]string) (string, error) { + return "pod-1", nil + } +} + +// "local port in use" can never be fixed by reconnecting; it used to be +// retried in a tight loop, each attempt opening a new API server connection. +func TestPortForward_LocalPortInUseIsFatal(t *testing.T) { + stubPortForward(t) + calls := 0 + forwardPortsFn = func(_ context.Context, _ *client, pod string, _ []PortRule) error { + calls++ + return fmt.Errorf("forwarding ports for pod %s: %w", pod, + errors.New("unable to listen on any of the requested ports: [{8080 80}]")) + } + + done := make(chan error, 1) + go func() { + done <- portForward(context.Background(), &client{}, map[string]string{"app": "web"}, []PortRule{{Local: 8080, Remote: 80}}) + }() + select { + case err := <-done: + require.Error(t, err) + assert.Contains(t, err.Error(), "8080") + assert.Contains(t, err.Error(), "already in use") + assert.Equal(t, 1, calls) + case <-time.After(2 * time.Second): + t.Fatal("portForward kept retrying an error that a reconnect cannot fix") + } +} + +func TestPortForward_BacksOffBetweenReconnects(t *testing.T) { + stubPortForward(t) + portForwardBackoff = 50 * time.Millisecond + maxPortForwardBackoff = time.Second + + var times []time.Time + forwardPortsFn = func(_ context.Context, _ *client, _ string, _ []PortRule) error { + times = append(times, time.Now()) + if len(times) < 3 { + return errors.New("lost connection to pod") + } + return nil + } + + require.NoError(t, portForward(context.Background(), &client{}, map[string]string{"app": "web"}, []PortRule{{Local: 3000, Remote: 3000}})) + require.Len(t, times, 3) + assert.GreaterOrEqual(t, times[1].Sub(times[0]), 50*time.Millisecond) + assert.GreaterOrEqual(t, times[2].Sub(times[1]), 100*time.Millisecond) +} + +func TestPortForward_CancelDuringBackoffReturns(t *testing.T) { + stubPortForward(t) + portForwardBackoff = time.Hour + ctx, cancel := context.WithCancel(context.Background()) + forwardPortsFn = func(_ context.Context, _ *client, _ string, _ []PortRule) error { + time.AfterFunc(20*time.Millisecond, cancel) + return errors.New("lost connection to pod") + } + + done := make(chan error, 1) + go func() { + done <- portForward(ctx, &client{}, map[string]string{"app": "web"}, []PortRule{{Local: 3000, Remote: 3000}}) + }() + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(2 * time.Second): + t.Fatal("portForward did not return after cancel during backoff") + } +} + +// Every failed attempt leaked two goroutines: one waiting for a ready signal +// that never comes, one waiting for ctx to close the stop channel. +func TestForwardPorts_DoesNotLeakGoroutinesOnFailedDial(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + // client-go does not close the connection of a refused upgrade; + // close it server-side so only our goroutines are counted. + w.Header().Set("Connection", "close") + http.Error(w, "upgrade refused", http.StatusBadRequest) + })) + defer srv.Close() + cfg := &rest.Config{Host: srv.URL} + core, err := corev1client.NewForConfig(cfg) + require.NoError(t, err) + c := &client{Config: cfg, CoreV1: core, Namespace: "ns"} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ports := []PortRule{{Local: 18080, Remote: 80}} + require.Error(t, forwardPorts(ctx, c, "pod-1", ports)) // warm up transport goroutines + + before := runtime.NumGoroutine() + for i := 0; i < 20; i++ { + require.Error(t, forwardPorts(ctx, c, "pod-1", ports)) + } + if !assert.Eventually(t, func() bool { return runtime.NumGoroutine() <= before+3 }, 2*time.Second, 20*time.Millisecond, + "goroutines leaked: before=%d now=%d", before, runtime.NumGoroutine()) { + buf := make([]byte, 1<<20) + t.Logf("%s", buf[:runtime.Stack(buf, true)]) + } +} + +func TestLineLogger_LogsEachLine(t *testing.T) { + var buf bytes.Buffer + orig := log.Writer() + log.SetOutput(&buf) + t.Cleanup(func() { log.SetOutput(orig) }) + + input := []byte("Unable to listen on port 8080: in use\nsecond\n") + n, err := (&lineLogger{prefix: "[pf]"}).Write(input) + require.NoError(t, err) + assert.Equal(t, len(input), n) + assert.Contains(t, buf.String(), "[pf] Unable to listen on port 8080: in use\n") + assert.Contains(t, buf.String(), "[pf] second\n") +} + +// A refused upgrade because of RBAC cannot be fixed by reconnecting (and +// client-go leaks the connection of every refused upgrade). +func TestPortForward_ForbiddenIsFatal(t *testing.T) { + stubPortForward(t) + calls := 0 + forwardPortsFn = func(_ context.Context, _ *client, pod string, _ []PortRule) error { + calls++ + return fmt.Errorf("forwarding ports for pod %s: error upgrading connection: pods %q is forbidden: User "+ + "\"dev\" cannot create resource \"pods/portforward\" in API group \"\" in the namespace \"ns\"", pod, pod) + } + + err := portForward(context.Background(), &client{}, map[string]string{"app": "web"}, []PortRule{{Local: 8080, Remote: 80}}) + require.Error(t, err) + assert.Contains(t, err.Error(), "forbidden") + assert.Equal(t, 1, calls) +} diff --git a/pkg/k8s/prune_test.go b/pkg/k8s/prune_test.go index f174950..30fb146 100644 --- a/pkg/k8s/prune_test.go +++ b/pkg/k8s/prune_test.go @@ -9,7 +9,7 @@ import ( func TestComputeOrphaned_EmptyOldRefs(t *testing.T) { orphaned := computeOrphaned(nil, []ResourceRef{ {APIVersion: "v1", Kind: "ConfigMap", Namespace: "prod", Name: "cfg"}, - }) + }, "prod") assert.Empty(t, orphaned) } @@ -24,7 +24,7 @@ func TestComputeOrphaned_NoOrphans(t *testing.T) { {APIVersion: "v1", Kind: "ConfigMap", Namespace: "prod", Name: "cfg"}, } - orphaned := computeOrphaned(oldRefs, newRefs) + orphaned := computeOrphaned(oldRefs, newRefs, "prod") assert.Empty(t, orphaned) } @@ -38,7 +38,7 @@ func TestComputeOrphaned_ReturnsRemovedResources(t *testing.T) { {APIVersion: "apps/v1", Kind: "Deployment", Namespace: "prod", Name: "web"}, } - orphaned := computeOrphaned(oldRefs, newRefs) + orphaned := computeOrphaned(oldRefs, newRefs, "prod") assert.Equal(t, []ResourceRef{ {APIVersion: "v1", Kind: "Service", Namespace: "prod", Name: "web-svc"}, {APIVersion: "v1", Kind: "ConfigMap", Namespace: "prod", Name: "cfg"}, @@ -54,7 +54,7 @@ func TestComputeOrphaned_SupportsClusterScopedResources(t *testing.T) { {APIVersion: "v1", Kind: "ConfigMap", Namespace: "prod", Name: "cfg"}, } - orphaned := computeOrphaned(oldRefs, newRefs) + orphaned := computeOrphaned(oldRefs, newRefs, "prod") assert.Equal(t, []ResourceRef{ {APIVersion: "v1", Kind: "Namespace", Name: "prod"}, }, orphaned) @@ -66,8 +66,33 @@ func TestComputeOrphaned_DeduplicatesOldRefs(t *testing.T) { {APIVersion: "v1", Kind: "ConfigMap", Namespace: "prod", Name: "cfg"}, } - orphaned := computeOrphaned(oldRefs, nil) + orphaned := computeOrphaned(oldRefs, nil, "prod") assert.Equal(t, []ResourceRef{ {APIVersion: "v1", Kind: "ConfigMap", Namespace: "prod", Name: "cfg"}, }, orphaned) } + +func TestComputeOrphaned_SameObjectUnderAnotherVersionOrDefaultedNamespace(t *testing.T) { + oldRefs := []ResourceRef{ + {APIVersion: "autoscaling/v1", Kind: "HorizontalPodAutoscaler", Namespace: "prod", Name: "web"}, + {APIVersion: "v1", Kind: "ConfigMap", Name: "cfg"}, + {APIVersion: "rbac.authorization.k8s.io/v1", Kind: "ClusterRole", Namespace: "prod", Name: "reader"}, + {APIVersion: "v1", Kind: "ConfigMap", Name: "gone"}, + } + newRefs := []ResourceRef{ + {APIVersion: "autoscaling/v2", Kind: "HorizontalPodAutoscaler", Namespace: "prod", Name: "web"}, + {APIVersion: "v1", Kind: "ConfigMap", Namespace: "prod", Name: "cfg"}, + {APIVersion: "rbac.authorization.k8s.io/v1", Kind: "ClusterRole", Name: "reader"}, + } + + orphaned := computeOrphaned(oldRefs, newRefs, "prod") + + assert.Equal(t, []ResourceRef{{APIVersion: "v1", Kind: "ConfigMap", Name: "gone"}}, orphaned) +} + +func TestComputeOrphaned_DifferentNamespacesStayDistinct(t *testing.T) { + oldRefs := []ResourceRef{{APIVersion: "v1", Kind: "ConfigMap", Namespace: "staging", Name: "cfg"}} + newRefs := []ResourceRef{{APIVersion: "v1", Kind: "ConfigMap", Namespace: "prod", Name: "cfg"}} + + assert.Equal(t, oldRefs, computeOrphaned(oldRefs, newRefs, "prod")) +} diff --git a/pkg/k8s/release.go b/pkg/k8s/release.go index cf37b91..96b779d 100644 --- a/pkg/k8s/release.go +++ b/pkg/k8s/release.go @@ -7,7 +7,9 @@ import ( "fmt" "log" "sort" + "strings" + "github.com/cloudticon/ct/pkg/manifest" "github.com/fatih/color" corev1 "k8s.io/api/core/v1" @@ -23,11 +25,11 @@ import ( // and require cross-file lookups during reads. const ( - managedByLabelKey = "app.kubernetes.io/managed-by" - managedByLabelVal = "ct" - instanceLabelKey = "ct.cloudticon.com/instance" - inventoryDataKey = "resources" - inventoryCMPrefix = "ct-inventory-" + managedByLabelKey = "app.kubernetes.io/managed-by" + managedByLabelVal = "ct" + instanceLabelKey = "ct.cloudticon.com/instance" + inventoryDataKey = "resources" + inventoryCMPrefix = "ct-inventory-" ) // ReleaseInfo summarizes a release tracked in inventory. @@ -50,7 +52,21 @@ func (c *client) applyRelease(ctx context.Context, namespace, releaseName string return fmt.Errorf("building resource refs: %w", err) } - orphaned := computeOrphaned(oldRefs, newRefs) + defaultNs := namespace + if defaultNs == "" { + defaultNs = c.Namespace + } + orphaned := computeOrphaned(oldRefs, newRefs, defaultNs) + + // Track old+new before touching the cluster: if apply fails halfway, the + // objects it already created stay in the inventory and a later run can + // still prune them. A first install skips this, because the release may + // create the namespace the inventory lives in. + if added := computeOrphaned(newRefs, oldRefs, defaultNs); len(added) > 0 && len(oldRefs) > 0 { + if err := saveInventoryRefs(ctx, c, namespace, releaseName, append(append([]ResourceRef{}, oldRefs...), added...)); err != nil { + return fmt.Errorf("saving inventory: %w", err) + } + } if err := c.apply(ctx, resources); err != nil { return fmt.Errorf("applying resources: %w", err) @@ -106,6 +122,14 @@ func ensureNamespace(ctx context.Context, c *client, namespace string) error { // --- Inventory CRUD --- func saveInventory(ctx context.Context, c *client, namespace, releaseName string, resources []Resource) error { + refs, err := resourcesToRefs(resources) + if err != nil { + return err + } + return saveInventoryRefs(ctx, c, namespace, releaseName, refs) +} + +func saveInventoryRefs(ctx context.Context, c *client, namespace, releaseName string, refs []ResourceRef) error { if c == nil || c.CoreV1 == nil { return errors.New("k8s client is required") } @@ -118,11 +142,6 @@ func saveInventory(ctx context.Context, c *client, namespace, releaseName string return err } - refs, err := resourcesToRefs(resources) - if err != nil { - return err - } - refsJSON, err := json.Marshal(refs) if err != nil { return fmt.Errorf("marshaling inventory refs: %w", err) @@ -244,8 +263,10 @@ func listReleases(ctx context.Context, c *client, namespace string, allNamespace releases := make([]ReleaseInfo, 0, len(cmList.Items)) for _, cm := range cmList.Items { + // ConfigMaps a release renders carry the same labels as its + // inventory; only ct-inventory-* ones are inventories. releaseName := cm.Labels[instanceLabelKey] - if releaseName == "" { + if releaseName == "" || !strings.HasPrefix(cm.Name, inventoryCMPrefix) { continue } @@ -325,21 +346,24 @@ func resourcesToRefs(resources []Resource) ([]ResourceRef, error) { // --- Prune (orphan detection) --- // computeOrphaned returns refs that existed before but are no longer present. -// Comparison key is apiVersion+kind+namespace+name. -func computeOrphaned(oldRefs, newRefs []ResourceRef) []ResourceRef { +// Refs are compared by server-side identity: API group (not version), kind, +// namespace (an empty one means defaultNamespace) and name. Comparing raw +// apiVersions and namespaces pruned the object just applied when an HPA +// moved from autoscaling/v1 to v2 or a release gained an explicit -n. +func computeOrphaned(oldRefs, newRefs []ResourceRef, defaultNamespace string) []ResourceRef { if len(oldRefs) == 0 { return []ResourceRef{} } newSet := make(map[string]struct{}, len(newRefs)) for _, ref := range newRefs { - newSet[resourceRefKey(ref)] = struct{}{} + newSet[resourceRefKey(ref, defaultNamespace)] = struct{}{} } orphaned := make([]ResourceRef, 0) seen := make(map[string]struct{}, len(oldRefs)) for _, ref := range oldRefs { - key := resourceRefKey(ref) + key := resourceRefKey(ref, defaultNamespace) if _, alreadyAdded := seen[key]; alreadyAdded { continue } @@ -353,8 +377,15 @@ func computeOrphaned(oldRefs, newRefs []ResourceRef) []ResourceRef { return orphaned } -func resourceRefKey(ref ResourceRef) string { - return fmt.Sprintf("%s|%s|%s|%s", ref.APIVersion, ref.Kind, ref.Namespace, ref.Name) +func resourceRefKey(ref ResourceRef, defaultNamespace string) string { + ns := ref.Namespace + switch { + case manifest.IsClusterScoped(ref.APIVersion, ref.Kind): + ns = "" + case ns == "": + ns = defaultNamespace + } + return fmt.Sprintf("%s|%s|%s|%s", manifest.Group(ref.APIVersion), ref.Kind, ns, ref.Name) } // --- Label injection --- diff --git a/pkg/k8s/release_test.go b/pkg/k8s/release_test.go index a1e92a2..a2877b2 100644 --- a/pkg/k8s/release_test.go +++ b/pkg/k8s/release_test.go @@ -253,3 +253,54 @@ func TestApplyRelease_EmptyResources(t *testing.T) { err := c.applyRelease(context.Background(), "test-ns", "my-release", []Resource{}) require.NoError(t, err) } + +func TestApplyRelease_FailedApplyKeepsNewObjectsTracked(t *testing.T) { + c, dynClient := newReleaseTestClient(t) + c.Namespace = "test-ns" + seedInventory(t, c, "test-ns", "my-release", []ResourceRef{ + {APIVersion: "v1", Kind: "ConfigMap", Name: "cfg", Namespace: "test-ns"}, + }) + // The ConfigMap applies, the Deployment (applied after it) fails. + dynClient.PrependReactor("patch", "deployments", func(action k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, errors.New("apply boom") + }) + + resources := []Resource{ + {"apiVersion": "apps/v1", "kind": "Deployment", "metadata": map[string]interface{}{"name": "web", "namespace": "test-ns"}}, + {"apiVersion": "v1", "kind": "Service", "metadata": map[string]interface{}{"name": "web", "namespace": "test-ns"}}, + {"apiVersion": "v1", "kind": "ConfigMap", "metadata": map[string]interface{}{"name": "cfg", "namespace": "test-ns"}}, + } + + err := c.applyRelease(context.Background(), "test-ns", "my-release", resources) + require.Error(t, err) + + refs, err := loadInventory(context.Background(), c, "test-ns", "my-release") + require.NoError(t, err) + assert.ElementsMatch(t, []ResourceRef{ + {APIVersion: "v1", Kind: "ConfigMap", Name: "cfg", Namespace: "test-ns"}, + {APIVersion: "apps/v1", Kind: "Deployment", Name: "web", Namespace: "test-ns"}, + {APIVersion: "v1", Kind: "Service", Name: "web", Namespace: "test-ns"}, + }, refs, "the Service was created before the failure and must stay prunable") +} + +func TestApplyRelease_PrunesObjectsFromAFailedRun(t *testing.T) { + c, dynClient := newReleaseTestClient(t) + c.Namespace = "test-ns" + seedInventory(t, c, "test-ns", "my-release", []ResourceRef{ + {APIVersion: "v1", Kind: "ConfigMap", Name: "cfg", Namespace: "test-ns"}, + {APIVersion: "v1", Kind: "Service", Name: "leftover", Namespace: "test-ns"}, + }) + + resources := []Resource{ + {"apiVersion": "v1", "kind": "ConfigMap", "metadata": map[string]interface{}{"name": "cfg", "namespace": "test-ns"}}, + } + require.NoError(t, c.applyRelease(context.Background(), "test-ns", "my-release", resources)) + + var deleted []string + for _, a := range dynClient.Actions() { + if d, ok := a.(k8stesting.DeleteAction); ok { + deleted = append(deleted, d.GetName()) + } + } + assert.Equal(t, []string{"leftover"}, deleted) +} diff --git a/pkg/manifest/manifest.go b/pkg/manifest/manifest.go new file mode 100644 index 0000000..aebab5c --- /dev/null +++ b/pkg/manifest/manifest.go @@ -0,0 +1,305 @@ +// Package manifest holds pure transformations on rendered Kubernetes objects: +// cleaning, namespace defaulting, scope detection, ordering and duplicate +// detection. Nothing here talks to a cluster, so everything is unit-testable +// and shared by `ct template`, `ct apply` and `ct dev`. +package manifest + +import ( + "fmt" + "sort" + "strings" +) + +// Resource is a rendered Kubernetes object. +type Resource = map[string]interface{} + +// ScopeMarker is the property factory libraries set on cluster-scoped objects +// (`__ctts_scope: "cluster"`). It is stripped before output. +const ScopeMarker = "__ctts_scope" + +// Clean removes null and undefined values in place, the way JSON.stringify +// drops undefined: keys holding null/undefined go away, and so do null items +// in arrays. Everything else stays as written, including empty objects and +// arrays, because they can carry meaning: `emptyDir: {}`, a NetworkPolicy +// `ingress: [{}]` (allow all), `egress: [{ to: undefined }]`, a PDB +// `selector: {}`, a CRD `default: []`. +func Clean(obj map[string]interface{}) { + for k, v := range obj { + if v == nil { + delete(obj, k) + continue + } + obj[k] = cleanValue(v) + } +} + +func cleanValue(v interface{}) interface{} { + switch val := v.(type) { + case map[string]interface{}: + Clean(val) + return val + case []interface{}: + cleaned := make([]interface{}, 0, len(val)) + for _, item := range val { + if item != nil { + cleaned = append(cleaned, cleanValue(item)) + } + } + return cleaned + default: + return v + } +} + +// Group returns the API group of an apiVersion ("apps/v1" -> "apps", +// "v1" -> ""). The non-canonical "core/v1" is treated as the core group. +func Group(apiVersion string) string { + group, _, found := strings.Cut(apiVersion, "/") + if !found || group == "core" { + return "" + } + return group +} + +// IsClusterScoped reports whether apiVersion/kind is a well-known +// cluster-scoped type. Factory libraries should mark their own cluster-scoped +// kinds with ScopeMarker; this list is the safety net for hand-built objects. +func IsClusterScoped(apiVersion, kind string) bool { + _, ok := clusterScopedKinds[Group(apiVersion)+"/"+kind] + return ok +} + +var clusterScopedKinds = setOf( + "/Namespace", "/Node", "/PersistentVolume", "/ComponentStatus", + "rbac.authorization.k8s.io/ClusterRole", + "rbac.authorization.k8s.io/ClusterRoleBinding", + "apiextensions.k8s.io/CustomResourceDefinition", + "apiregistration.k8s.io/APIService", + "admissionregistration.k8s.io/MutatingWebhookConfiguration", + "admissionregistration.k8s.io/ValidatingWebhookConfiguration", + "admissionregistration.k8s.io/ValidatingAdmissionPolicy", + "admissionregistration.k8s.io/ValidatingAdmissionPolicyBinding", + "admissionregistration.k8s.io/MutatingAdmissionPolicy", + "admissionregistration.k8s.io/MutatingAdmissionPolicyBinding", + "storage.k8s.io/StorageClass", + "storage.k8s.io/CSIDriver", + "storage.k8s.io/CSINode", + "storage.k8s.io/VolumeAttachment", + "storage.k8s.io/VolumeAttributesClass", + "scheduling.k8s.io/PriorityClass", + "node.k8s.io/RuntimeClass", + "networking.k8s.io/IngressClass", + "networking.k8s.io/IPAddress", + "networking.k8s.io/ServiceCIDR", + "certificates.k8s.io/CertificateSigningRequest", + "certificates.k8s.io/ClusterTrustBundle", + "flowcontrol.apiserver.k8s.io/FlowSchema", + "flowcontrol.apiserver.k8s.io/PriorityLevelConfiguration", + "resource.k8s.io/DeviceClass", + "resource.k8s.io/ResourceSlice", + "policy/PodSecurityPolicy", + // Widely used CRDs. + "cert-manager.io/ClusterIssuer", + "external-secrets.io/ClusterSecretStore", + "external-secrets.io/ClusterExternalSecret", + "gateway.networking.k8s.io/GatewayClass", + "snapshot.storage.k8s.io/VolumeSnapshotClass", + "snapshot.storage.k8s.io/VolumeSnapshotContent", + "kyverno.io/ClusterPolicy", + "kyverno.io/ClusterCleanupPolicy", + "argoproj.io/ClusterWorkflowTemplate", + "karpenter.sh/NodePool", + "karpenter.k8s.aws/EC2NodeClass", + "cilium.io/CiliumClusterwideNetworkPolicy", +) + +func setOf(keys ...string) map[string]struct{} { + set := make(map[string]struct{}, len(keys)) + for _, k := range keys { + set[k] = struct{}{} + } + return set +} + +// Normalize strips the scope marker, cleans null values and sets +// metadata.namespace to namespace on namespaced objects that don't have one. +// An empty namespace leaves namespaces untouched. +func Normalize(resources []Resource, namespace string) { + for _, res := range resources { + scope, _ := res[ScopeMarker].(string) + delete(res, ScopeMarker) + Clean(res) + + if namespace == "" || scope == "cluster" { + continue + } + apiVersion, _ := res["apiVersion"].(string) + kind, _ := res["kind"].(string) + if IsClusterScoped(apiVersion, kind) { + continue + } + meta, ok := res["metadata"].(map[string]interface{}) + if !ok { + continue + } + if ns, _ := meta["namespace"].(string); ns == "" { + meta["namespace"] = namespace + } + } +} + +// Ref names an object for messages: `Deployment "web"` or +// `Deployment "web" (namespace "prod")`. +func Ref(res Resource) string { + kind, _ := res["kind"].(string) + meta, _ := res["metadata"].(map[string]interface{}) + name, _ := meta["name"].(string) + ns, _ := meta["namespace"].(string) + if kind == "" { + kind = "" + } + if ns == "" { + return fmt.Sprintf("%s %q", kind, name) + } + return fmt.Sprintf("%s %q (namespace %q)", kind, name, ns) +} + +// identity is the server-side identity of an object. The version is left +// out on purpose: apps/v1 and apps/v1beta1 Deployments with the same name are +// the same object. +func identity(res Resource) string { + apiVersion, _ := res["apiVersion"].(string) + kind, _ := res["kind"].(string) + meta, _ := res["metadata"].(map[string]interface{}) + name, _ := meta["name"].(string) + ns, _ := meta["namespace"].(string) + if IsClusterScoped(apiVersion, kind) { + ns = "" + } + return Group(apiVersion) + "|" + kind + "|" + ns + "|" + name +} + +// Duplicate describes an object registered more than once. Indexes point +// into the rendered resource list (registration order). +type Duplicate struct { + Ref string + Indexes []int +} + +// FindDuplicates returns objects registered more than once, in order of first +// registration. Applying such a list silently keeps only the last copy. +func FindDuplicates(resources []Resource) []Duplicate { + first := make(map[string]int, len(resources)) + dupAt := map[string]int{} + var dups []Duplicate + for i, res := range resources { + meta, _ := res["metadata"].(map[string]interface{}) + if name, _ := meta["name"].(string); name == "" { + continue // nameless objects (generateName) are reported by validation + } + key := identity(res) + f, ok := first[key] + if !ok { + first[key] = i + continue + } + if d, ok := dupAt[key]; ok { + dups[d].Indexes = append(dups[d].Indexes, i) + continue + } + dupAt[key] = len(dups) + dups = append(dups, Duplicate{Ref: Ref(resources[f]), Indexes: []int{f, i}}) + } + return dups +} + +// installOrder mirrors Helm's install order so ct and Helm apply a release in +// the same sequence: namespaces and CRDs before the objects that need them. +var installOrder = []string{ + "PriorityClass", + "Namespace", + "NetworkPolicy", + "ResourceQuota", + "LimitRange", + "PodSecurityPolicy", + "PodDisruptionBudget", + "ServiceAccount", + "Secret", + "SecretList", + "ConfigMap", + "StorageClass", + "PersistentVolume", + "PersistentVolumeClaim", + "CustomResourceDefinition", + "ClusterRole", + "ClusterRoleList", + "ClusterRoleBinding", + "ClusterRoleBindingList", + "Role", + "RoleList", + "RoleBinding", + "RoleBindingList", + "Service", + "DaemonSet", + "Pod", + "ReplicationController", + "ReplicaSet", + "Deployment", + "HorizontalPodAutoscaler", + "StatefulSet", + "Job", + "CronJob", + "IngressClass", + "Ingress", + "APIService", + "MutatingWebhookConfiguration", + "ValidatingWebhookConfiguration", +} + +var installRank = func() map[string]int { + rank := make(map[string]int, len(installOrder)) + for i, kind := range installOrder { + rank[kind] = i + } + return rank +}() + +// InstallRank is an object's position in Helm's install order; false for +// kinds Helm doesn't know. Only Kubernetes' own API groups count, so a custom +// resource that reuses a built-in kind name (Calico's NetworkPolicy) is +// treated as a custom resource and still goes after its CRD. +func InstallRank(apiVersion, kind string) (int, bool) { + if !isKubernetesGroup(Group(apiVersion)) { + return 0, false + } + rank, ok := installRank[kind] + return rank, ok +} + +// isKubernetesGroup reports API groups defined by Kubernetes itself: the +// core group, dotless groups (apps, batch, policy, ...) and *.k8s.io. +func isKubernetesGroup(group string) bool { + return group == "" || !strings.Contains(group, ".") || strings.HasSuffix(group, ".k8s.io") +} + +// SortForApply orders resources the way Helm installs them. Kinds Helm +// doesn't know (custom resources) go last, alphabetically by kind. Objects of +// the same kind keep their registration order. +func SortForApply(resources []Resource) { + sort.SliceStable(resources, func(i, j int) bool { + ai, _ := resources[i]["apiVersion"].(string) + aj, _ := resources[j]["apiVersion"].(string) + ki, _ := resources[i]["kind"].(string) + kj, _ := resources[j]["kind"].(string) + ri, iok := InstallRank(ai, ki) + rj, jok := InstallRank(aj, kj) + switch { + case iok && jok: + return ri < rj + case iok != jok: + return iok + default: + return ki < kj + } + }) +} diff --git a/pkg/manifest/manifest_test.go b/pkg/manifest/manifest_test.go new file mode 100644 index 0000000..426bfd1 --- /dev/null +++ b/pkg/manifest/manifest_test.go @@ -0,0 +1,218 @@ +package manifest_test + +import ( + "testing" + + "github.com/cloudticon/ct/pkg/manifest" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func obj(apiVersion, kind, name, namespace string) manifest.Resource { + meta := map[string]interface{}{"name": name} + if namespace != "" { + meta["namespace"] = namespace + } + return manifest.Resource{"apiVersion": apiVersion, "kind": kind, "metadata": meta} +} + +func kinds(resources []manifest.Resource) []string { + out := make([]string, len(resources)) + for i, r := range resources { + out[i] = r["kind"].(string) + } + return out +} + +func TestClean_KeepsAuthoredEmptyObjects(t *testing.T) { + res := manifest.Resource{ + "spec": map[string]interface{}{ + "volumes": []interface{}{ + map[string]interface{}{"name": "tmp", "emptyDir": map[string]interface{}{}}, + }, + "podSelector": map[string]interface{}{}, + }, + } + + manifest.Clean(res) + + spec := res["spec"].(map[string]interface{}) + assert.Equal(t, map[string]interface{}{}, spec["podSelector"]) + vol := spec["volumes"].([]interface{})[0].(map[string]interface{}) + assert.Equal(t, map[string]interface{}{}, vol["emptyDir"]) +} + +func TestClean_KeepsEmptyObjectsInsideArrays(t *testing.T) { + // NetworkPolicy `ingress: [{}]` allows all traffic; dropping the {} would + // flip it to deny-all. + res := manifest.Resource{ + "spec": map[string]interface{}{ + "ingress": []interface{}{map[string]interface{}{}}, + }, + } + + manifest.Clean(res) + + assert.Equal(t, []interface{}{map[string]interface{}{}}, res["spec"].(map[string]interface{})["ingress"]) +} + +func TestClean_DropsOnlyNullsLikeJSONStringify(t *testing.T) { + res := manifest.Resource{ + "metadata": map[string]interface{}{"name": "x", "labels": nil}, + "spec": map[string]interface{}{ + "selector": map[string]interface{}{"app": nil}, + "args": []interface{}{nil, "a"}, + "egress": []interface{}{map[string]interface{}{"to": nil}}, + "ports": []interface{}{}, + "replicas": int64(0), + "paused": false, + "name": "", + }, + } + + manifest.Clean(res) + + assert.Equal(t, map[string]interface{}{"name": "x"}, res["metadata"]) + assert.Equal(t, map[string]interface{}{ + "selector": map[string]interface{}{}, + "args": []interface{}{"a"}, + // JSON.stringify keeps {} for { to: undefined }: allow-all egress + // must not turn into deny-all. + "egress": []interface{}{map[string]interface{}{}}, + "ports": []interface{}{}, + "replicas": int64(0), + "paused": false, + "name": "", + }, res["spec"]) +} + +func TestNormalize_DefaultsNamespaceOnlyOnNamespacedObjects(t *testing.T) { + marked := obj("example.com/v1", "Thing", "marked", "") + marked[manifest.ScopeMarker] = "cluster" + resources := []manifest.Resource{ + obj("v1", "ConfigMap", "cfg", ""), + obj("v1", "Namespace", "team", ""), + obj("rbac.authorization.k8s.io/v1", "ClusterRole", "reader", ""), + obj("core/v1", "Namespace", "legacy", ""), + obj("apps/v1", "Deployment", "pinned", "other"), + marked, + } + + manifest.Normalize(resources, "prod") + + ns := func(i int) interface{} { return resources[i]["metadata"].(map[string]interface{})["namespace"] } + assert.Equal(t, "prod", ns(0)) + assert.Nil(t, ns(1), "Namespace is cluster-scoped") + assert.Nil(t, ns(2), "ClusterRole is cluster-scoped") + assert.Nil(t, ns(3), "core/v1 is still the core group") + assert.Equal(t, "other", ns(4), "explicit namespace wins") + assert.Nil(t, ns(5), "scope marker wins") + assert.NotContains(t, resources[5], manifest.ScopeMarker) +} + +func TestNormalize_NoNamespaceLeavesObjectsAlone(t *testing.T) { + resources := []manifest.Resource{obj("v1", "ConfigMap", "cfg", "")} + + manifest.Normalize(resources, "") + + assert.NotContains(t, resources[0]["metadata"], "namespace") +} + +func TestGroup(t *testing.T) { + assert.Equal(t, "", manifest.Group("v1")) + assert.Equal(t, "", manifest.Group("core/v1")) + assert.Equal(t, "apps", manifest.Group("apps/v1")) + assert.Equal(t, "cert-manager.io", manifest.Group("cert-manager.io/v1")) +} + +func TestFindDuplicates(t *testing.T) { + resources := []manifest.Resource{ + obj("apps/v1", "Deployment", "web", "prod"), + obj("v1", "Service", "web", "prod"), + obj("apps/v1beta1", "Deployment", "web", "prod"), + obj("apps/v1", "Deployment", "web", "staging"), + obj("apps/v1", "Deployment", "web", "prod"), + obj("v1", "Namespace", "prod", ""), + obj("v1", "Namespace", "prod", "ignored-for-cluster-scope"), + } + + dups := manifest.FindDuplicates(resources) + + require.Len(t, dups, 2) + assert.Equal(t, `Deployment "web" (namespace "prod")`, dups[0].Ref) + assert.Equal(t, []int{0, 2, 4}, dups[0].Indexes) + assert.Equal(t, `Namespace "prod"`, dups[1].Ref) + assert.Equal(t, []int{5, 6}, dups[1].Indexes) +} + +func TestFindDuplicates_None(t *testing.T) { + assert.Empty(t, manifest.FindDuplicates([]manifest.Resource{ + obj("v1", "ConfigMap", "a", ""), + obj("v1", "ConfigMap", "b", ""), + })) +} + +func TestSortForApply_FollowsHelmInstallOrder(t *testing.T) { + resources := []manifest.Resource{ + obj("networking.k8s.io/v1", "Ingress", "web", ""), + obj("apps/v1", "Deployment", "web", ""), + obj("example.com/v1", "Widget", "w", ""), + obj("v1", "Service", "web", ""), + obj("example.com/v1", "Gadget", "g", ""), + obj("apiextensions.k8s.io/v1", "CustomResourceDefinition", "widgets.example.com", ""), + obj("v1", "ConfigMap", "second", ""), + obj("v1", "Namespace", "team", ""), + obj("v1", "ConfigMap", "first", ""), + } + resources[8]["metadata"].(map[string]interface{})["name"] = "third" + + manifest.SortForApply(resources) + + assert.Equal(t, []string{ + "Namespace", "ConfigMap", "ConfigMap", "CustomResourceDefinition", + "Service", "Deployment", "Ingress", "Gadget", "Widget", + }, kinds(resources)) + assert.Equal(t, "second", resources[1]["metadata"].(map[string]interface{})["name"], "same kind keeps registration order") + assert.Equal(t, "third", resources[2]["metadata"].(map[string]interface{})["name"]) +} + +func TestFindDuplicates_IgnoresNamelessObjects(t *testing.T) { + a := obj("batch/v1", "Job", "", "prod") + a["metadata"].(map[string]interface{})["generateName"] = "migrate-" + b := obj("batch/v1", "Job", "", "prod") + b["metadata"].(map[string]interface{})["generateName"] = "seed-" + + assert.Empty(t, manifest.FindDuplicates([]manifest.Resource{a, b})) +} + +func TestSortForApply_CustomResourceWithBuiltinKindNameIsACustomResource(t *testing.T) { + resources := []manifest.Resource{ + obj("crd.projectcalico.org/v1", "NetworkPolicy", "calico", ""), + obj("apiextensions.k8s.io/v1", "CustomResourceDefinition", "networkpolicies.crd.projectcalico.org", ""), + obj("networking.k8s.io/v1", "NetworkPolicy", "k8s", ""), + } + + manifest.SortForApply(resources) + + var names []string + for _, r := range resources { + names = append(names, r["metadata"].(map[string]interface{})["name"].(string)) + } + assert.Equal(t, []string{"k8s", "networkpolicies.crd.projectcalico.org", "calico"}, names) +} + +func TestInstallRank(t *testing.T) { + for _, tc := range []struct { + apiVersion, kind string + known bool + }{ + {"v1", "Namespace", true}, + {"apps/v1", "Deployment", true}, + {"networking.k8s.io/v1", "Ingress", true}, + {"crd.projectcalico.org/v1", "NetworkPolicy", false}, + {"example.com/v1", "Widget", false}, + } { + _, ok := manifest.InstallRank(tc.apiVersion, tc.kind) + assert.Equal(t, tc.known, ok, "%s %s", tc.apiVersion, tc.kind) + } +} diff --git a/pkg/packages/git_test.go b/pkg/packages/git_test.go index abaac43..16cf5db 100644 --- a/pkg/packages/git_test.go +++ b/pkg/packages/git_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/cloudticon/ctts/pkg/packages" + "github.com/cloudticon/ct/pkg/packages" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/packages/resolver.go b/pkg/packages/resolver.go index 303fe8e..5f491a5 100644 --- a/pkg/packages/resolver.go +++ b/pkg/packages/resolver.go @@ -5,6 +5,8 @@ import ( "os" "regexp" "strings" + + "github.com/cloudticon/ct/pkg/cache" ) func IsURLImport(importPath string) bool { @@ -48,6 +50,14 @@ func IsGitPackage(importPath string) bool { func SplitPackagePath(importPath string) (pkgName, subPath string) { parts := strings.Split(importPath, "/") n := packageSegmentCount(parts[0]) + // A version marks where the package ends, which also covers hosts with + // nested groups: "git.example.com/group/team/repo@v1/lib". + for i := 1; i < len(parts); i++ { + if strings.Contains(parts[i], "@") { + n = i + 1 + break + } + } if len(parts) <= n { return importPath, "" } @@ -59,16 +69,32 @@ func SplitPackageVersion(pkgName string) (pkg, version string) { return } +// ImportURL maps an import path to the package URL the cache understands: +// "github.com/o/r@v1/sub" and "https://github.com/o/r@v1" both become +// "https://github.com/o/r@v1". Relative and bare imports return false. +func ImportURL(importPath string) (string, bool) { + if IsURLImport(importPath) { + return importPath, true + } + if !IsGitPackage(importPath) { + return "", false + } + pkgWithVersion, _ := SplitPackagePath(importPath) + pkg, version := SplitPackageVersion(pkgWithVersion) + url := "https://" + pkg + if version != "" { + url += "@" + version + } + return url, true +} + func PackageToGitURL(pkgName string) string { return "https://" + pkgName + ".git" } func packageSegmentCount(domain string) int { - wellKnown := [...]string{"github.com", "gitlab.com", "bitbucket.org"} - for _, h := range wellKnown { - if domain == h { - return 3 - } + if cache.IsWellKnownHost(domain) { + return 3 } return 2 } diff --git a/pkg/packages/resolver_test.go b/pkg/packages/resolver_test.go index e3fb621..0bad9ae 100644 --- a/pkg/packages/resolver_test.go +++ b/pkg/packages/resolver_test.go @@ -5,7 +5,7 @@ import ( "path/filepath" "testing" - "github.com/cloudticon/ctts/pkg/packages" + "github.com/cloudticon/ct/pkg/packages" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/packages/sync.go b/pkg/packages/sync.go index 662813d..2bb52ba 100644 --- a/pkg/packages/sync.go +++ b/pkg/packages/sync.go @@ -7,7 +7,7 @@ import ( "path/filepath" "strings" - "github.com/cloudticon/ctts/pkg/cache" + "github.com/cloudticon/ct/pkg/cache" ) func SyncPackages(projectDir string) error { @@ -31,17 +31,18 @@ func syncImports(filePath string, visited map[string]bool) error { } for _, imp := range imports { - if !IsURLImport(imp.Path) { + url, ok := ImportURL(imp.Path) + if !ok { continue } - pkgDir, err := cache.Resolve(imp.Path) + pkgDir, err := cache.Resolve(url) if err != nil { return fmt.Errorf("resolving %s: %w", imp.Path, err) } - tsFiles, _ := collectTSFiles(pkgDir) - for _, f := range tsFiles { + sourceFiles, _ := collectSourceFiles(pkgDir) + for _, f := range sourceFiles { if err := syncImports(f, visited); err != nil { return err } @@ -51,13 +52,14 @@ func syncImports(filePath string, visited map[string]bool) error { return nil } -func collectTSFiles(dir string) ([]string, error) { +// collectSourceFiles lists the .ts and .ct files of a package. +func collectSourceFiles(dir string) ([]string, error) { var files []string err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error { if err != nil { return err } - if !d.IsDir() && strings.HasSuffix(path, ".ts") { + if !d.IsDir() && (strings.HasSuffix(path, ".ts") || strings.HasSuffix(path, ".ct")) { files = append(files, path) } return nil diff --git a/pkg/packages/sync_test.go b/pkg/packages/sync_test.go index 8717a24..aae4faf 100644 --- a/pkg/packages/sync_test.go +++ b/pkg/packages/sync_test.go @@ -5,7 +5,7 @@ import ( "path/filepath" "testing" - "github.com/cloudticon/ctts/pkg/packages" + "github.com/cloudticon/ct/pkg/packages" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -37,3 +37,40 @@ func TestSyncPackages_MissingEntryPoint(t *testing.T) { err := packages.SyncPackages(dir) assert.NoError(t, err, "missing entry point should not error") } + +func TestSyncPackages_FollowsGitImportsIntoCtFiles(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + pkgDir := filepath.Join(home, ".ct", "cache", "github.com", "acme", "factories@v1") + require.NoError(t, os.MkdirAll(pkgDir, 0o755)) + // The package's own .ct file imports something unresolvable; reaching it + // proves the github.com/... import and the .ct file were both followed. + require.NoError(t, os.WriteFile(filepath.Join(pkgDir, "index.ct"), + []byte(`import { x } from "https://github.com/acme";`), 0o644)) + + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "main.ct"), + []byte(`import { webApp } from "github.com/acme/factories@v1";`), 0o644)) + + err := packages.SyncPackages(dir) + require.Error(t, err) + assert.Contains(t, err.Error(), "https://github.com/acme") +} + +func TestImportURL(t *testing.T) { + for in, want := range map[string]string{ + "https://github.com/o/r@v1": "https://github.com/o/r@v1", + "github.com/o/r": "https://github.com/o/r", + "github.com/o/r@v1.2.0/sub/x": "https://github.com/o/r@v1.2.0", + "gitlab.example.com/o/r@main/x": "https://gitlab.example.com/o/r@main", + "custom.dev/mylib/utils": "https://custom.dev/mylib", + } { + got, ok := packages.ImportURL(in) + assert.True(t, ok, in) + assert.Equal(t, want, got, in) + } + for _, in := range []string{"./x", "../x", "lodash", "@scope/pkg"} { + _, ok := packages.ImportURL(in) + assert.False(t, ok, in) + } +} diff --git a/pkg/sync/sync.go b/pkg/sync/sync.go index a4de753..4943a0a 100644 --- a/pkg/sync/sync.go +++ b/pkg/sync/sync.go @@ -12,8 +12,9 @@ import ( "path/filepath" "strings" stdsync "sync" + "time" - "github.com/cloudticon/ctts/pkg/k8s" + "github.com/cloudticon/ct/pkg/k8s" "github.com/fatih/color" ) @@ -23,8 +24,15 @@ type SyncRule struct { To string Exclude []string Polling bool + // Container is the pod container the files are synced into. Empty means + // the API server default, which only works for single-container pods. + Container string } +// podCheckInterval is how often a running syncer checks whether its pod +// was replaced. +var podCheckInterval = 3 * time.Second + // Syncer performs initial and incremental sync. type Syncer struct { exec k8s.PodExecutor @@ -50,17 +58,34 @@ func (s *Syncer) Run(ctx context.Context) error { return s.RunWithReady(ctx, nil) } -// RunWithReady is like Run but calls ready after the initial sync completes. -// The ready callback is guaranteed to be called exactly once before returning, -// even if an error occurs during initial sync. -func (s *Syncer) RunWithReady(ctx context.Context, ready func()) error { - signalReady := func() {} - if ready != nil { - var once stdsync.Once - signalReady = func() { once.Do(ready) } - defer signalReady() +// RunWithReady is like Run but reports the outcome of the initial sync. ready +// is called exactly once: with nil as soon as the initial sync completed, or +// with the error that prevented it (before RunWithReady returns that error). +// Callers can therefore tell "synced" from "failed" without racing the +// returned error. +func (s *Syncer) RunWithReady(ctx context.Context, ready func(error)) error { + signalled := false + err := s.run(ctx, func() { + signalled = true + if ready != nil { + ready(nil) + } + }) + if !signalled { + if err == nil { + err = errors.New("sync stopped before the initial sync completed") + } + if ready != nil { + ready(err) + } + } + if err != nil && errors.Is(err, context.Canceled) && ctx.Err() != nil { + return nil } + return err +} +func (s *Syncer) run(ctx context.Context, signalReady func()) error { if s.exec == nil { return errors.New("k8s client is required") } @@ -68,6 +93,20 @@ func (s *Syncer) RunWithReady(ctx context.Context, ready func()) error { return errors.New("sync rule requires non-empty from and to") } + watcher, err := NewWatcher(s.rule.From, s.rule.Exclude, s.rule.Polling) + if err != nil { + return err + } + // Watch before the initial snapshot is taken: a file saved while the + // initial sync is uploading is then reported afterwards instead of being + // lost between the snapshot and the start of the watcher. + watchCtx, stopWatch := context.WithCancel(ctx) + defer stopWatch() + changes, err := watcher.Watch(watchCtx) + if err != nil { + return err + } + pod, err := s.exec.WaitPod(ctx, s.namespace, s.selector) if err != nil { return err @@ -80,38 +119,139 @@ func (s *Syncer) RunWithReady(ctx context.Context, ready func()) error { signalReady() - watcher, err := NewWatcher(s.rule.From, s.rule.Exclude, s.rule.Polling) - if err != nil { - return err + podCheck := time.NewTicker(podCheckInterval) + defer podCheck.Stop() + for { + select { + case batch, ok := <-changes: + if !ok { + if err := watcher.Err(); err != nil { + return fmt.Errorf("watching %s stopped: %w", s.rule.From, err) + } + if errors.Is(ctx.Err(), context.Canceled) { + return nil + } + return ctx.Err() + } + if s.podName == "" { + // The last re-sync failed; a successful full sync also + // covers this batch. + s.followPod(ctx, 0) + continue + } + if err := s.incrementalSync(ctx, batch); err != nil && ctx.Err() == nil { + log.Printf("%s incremental sync error: %v", color.YellowString("[sync]"), err) + // The usual cause is that the pod is gone; move on to its + // replacement (the full sync covers this batch as well). + s.followPod(ctx, 0) + } + case <-podCheck.C: + // Bounded: WaitPod only returns healthy pods, and a pod that is + // unhealthy but running (e.g. a crash-looping sidecar) must not + // stall syncing into it. + s.followPod(ctx, podCheckInterval) + } } +} - for changes := range watcher.Watch(ctx) { - if err := s.incrementalSync(ctx, changes); err != nil { - log.Printf("%s incremental sync error: %v", color.YellowString("[sync]"), err) +// followPod re-resolves the target pod and, when it has been replaced (a +// rollout, an eviction, or the rollout triggered by ct dev's own workload +// patch while the old pod was still running), runs a full sync into the new +// pod: it starts from the image and has none of the synced files. A positive +// maxWait bounds how long to wait for a healthy pod. +func (s *Syncer) followPod(ctx context.Context, maxWait time.Duration) { + waitCtx := ctx + if maxWait > 0 { + var cancel context.CancelFunc + waitCtx, cancel = context.WithTimeout(ctx, maxWait) + defer cancel() + } + pod, err := s.exec.WaitPod(waitCtx, s.namespace, s.selector) + if err != nil || pod == s.podName { + return + } + previous := s.podName + s.podName = pod + if err := s.initialSync(ctx); err != nil { + if ctx.Err() == nil { + log.Printf("%s re-sync into new pod %s failed, will retry: %v", color.YellowString("[sync]"), pod, err) } + s.podName = "" // retry on the next check + return } - - if errors.Is(ctx.Err(), context.Canceled) { - return nil + if previous != "" { + log.Printf("%s pod %s replaced by %s, re-synced %s", color.CyanString("[sync]"), previous, pod, s.rule.From) } - return ctx.Err() } func (s *Syncer) execStream(ctx context.Context, cmd []string, stdin io.Reader) error { - return s.exec.ExecPod(ctx, s.namespace, s.podName, k8s.ExecOpts{ - Command: cmd, - Stdin: stdin, - Stdout: io.Discard, - Stderr: io.Discard, - }) + return s.runInPod(ctx, cmd, stdin) } func (s *Syncer) execSimple(ctx context.Context, cmd []string) error { - return s.exec.ExecPod(ctx, s.namespace, s.podName, k8s.ExecOpts{ - Command: cmd, - Stdout: io.Discard, - Stderr: io.Discard, + return s.runInPod(ctx, cmd, nil) +} + +// runInPod runs cmd in the target container. On failure the error carries +// what the command printed on stderr: "exit code 2" alone does not tell the +// user that tar could not write to the target directory. +func (s *Syncer) runInPod(ctx context.Context, cmd []string, stdin io.Reader) error { + stderr := &boundedBuffer{max: 4 << 10} + err := s.exec.ExecPod(ctx, s.namespace, s.podName, k8s.ExecOpts{ + Container: s.rule.Container, + Command: cmd, + Stdin: stdin, + Stdout: io.Discard, + Stderr: stderr, }) + if err == nil { + return nil + } + if msg := strings.TrimSpace(stderr.String()); msg != "" { + err = fmt.Errorf("%w: %s", err, msg) + } + if isMissingToolError(err) { + container := "the target container" + if s.rule.Container != "" { + container = fmt.Sprintf("container %q", s.rule.Container) + } + err = fmt.Errorf("%w (ct dev sync runs tar, mkdir and rm in %s; the image must provide them)", err, container) + } + return err +} + +func isMissingToolError(err error) bool { + msg := err.Error() + return strings.Contains(msg, "executable file not found") || + strings.Contains(msg, "exit code 126") || + strings.Contains(msg, "exit code 127") +} + +// boundedBuffer keeps the first max bytes written to it. Exec streams may +// write from another goroutine, hence the lock. +type boundedBuffer struct { + mu stdsync.Mutex + buf bytes.Buffer + max int +} + +func (b *boundedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + if room := b.max - b.buf.Len(); room > 0 { + if len(p) > room { + b.buf.Write(p[:room]) + } else { + b.buf.Write(p) + } + } + return len(p), nil +} + +func (b *boundedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() } func (s *Syncer) ensureRemoteDir(ctx context.Context) error { @@ -123,13 +263,15 @@ func (s *Syncer) initialSync(ctx context.Context) error { if err != nil { return err } - if len(files) == 0 { - return nil - } + // Create the target even when there is nothing to copy yet: later + // incremental syncs extract into it. if err := s.ensureRemoteDir(ctx); err != nil { return fmt.Errorf("creating remote directory %s: %w", s.rule.To, err) } + if len(files) == 0 { + return nil + } buf := bytes.NewBuffer(nil) if _, err := writeTarFromFiles(buf, s.rule.From, files); err != nil { @@ -176,18 +318,43 @@ func (s *Syncer) incrementalSync(ctx context.Context, changes []FileChange) erro } deletedCount := 0 - for _, rel := range deleted { - remote := filepath.ToSlash(filepath.Join(s.rule.To, rel)) - if err := s.execSimple(ctx, []string{"rm", "-rf", remote}); err != nil { + for _, batch := range rmBatches(s.rule.To, deleted) { + if err := s.execSimple(ctx, append([]string{"rm", "-rf"}, batch...)); err != nil { return err } - deletedCount++ + deletedCount += len(batch) } log.Printf("%s %d files synced, %d deleted", color.CyanString("[sync]"), syncedCount, deletedCount) return nil } +// maxRmArgBytes caps the size of one rm command line, far below ARG_MAX. +const maxRmArgBytes = 64 * 1024 + +// rmBatches maps relative paths to container paths under to and groups them +// into as few rm invocations as the argument size limit allows. Deleting a +// directory produces one event per file; one exec per path would cost one +// API round trip each. +func rmBatches(to string, rels []string) [][]string { + var batches [][]string + var current []string + size := 0 + for _, rel := range rels { + remote := filepath.ToSlash(filepath.Join(to, rel)) + if len(current) > 0 && size+len(remote)+1 > maxRmArgBytes { + batches = append(batches, current) + current, size = nil, 0 + } + current = append(current, remote) + size += len(remote) + 1 + } + if len(current) > 0 { + batches = append(batches, current) + } + return batches +} + func collectFiles(root string, exclude []string) ([]string, error) { excluder, err := newPathExcluder(exclude) if err != nil { @@ -228,95 +395,73 @@ func collectFiles(root string, exclude []string) ([]string, error) { } func writeTarFromFiles(w io.Writer, root string, relPaths []string) (int64, error) { + _, size, err := writeTar(w, root, relPaths) + return size, err +} + +func writeTarFromRelativePaths(w io.Writer, root string, relPaths []string) (int, error) { + files, _, err := writeTar(w, root, relPaths) + return files, err +} + +// writeTar archives the regular files among relPaths (relative to root) and +// returns how many files and bytes it wrote. Paths that vanished, and +// anything that is not a regular file (directories, FIFOs, sockets, +// devices), are skipped: opening a FIFO blocks forever and sockets cannot be +// archived. Each file is read completely before its header is written, so a +// file that changes while being archived yields a consistent entry instead +// of a corrupt archive ("archive/tar: write too long"). Files that cannot be +// read (symlink loops, other users' 0600 files) are skipped with a warning +// rather than failing the whole sync. +func writeTar(w io.Writer, root string, relPaths []string) (int, int64, error) { absRoot, err := filepath.Abs(root) if err != nil { - return 0, err + return 0, 0, err } tw := tar.NewWriter(w) - defer tw.Close() - - var total int64 + files := 0 + var size int64 + var skipped []string for _, rel := range relPaths { rel = filepath.ToSlash(rel) srcPath := filepath.Join(absRoot, filepath.FromSlash(rel)) info, err := os.Stat(srcPath) if err != nil { - if os.IsNotExist(err) { - continue + if !os.IsNotExist(err) { + skipped = append(skipped, err.Error()) } - return total, err - } - if info.IsDir() { continue } - - header, err := tar.FileInfoHeader(info, "") - if err != nil { - return total, err - } - header.Name = rel - - if err := tw.WriteHeader(header); err != nil { - return total, err - } - file, err := os.Open(srcPath) - if err != nil { - return total, err + if !info.Mode().IsRegular() { + continue } - n, err := io.Copy(tw, file) - _ = file.Close() + data, err := os.ReadFile(srcPath) if err != nil { - return total, err - } - total += n - } - return total, tw.Close() -} - -func writeTarFromRelativePaths(w io.Writer, root string, relPaths []string) (int, error) { - absRoot, err := filepath.Abs(root) - if err != nil { - return 0, err - } - - tw := tar.NewWriter(w) - defer tw.Close() - - written := 0 - for _, rel := range relPaths { - rel = filepath.ToSlash(rel) - srcPath := filepath.Join(absRoot, filepath.FromSlash(rel)) - info, err := os.Stat(srcPath) - if err != nil { - if os.IsNotExist(err) { - continue + if !os.IsNotExist(err) { + skipped = append(skipped, err.Error()) } - return written, err - } - if info.IsDir() { continue } header, err := tar.FileInfoHeader(info, "") if err != nil { - return written, err + return files, size, err } header.Name = rel + header.Size = int64(len(data)) if err := tw.WriteHeader(header); err != nil { - return written, err - } - - file, err := os.Open(srcPath) - if err != nil { - return written, err + return files, size, err } - _, err = io.Copy(tw, file) - _ = file.Close() - if err != nil { - return written, err + if _, err := tw.Write(data); err != nil { + return files, size, err } - written++ + files++ + size += int64(len(data)) + } + if len(skipped) > 0 { + log.Printf("%s skipped %d unreadable file(s), e.g. %s (exclude them to silence this)", + color.YellowString("[sync]"), len(skipped), skipped[0]) } - return written, tw.Close() + return files, size, tw.Close() } diff --git a/pkg/sync/sync_test.go b/pkg/sync/sync_test.go index 32b510b..49312b0 100644 --- a/pkg/sync/sync_test.go +++ b/pkg/sync/sync_test.go @@ -5,6 +5,7 @@ import ( "bytes" "context" "errors" + "fmt" "io" "os" "path/filepath" @@ -12,7 +13,7 @@ import ( "testing" "time" - "github.com/cloudticon/ctts/pkg/k8s" + "github.com/cloudticon/ct/pkg/k8s" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -117,11 +118,13 @@ func TestSyncerRun_RequiresExec(t *testing.T) { func TestSyncerRunWithReady_StillSignalsReadyOnValidationError(t *testing.T) { s := NewSyncer(nil, "demo", nil, SyncRule{From: ".", To: "/app"}) + var readyErr error readyCalled := false - err := s.RunWithReady(context.Background(), func() { readyCalled = true }) + err := s.RunWithReady(context.Background(), func(err error) { readyCalled, readyErr = true, err }) require.Error(t, err) assert.Contains(t, err.Error(), "k8s client is required") assert.True(t, readyCalled, "ready must be called even on validation error") + assert.Equal(t, err, readyErr, "ready must report the failure") } func TestSyncerRunWithReady_PropagatesWaitError(t *testing.T) { @@ -177,14 +180,15 @@ func TestSyncerRunWithReady_SignalsAfterInitialSync(t *testing.T) { }) ctx, cancel := context.WithCancel(context.Background()) - readyCh := make(chan struct{}) + readyCh := make(chan error, 1) done := make(chan error, 1) go func() { - done <- s.RunWithReady(ctx, func() { close(readyCh) }) + done <- s.RunWithReady(ctx, func(err error) { readyCh <- err }) }() select { - case <-readyCh: + case err := <-readyCh: + require.NoError(t, err, "a successful initial sync reports nil") case <-time.After(2 * time.Second): t.Fatal("ready callback was not called after initial sync") } @@ -226,3 +230,336 @@ func TestSyncerRunWithReady_NilReadyDoesNotPanic(t *testing.T) { // Compile-time check fakePodExecutor satisfies the port. var _ k8s.PodExecutor = (*fakePodExecutor)(nil) + +func TestSyncer_ExecsTargetContainer(t *testing.T) { + root := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(root, "a.txt"), []byte("x"), 0o644)) + + fake := &fakePodExecutor{} + s := NewSyncer(fake, "demo", map[string]string{"app": "x"}, SyncRule{From: root, To: "/app", Container: "app"}) + s.podName = "pod-1" + + require.NoError(t, s.initialSync(context.Background())) + require.NoError(t, s.incrementalSync(context.Background(), []FileChange{ + {Path: "a.txt", Type: ChangeModify}, + {Path: "gone.txt", Type: ChangeDelete}, + })) + + require.NotEmpty(t, fake.ExecCalls) + for _, call := range fake.ExecCalls { + assert.Equal(t, "app", call.Container, "exec %v must target the configured container", call.Command) + } +} + +func tarEntryNames(t *testing.T, r io.Reader) []string { + t.Helper() + var names []string + tr := tar.NewReader(r) + for { + h, err := tr.Next() + if err == io.EOF { + return names + } + require.NoError(t, err) + names = append(names, h.Name) + } +} + +// A file saved while the initial sync is uploading used to be lost: the tar +// snapshot did not contain it yet and the watcher only started afterwards. +func TestSyncerRun_ChangeDuringInitialSyncIsSynced(t *testing.T) { + for _, polling := range []bool{false, true} { + t.Run(map[bool]string{false: "fsnotify", true: "polling"}[polling], func(t *testing.T) { + root := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(root, "a.txt"), []byte("a"), 0o644)) + + initialInFlight := make(chan struct{}) + releaseInitial := make(chan struct{}) + var mu sync.Mutex + var tars [][]string + fake := &fakePodExecutor{ExecFn: func(_ context.Context, _, _ string, opts k8s.ExecOpts) error { + if opts.Command[0] != "tar" { + return nil + } + names := tarEntryNames(t, opts.Stdin) + mu.Lock() + tars = append(tars, names) + first := len(tars) == 1 + mu.Unlock() + if first { + close(initialInFlight) + <-releaseInitial + } + return nil + }} + s := NewSyncer(fake, "demo", map[string]string{"app": "x"}, SyncRule{From: root, To: "/app", Polling: polling}) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { done <- s.Run(ctx) }() + + <-initialInFlight + require.NoError(t, os.WriteFile(filepath.Join(root, "b.txt"), []byte("b"), 0o644)) + close(releaseInitial) + + require.Eventually(t, func() bool { + mu.Lock() + defer mu.Unlock() + for _, names := range tars[1:] { + for _, n := range names { + if n == "b.txt" { + return true + } + } + } + return false + }, 3*time.Second, 20*time.Millisecond, "b.txt changed during the initial sync was never synced") + + cancel() + require.NoError(t, <-done) + }) + } +} + +// Deleting a directory with many files produces one event per file; each +// used to cost its own exec round trip, stalling sync for minutes. +func TestSyncerIncrementalSync_BatchesDeletes(t *testing.T) { + fake := &fakePodExecutor{} + s := NewSyncer(fake, "demo", map[string]string{"app": "x"}, SyncRule{From: t.TempDir(), To: "/app"}) + s.podName = "pod-1" + + var changes []FileChange + want := map[string]bool{} + for i := 0; i < 1000; i++ { + rel := fmt.Sprintf("dist/chunk-%04d.js", i) + changes = append(changes, FileChange{Path: rel, Type: ChangeDelete}) + want["/app/"+rel] = true + } + require.NoError(t, s.incrementalSync(context.Background(), changes)) + + assert.LessOrEqual(t, len(fake.ExecCalls), 3, "deletes must be batched into few rm calls") + got := map[string]bool{} + for _, call := range fake.ExecCalls { + require.Equal(t, []string{"rm", "-rf"}, call.Command[:2]) + for _, p := range call.Command[2:] { + got[p] = true + } + } + assert.Equal(t, want, got) +} + +// Sync commands discarded the container's stderr, so a failing tar only +// reported "command terminated with exit code 2" without the reason. +func TestSyncerInitialSync_ErrorIncludesRemoteStderr(t *testing.T) { + root := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(root, "a.txt"), []byte("x"), 0o644)) + + fake := &fakePodExecutor{ExecFn: func(_ context.Context, _, _ string, opts k8s.ExecOpts) error { + if opts.Command[0] != "tar" { + return nil + } + _, _ = io.WriteString(opts.Stderr, "tar: a.txt: Cannot open: Permission denied\n") + return errors.New("command terminated with exit code 2") + }} + s := NewSyncer(fake, "demo", map[string]string{"app": "x"}, SyncRule{From: root, To: "/app"}) + s.podName = "pod-1" + + err := s.initialSync(context.Background()) + require.Error(t, err) + assert.Contains(t, err.Error(), "exit code 2") + assert.Contains(t, err.Error(), "Permission denied") +} + +func TestSyncerInitialSync_MissingToolHint(t *testing.T) { + root := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(root, "a.txt"), []byte("x"), 0o644)) + + fake := &fakePodExecutor{ExecFn: func(_ context.Context, _, _ string, opts k8s.ExecOpts) error { + return errors.New(`OCI runtime exec failed: exec failed: unable to start container process: exec: "mkdir": executable file not found in $PATH: unknown`) + }} + s := NewSyncer(fake, "demo", map[string]string{"app": "x"}, SyncRule{From: root, To: "/app", Container: "app"}) + s.podName = "pod-1" + + err := s.initialSync(context.Background()) + require.Error(t, err) + assert.Contains(t, err.Error(), `runs tar, mkdir and rm in container "app"`) +} + +// podSwitchingExecutor serves pod-1 until switchPod() is called and pod-2 +// afterwards, recording which pod every tar went to. +type podSwitchingExecutor struct { + mu sync.Mutex + current string + tarsTo []string + failPods map[string]bool +} + +func (p *podSwitchingExecutor) WaitPod(ctx context.Context, _ string, _ k8s.Selector) (string, error) { + p.mu.Lock() + defer p.mu.Unlock() + return p.current, nil +} + +func (p *podSwitchingExecutor) ExecPod(_ context.Context, _, pod string, opts k8s.ExecOpts) error { + p.mu.Lock() + defer p.mu.Unlock() + if p.failPods[pod] { + return fmt.Errorf("pods %q not found", pod) + } + if opts.Command[0] == "tar" { + p.tarsTo = append(p.tarsTo, pod) + } + return nil +} + +func (p *podSwitchingExecutor) switchPod(failOld bool) { + p.mu.Lock() + defer p.mu.Unlock() + if failOld { + p.failPods = map[string]bool{p.current: true} + } + p.current = "pod-2" +} + +func (p *podSwitchingExecutor) tarredTo(pod string) bool { + p.mu.Lock() + defer p.mu.Unlock() + for _, t := range p.tarsTo { + if t == pod { + return true + } + } + return false +} + +func setPodCheckInterval(t *testing.T, d time.Duration) { + t.Helper() + orig := podCheckInterval + podCheckInterval = d + t.Cleanup(func() { podCheckInterval = orig }) +} + +// When the pod is replaced (rollout, eviction, the rollout triggered by +// ct dev's own patch), the new pod starts from the image: it must get a full +// sync even if nothing changes locally. +func TestSyncerRun_ResyncsWhenPodIsReplaced(t *testing.T) { + setPodCheckInterval(t, 20*time.Millisecond) + root := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(root, "a.txt"), []byte("x"), 0o644)) + + exec := &podSwitchingExecutor{current: "pod-1"} + s := NewSyncer(exec, "demo", map[string]string{"app": "x"}, SyncRule{From: root, To: "/app", Polling: true}) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { done <- s.Run(ctx) }() + + require.Eventually(t, func() bool { return exec.tarredTo("pod-1") }, 2*time.Second, 10*time.Millisecond) + exec.switchPod(true) + require.Eventually(t, func() bool { return exec.tarredTo("pod-2") }, 2*time.Second, 10*time.Millisecond, + "the replacement pod never received the synced files") + + cancel() + require.NoError(t, <-done) +} + +// An incremental sync that fails because the pod is gone must move to the +// new pod right away instead of failing against the old one forever. +func TestSyncerRun_FailedIncrementalSyncMovesToNewPod(t *testing.T) { + setPodCheckInterval(t, time.Hour) + root := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(root, "a.txt"), []byte("x"), 0o644)) + + exec := &podSwitchingExecutor{current: "pod-1"} + s := NewSyncer(exec, "demo", map[string]string{"app": "x"}, SyncRule{From: root, To: "/app", Polling: true}) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { done <- s.Run(ctx) }() + + require.Eventually(t, func() bool { return exec.tarredTo("pod-1") }, 2*time.Second, 10*time.Millisecond) + exec.switchPod(true) + require.NoError(t, os.WriteFile(filepath.Join(root, "b.txt"), []byte("y"), 0o644)) + require.Eventually(t, func() bool { return exec.tarredTo("pod-2") }, 3*time.Second, 10*time.Millisecond, + "sync kept targeting the deleted pod") + + cancel() + require.NoError(t, <-done) +} + +// With an empty source directory the initial sync returned before creating +// the target directory, so the first incremental `tar -C /app` failed when +// the image has no /app. +func TestSyncerInitialSync_CreatesTargetDirEvenWhenEmpty(t *testing.T) { + fake := &fakePodExecutor{} + s := NewSyncer(fake, "demo", map[string]string{"app": "x"}, SyncRule{From: t.TempDir(), To: "/app"}) + s.podName = "pod-1" + + require.NoError(t, s.initialSync(context.Background())) + require.Len(t, fake.ExecCalls, 1) + assert.Equal(t, []string{"mkdir", "-p", "/app"}, fake.ExecCalls[0].Command) +} + +// WaitPod only returns healthy pods. If the pod becomes unhealthy but keeps +// running (e.g. a crash-looping sidecar), the periodic pod check must not +// stall the sync loop: changes still have to reach the running container. +func TestSyncerRun_PeriodicPodCheckDoesNotBlockSync(t *testing.T) { + setPodCheckInterval(t, 20*time.Millisecond) + root := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(root, "a.txt"), []byte("x"), 0o644)) + + var mu sync.Mutex + waits := 0 + var tarred []string + fake := &fakePodExecutor{ + WaitFn: func(ctx context.Context, _ string, _ k8s.Selector) (string, error) { + mu.Lock() + waits++ + first := waits == 1 + mu.Unlock() + if first { + return "pod-1", nil + } + <-ctx.Done() // no healthy pod any more + return "", ctx.Err() + }, + ExecFn: func(_ context.Context, _, _ string, opts k8s.ExecOpts) error { + if opts.Command[0] == "tar" { + names := tarEntryNames(t, opts.Stdin) + mu.Lock() + tarred = append(tarred, names...) + mu.Unlock() + } + return nil + }, + } + s := NewSyncer(fake, "demo", map[string]string{"app": "x"}, SyncRule{From: root, To: "/app", Polling: true}) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { done <- s.Run(ctx) }() + + require.Eventually(t, func() bool { + mu.Lock() + defer mu.Unlock() + return waits >= 2 + }, 2*time.Second, 5*time.Millisecond, "periodic check should have started") + require.NoError(t, os.WriteFile(filepath.Join(root, "b.txt"), []byte("y"), 0o644)) + require.Eventually(t, func() bool { + mu.Lock() + defer mu.Unlock() + for _, n := range tarred { + if n == "b.txt" { + return true + } + } + return false + }, 3*time.Second, 10*time.Millisecond, "sync stalled behind the pod check") + + cancel() + require.NoError(t, <-done) +} diff --git a/pkg/sync/tar_unix_test.go b/pkg/sync/tar_unix_test.go new file mode 100644 index 0000000..45e4773 --- /dev/null +++ b/pkg/sync/tar_unix_test.go @@ -0,0 +1,134 @@ +//go:build !windows + +package sync + +import ( + "archive/tar" + "bytes" + "io" + "net" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Opening a FIFO blocks until a writer shows up, so a named pipe anywhere in +// the synced tree used to hang the initial sync forever. +func TestWriteTar_SkipsFIFOs(t *testing.T) { + root := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(root, "a.txt"), []byte("a"), 0o644)) + require.NoError(t, syscall.Mkfifo(filepath.Join(root, "pipe"), 0o644)) + + files, err := collectFiles(root, nil) + require.NoError(t, err) + + done := make(chan error, 1) + var buf bytes.Buffer + go func() { + _, err := writeTarFromFiles(&buf, root, files) + done <- err + }() + select { + case err := <-done: + require.NoError(t, err) + case <-time.After(2 * time.Second): + t.Fatal("writing the tar hung on a FIFO") + } + assert.Equal(t, []string{"a.txt"}, tarNames(t, buf.Bytes())) +} + +// A unix socket in the tree (git fsmonitor, a local database socket, ...) +// used to abort the whole sync with "archive/tar: sockets not supported". +func TestWriteTar_SkipsSockets(t *testing.T) { + root, err := os.MkdirTemp("", "ctsock") + require.NoError(t, err) + t.Cleanup(func() { _ = os.RemoveAll(root) }) + require.NoError(t, os.WriteFile(filepath.Join(root, "a.txt"), []byte("a"), 0o644)) + l, err := net.Listen("unix", filepath.Join(root, "s.sock")) + require.NoError(t, err) + t.Cleanup(func() { _ = l.Close() }) + + var buf bytes.Buffer + _, err = writeTarFromRelativePaths(&buf, root, []string{"a.txt", "s.sock"}) + require.NoError(t, err) + assert.Equal(t, []string{"a.txt"}, tarNames(t, buf.Bytes())) +} + +// The tar header used the size from stat while the content was copied +// later; a file that grew in between (a log being appended to, an editor +// writing) failed the whole batch with "archive/tar: write too long". +// procfs files report size 0 but have content, which reproduces that +// deterministically. +func TestWriteTar_FileChangingSizeAfterStat(t *testing.T) { + if _, err := os.Stat("/proc/self/status"); err != nil { + t.Skip("procfs not available") + } + root := t.TempDir() + require.NoError(t, os.Symlink("/proc/self/status", filepath.Join(root, "growing.log"))) + + var buf bytes.Buffer + _, err := writeTarFromFiles(&buf, root, []string{"growing.log"}) + require.NoError(t, err) + + tr := tar.NewReader(bytes.NewReader(buf.Bytes())) + h, err := tr.Next() + require.NoError(t, err) + assert.Equal(t, "growing.log", h.Name) + content, err := io.ReadAll(tr) + require.NoError(t, err) + assert.Contains(t, string(content), "Name:", "the entry must hold the file's actual content") +} + +func tarNames(t *testing.T, data []byte) []string { + t.Helper() + return tarEntryNames(t, bytes.NewReader(data)) +} + +// One unreadable entry (a symlink loop, a root-owned 0600 file written by a +// container into a bind mount) used to abort the whole sync. +func TestWriteTar_SkipsUnreadableFiles(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root can read everything") + } + root := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(root, "a.txt"), []byte("a"), 0o644)) + require.NoError(t, os.Symlink("loop", filepath.Join(root, "loop"))) + require.NoError(t, os.WriteFile(filepath.Join(root, "secret.key"), []byte("k"), 0o000)) + + var buf bytes.Buffer + files, _, err := writeTar(&buf, root, []string{"loop", "secret.key", "a.txt"}) + require.NoError(t, err) + assert.Equal(t, 1, files) + assert.Equal(t, []string{"a.txt"}, tarNames(t, buf.Bytes())) +} + +func TestWriteTar_PreservesModeAndLongNames(t *testing.T) { + root := t.TempDir() + long := filepath.Join("very", strings.Repeat("deeply-nested-directory-", 8), strings.Repeat("n", 120)+".sh") + require.NoError(t, os.MkdirAll(filepath.Join(root, filepath.Dir(long)), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(root, long), []byte("#!/bin/sh\n"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(root, "żółw.txt"), []byte("utf8"), 0o640)) + + var buf bytes.Buffer + _, err := writeTarFromFiles(&buf, root, []string{filepath.ToSlash(long), "żółw.txt"}) + require.NoError(t, err) + + tr := tar.NewReader(bytes.NewReader(buf.Bytes())) + modes := map[string]int64{} + for { + h, err := tr.Next() + if err == io.EOF { + break + } + require.NoError(t, err) + modes[h.Name] = h.Mode & 0o777 + } + assert.Equal(t, int64(0o755), modes[filepath.ToSlash(long)], "long names survive and executables stay executable") + assert.Equal(t, int64(0o640), modes["żółw.txt"]) +} diff --git a/pkg/sync/watcher.go b/pkg/sync/watcher.go index f0587e6..d47c5d2 100644 --- a/pkg/sync/watcher.go +++ b/pkg/sync/watcher.go @@ -3,16 +3,27 @@ package sync import ( "context" "errors" + "fmt" "os" "path/filepath" "strings" + stdsync "sync" + "syscall" "time" "github.com/bmatcuk/doublestar/v4" "github.com/fsnotify/fsnotify" ) -const debounceWindow = 300 * time.Millisecond +const ( + debounceWindow = 300 * time.Millisecond + // maxDebounce bounds how long a continuous stream of events (e.g. a + // build writing files) can postpone a flush. + maxDebounce = 2 * time.Second +) + +// newFSWatcher is a seam for tests. +var newFSWatcher = fsnotify.NewWatcher // ChangeType describes a file system change type. type ChangeType int @@ -36,6 +47,9 @@ type Watcher struct { polling bool excluder *pathExcluder pollEvery time.Duration + + mu stdsync.Mutex + err error } // NewWatcher creates a watcher for root. @@ -70,134 +84,201 @@ func NewWatcher(root string, exclude []string, polling bool) (*Watcher, error) { } // Watch starts watching and returns a channel of debounced change batches. -func (w *Watcher) Watch(ctx context.Context) <-chan []FileChange { +// It returns only once the watcher is established, so every change made +// after Watch returns is reported. The channel is closed when ctx is done or +// the watcher fails; Err reports the failure. +func (w *Watcher) Watch(ctx context.Context) (<-chan []FileChange, error) { out := make(chan []FileChange) if w.polling { - go w.pollLoop(ctx, out) - } else { - go w.fsnotifyLoop(ctx, out) + prev, err := w.snapshot() + if err != nil { + return nil, fmt.Errorf("scanning %s: %w", w.root, err) + } + go w.pollLoop(ctx, prev, out) + return out, nil + } + + fw, err := newFSWatcher() + if err != nil { + return nil, fmt.Errorf("creating file watcher: %w%s", err, watchLimitHint(err)) + } + if err := w.addWatches(fw, w.root, nil); err != nil { + _ = fw.Close() + return nil, err } - return out + go w.fsnotifyLoop(ctx, fw, out) + return out, nil } -func (w *Watcher) fsnotifyLoop(ctx context.Context, out chan<- []FileChange) { - defer close(out) +// Err returns the error that stopped the watcher, if any. +func (w *Watcher) Err() error { + w.mu.Lock() + defer w.mu.Unlock() + return w.err +} - fw, err := fsnotify.NewWatcher() - if err != nil { - return +func (w *Watcher) setErr(err error) { + w.mu.Lock() + defer w.mu.Unlock() + if w.err == nil { + w.err = err } - defer fw.Close() +} - _ = filepath.WalkDir(w.root, func(path string, d os.DirEntry, walkErr error) error { +// addWatches watches dir and every non-excluded directory below it. When +// onFile is set it is called for every non-excluded file found on the way. +// Running out of watches is an error: silently unwatched directories would +// mean silently unsynced changes. +func (w *Watcher) addWatches(fw *fsnotify.Watcher, dir string, onFile func(path string)) error { + return filepath.WalkDir(dir, func(path string, d os.DirEntry, walkErr error) error { if walkErr != nil { return nil } + if path != w.root && w.isExcluded(path, d.IsDir()) { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } if !d.IsDir() { + if onFile != nil { + onFile(path) + } return nil } - if w.isExcluded(path, true) && path != w.root { - return filepath.SkipDir + if err := fw.Add(path); err != nil && isWatchLimitError(err) { + return fmt.Errorf("watching %s: %w%s", path, err, watchLimitHint(err)) } - _ = fw.Add(path) return nil }) +} - pending := make(map[string]FileChange) - var timer *time.Timer - var timerCh <-chan time.Time +func isWatchLimitError(err error) bool { + return errors.Is(err, syscall.ENOSPC) || errors.Is(err, syscall.EMFILE) || errors.Is(err, syscall.ENFILE) +} - resetTimer := func() { - if timer == nil { - timer = time.NewTimer(debounceWindow) - timerCh = timer.C - return - } - if !timer.Stop() { - select { - case <-timer.C: - default: - } - } - timer.Reset(debounceWindow) +func watchLimitHint(err error) string { + if !isWatchLimitError(err) { + return "" } - flush := func() { + return " (the OS file-watch limit is exhausted: exclude large directories such as node_modules, " + + "raise fs.inotify.max_user_watches / fs.inotify.max_user_instances on Linux, " + + "or set polling: true on this sync rule)" +} + +func (w *Watcher) fsnotifyLoop(ctx context.Context, fw *fsnotify.Watcher, out chan<- []FileChange) { + defer close(out) + defer fw.Close() + + pending := make(map[string]FileChange) + var pendingSince time.Time + timer := time.NewTimer(time.Hour) + timer.Stop() + flushDue := false + var batch []FileChange // pending as a slice, rebuilt only when it changed + dirty := false + + add := func(change FileChange) { + dirty = true if len(pending) == 0 { - return + pendingSince = time.Now() } - batch := make([]FileChange, 0, len(pending)) - for _, change := range pending { - batch = append(batch, change) + if prev, exists := pending[change.Path]; exists { + pending[change.Path] = mergeChangeTypes(prev, change) + } else { + pending[change.Path] = change } - pending = make(map[string]FileChange) - select { - case out <- batch: - case <-ctx.Done(): + // Debounce, but never postpone a flush beyond maxDebounce. + if !flushDue && time.Since(pendingSince) < maxDebounce { + timer.Reset(debounceWindow) } } - defer func() { - if timer != nil { - timer.Stop() + addFile := func(path string, typ ChangeType) { + if rel, err := w.rel(path); err == nil && rel != "." { + add(FileChange{Path: rel, Type: typ}) } - flush() - }() + } for { + // Keep consuming events while the receiver is busy (initial sync, + // slow upload): changes are merged into pending instead of piling + // up in the kernel queue, which can overflow and drop events. + var send chan<- []FileChange + if flushDue && len(pending) > 0 { + send = out + if dirty { + batch = make([]FileChange, 0, len(pending)) + for _, change := range pending { + batch = append(batch, change) + } + dirty = false + } + } + select { case <-ctx.Done(): + timer.Stop() return + case send <- batch: + pending = make(map[string]FileChange) + batch = nil + flushDue = false + case <-timer.C: + flushDue = true case err, ok := <-fw.Errors: if !ok { + w.setErr(errors.New("file watcher stopped")) return } - if err != nil { - // Keep watching on fsnotify errors. - continue + if errors.Is(err, fsnotify.ErrEventOverflow) { + // Events were dropped: rescan everything so nothing is missed. + if err := w.addWatches(fw, w.root, func(path string) { addFile(path, ChangeModify) }); err != nil { + w.setErr(err) + return + } } case event, ok := <-fw.Events: if !ok { + w.setErr(errors.New("file watcher stopped")) return } - isDir := pathExistsAndIsDir(event.Name) - if w.isExcluded(event.Name, isDir) { + info, statErr := os.Stat(event.Name) + isDir := statErr == nil && info.IsDir() + excluded := w.isExcluded(event.Name, isDir) + if statErr != nil { + // Gone (deleted or renamed away): its type is unknown, and a + // deleted excluded directory must not be deleted remotely. + excluded = excluded || w.isExcluded(event.Name, true) + } + if excluded { continue } if event.Op&fsnotify.Create != 0 && isDir { - _ = filepath.WalkDir(event.Name, func(path string, d os.DirEntry, walkErr error) error { - if walkErr != nil || !d.IsDir() { - return nil - } - if w.isExcluded(path, true) && path != w.root { - return filepath.SkipDir - } - _ = fw.Add(path) - return nil - }) + // A directory that appears with content (mv, git checkout, + // unzip) produces no events for the files already inside it: + // report them while the new directories are being watched. + // Watches are added before each directory is read, so files + // created concurrently are seen either here or as events. + if err := w.addWatches(fw, event.Name, func(path string) { addFile(path, ChangeCreate) }); err != nil { + w.setErr(err) + return + } } change, ok := w.toFileChange(event) if !ok { continue } - prev, exists := pending[change.Path] - if exists { - pending[change.Path] = mergeChangeTypes(prev, change) - } else { - pending[change.Path] = change - } - resetTimer() - case <-timerCh: - flush() + add(change) } } } -func (w *Watcher) pollLoop(ctx context.Context, out chan<- []FileChange) { +func (w *Watcher) pollLoop(ctx context.Context, prev map[string]fileState, out chan<- []FileChange) { defer close(out) - prev, _ := w.snapshot() ticker := time.NewTicker(w.pollEvery) defer ticker.Stop() @@ -318,11 +399,6 @@ func (w *Watcher) rel(path string) (string, error) { return filepath.ToSlash(rel), nil } -func pathExistsAndIsDir(path string) bool { - info, err := os.Stat(path) - return err == nil && info.IsDir() -} - func (w *Watcher) isExcluded(path string, isDir bool) bool { rel, err := filepath.Rel(w.root, path) if err != nil { @@ -381,7 +457,20 @@ func newPathExcluder(patterns []string) (*pathExcluder, error) { return &pathExcluder{rules: rules}, nil } +// IsExcluded reports whether rel (slash-separated, relative to the sync +// root) is excluded. As in gitignore, everything below an excluded directory +// is excluded too and cannot be re-included. func (e *pathExcluder) IsExcluded(rel string, isDir bool) bool { + rel = filepath.ToSlash(rel) + for i := 0; i < len(rel); i++ { + if rel[i] == '/' && e.excludes(rel[:i], true) { + return true + } + } + return e.excludes(rel, isDir) +} + +func (e *pathExcluder) excludes(rel string, isDir bool) bool { excluded := false for _, rule := range e.rules { if rule.matches(rel, isDir) { @@ -392,13 +481,10 @@ func (e *pathExcluder) IsExcluded(rel string, isDir bool) bool { } func (r excludeRule) matches(rel string, isDir bool) bool { - rel = filepath.ToSlash(rel) if r.dirOnly && !isDir { - // For dir-only rules support descendants too. - return strings.HasPrefix(rel+"/", r.pattern+"/") - } - if r.dirOnly && isDir && strings.HasPrefix(rel+"/", r.pattern+"/") { - return true + // "build/" matches directories only; their content is covered by + // the ancestor check in IsExcluded. + return false } if r.anchored { diff --git a/pkg/sync/watcher_test.go b/pkg/sync/watcher_test.go index 729b143..1144ac1 100644 --- a/pkg/sync/watcher_test.go +++ b/pkg/sync/watcher_test.go @@ -4,9 +4,11 @@ import ( "context" "os" "path/filepath" + "syscall" "testing" "time" + "github.com/fsnotify/fsnotify" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -47,8 +49,8 @@ func TestWatcherPolling_EmitsCreateAndDelete(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() - ch := w.Watch(ctx) - time.Sleep(120 * time.Millisecond) + ch, err := w.Watch(ctx) + require.NoError(t, err) target := filepath.Join(root, "notes.txt") require.NoError(t, os.WriteFile(target, []byte("hello"), 0o644)) @@ -69,7 +71,8 @@ func TestWatcherFsnotify_DebouncesRapidChanges(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - ch := w.Watch(ctx) + ch, err := w.Watch(ctx) + require.NoError(t, err) target := filepath.Join(root, "rapid.txt") require.NoError(t, os.WriteFile(target, []byte("a"), 0o644)) @@ -97,3 +100,128 @@ func waitBatch(t *testing.T, ch <-chan []FileChange) []FileChange { return nil } } + +func TestWatcher_ReportsWatcherCreationFailureWithHint(t *testing.T) { + orig := newFSWatcher + t.Cleanup(func() { newFSWatcher = orig }) + newFSWatcher = func() (*fsnotify.Watcher, error) { return nil, syscall.EMFILE } + + w, err := NewWatcher(t.TempDir(), nil, false) + require.NoError(t, err) + _, err = w.Watch(context.Background()) + require.Error(t, err) + assert.Contains(t, err.Error(), "polling: true", "the error must tell the user how to get unstuck") +} + +// A watcher that could not start used to close its channel silently, so +// Syncer.Run returned nil and sync stopped without any message. +func TestSyncerRun_FailsWhenWatcherCannotStart(t *testing.T) { + orig := newFSWatcher + t.Cleanup(func() { newFSWatcher = orig }) + newFSWatcher = func() (*fsnotify.Watcher, error) { return nil, syscall.EMFILE } + + root := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(root, "a.txt"), []byte("x"), 0o644)) + s := NewSyncer(&fakePodExecutor{}, "demo", map[string]string{"app": "x"}, SyncRule{From: root, To: "/app"}) + + done := make(chan error, 1) + go func() { done <- s.Run(context.Background()) }() + select { + case err := <-done: + require.Error(t, err) + assert.Contains(t, err.Error(), "too many open files") + case <-time.After(2 * time.Second): + t.Fatal("Run kept running although no file watcher could be created") + } +} + +// Moving a populated directory into the tree (mv, git checkout, unzip, cp -r) +// yields one Create event for the directory and none for the files inside. +// The files used to be skipped (directories are not tarred) and never synced. +func TestWatcherFsnotify_ReportsFilesInsideNewDirectory(t *testing.T) { + root := t.TempDir() + w, err := NewWatcher(root, []string{"*.tmp"}, false) + require.NoError(t, err) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + ch, err := w.Watch(ctx) + require.NoError(t, err) + + staging := filepath.Join(t.TempDir(), "pkg") + require.NoError(t, os.MkdirAll(filepath.Join(staging, "sub"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(staging, "a.txt"), []byte("a"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(staging, "sub", "b.txt"), []byte("b"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(staging, "skip.tmp"), []byte("x"), 0o644)) + require.NoError(t, os.Rename(staging, filepath.Join(root, "pkg"))) + + seen := map[string]ChangeType{} + reported := func(path string) bool { + typ, ok := seen[path] + return ok && typ == ChangeCreate + } + deadline := time.After(3 * time.Second) + for !reported("pkg/a.txt") || !reported("pkg/sub/b.txt") { + select { + case batch := <-ch: + for _, c := range batch { + seen[c.Path] = c.Type + } + case <-deadline: + t.Fatalf("files inside the new directory were not reported; got %v", seen) + } + } + _, excluded := seen["pkg/skip.tmp"] + assert.False(t, excluded, "excluded files must not be reported") +} + +func TestPathExcluder_DirOnlyRulesAndDescendants(t *testing.T) { + excluder, err := newPathExcluder([]string{"build/", "node_modules", "/dist"}) + require.NoError(t, err) + + assert.True(t, excluder.IsExcluded("build", true)) + assert.True(t, excluder.IsExcluded("src/build", true), "dir-only rules without a slash match at any depth") + assert.True(t, excluder.IsExcluded("src/build/out.js", false), "everything below an excluded directory is excluded") + assert.True(t, excluder.IsExcluded("packages/a/node_modules/x/index.js", false)) + assert.True(t, excluder.IsExcluded("dist/app.js", false)) + assert.False(t, excluder.IsExcluded("src/dist/app.js", false), "anchored rules only match at the root") + assert.False(t, excluder.IsExcluded("src/builder.go", false)) +} + +// Deleting an excluded directory locally must not delete it in the +// container: it was excluded precisely so the container keeps its own copy +// (build output, dependencies, ...). +func TestWatcherFsnotify_IgnoresDeletionOfExcludedDirectory(t *testing.T) { + root := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(root, "src", "build"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(root, "src", "build", "out.js"), []byte("x"), 0o644)) + + w, err := NewWatcher(root, []string{"build/"}, false) + require.NoError(t, err) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + ch, err := w.Watch(ctx) + require.NoError(t, err) + + require.NoError(t, os.RemoveAll(filepath.Join(root, "src", "build"))) + require.NoError(t, os.WriteFile(filepath.Join(root, "src", "marker.txt"), []byte("m"), 0o644)) + + var seen []FileChange + for { + batch := waitBatch(t, ch) + seen = append(seen, batch...) + if containsPath(seen, "src/marker.txt") { + break + } + } + assert.False(t, containsPath(seen, "src/build"), "deleting an excluded directory must not be synced: %v", seen) +} + +func containsPath(changes []FileChange, path string) bool { + for _, c := range changes { + if c.Path == path { + return true + } + } + return false +} diff --git a/pkg/validate/kinds.go b/pkg/validate/kinds.go new file mode 100644 index 0000000..0699e88 --- /dev/null +++ b/pkg/validate/kinds.go @@ -0,0 +1,350 @@ +package validate + +import ( + "fmt" + + appsv1 "k8s.io/api/apps/v1" + autoscalingv2 "k8s.io/api/autoscaling/v2" + batchv1 "k8s.io/api/batch/v1" + corev1 "k8s.io/api/core/v1" + networkingv1 "k8s.io/api/networking/v1" + policyv1 "k8s.io/api/policy/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/intstr" + utilvalidation "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +// checkTyped applies the API server's admission rules that strict decoding +// can't see. Only rules the server enforces belong here. +func checkTyped(obj runtime.Object) field.ErrorList { + spec := field.NewPath("spec") + switch o := obj.(type) { + case *appsv1.Deployment: + return checkController(o.Spec.Selector, &o.Spec.Template, spec) + case *appsv1.StatefulSet: + // The API server adds volumeClaimTemplates as pod volumes, so + // containers may mount them by name. + var claims []string + for _, c := range o.Spec.VolumeClaimTemplates { + claims = append(claims, c.Name) + } + return checkController(o.Spec.Selector, &o.Spec.Template, spec, claims...) + case *appsv1.DaemonSet: + return checkController(o.Spec.Selector, &o.Spec.Template, spec) + case *appsv1.ReplicaSet: + return checkController(o.Spec.Selector, &o.Spec.Template, spec) + case *batchv1.Job: + return checkJobTemplate(&o.Spec.Template, spec.Child("template")) + case *batchv1.CronJob: + var errs field.ErrorList + if o.Spec.Schedule == "" { + errs = append(errs, field.Required(spec.Child("schedule"), "e.g. \"0 3 * * *\"")) + } + return append(errs, checkJobTemplate(&o.Spec.JobTemplate.Spec.Template, spec.Child("jobTemplate", "spec", "template"))...) + case *corev1.Pod: + return checkPodSpec(&o.Spec, spec) + case *corev1.Service: + return checkService(o, spec) + case *networkingv1.Ingress: + return checkIngress(o, spec) + case *autoscalingv2.HorizontalPodAutoscaler: + return checkHPA(o, spec) + case *policyv1.PodDisruptionBudget: + if o.Spec.MinAvailable != nil && o.Spec.MaxUnavailable != nil { + return field.ErrorList{field.Invalid(spec, "", "minAvailable and maxUnavailable cannot be both set")} + } + case *corev1.ConfigMap: + return checkDataKeys(field.NewPath("data"), keysOf(o.Data), field.NewPath("binaryData"), keysOfBytes(o.BinaryData)) + case *corev1.Secret: + return checkSecret(o) + } + return nil +} + +// checkController covers Deployment, StatefulSet, DaemonSet and ReplicaSet. +func checkController(selector *metav1.LabelSelector, template *corev1.PodTemplateSpec, spec *field.Path, extraVolumes ...string) field.ErrorList { + var errs field.ErrorList + switch { + case selector == nil: + errs = append(errs, field.Required(spec.Child("selector"), "e.g. matchLabels: { app: }, matching spec.template.metadata.labels")) + case len(selector.MatchLabels)+len(selector.MatchExpressions) == 0: + errs = append(errs, field.Invalid(spec.Child("selector"), selector, "empty selector is invalid")) + default: + matches, err := labelSelectorMatches(selector, template.Labels) + if err != nil { + errs = append(errs, field.Invalid(spec.Child("selector"), selector, err.Error())) + } else if !matches { + errs = append(errs, field.Invalid(spec.Child("template", "metadata", "labels"), template.Labels, + "`selector` does not match template `labels`")) + } + } + + podSpec := spec.Child("template", "spec") + if p := template.Spec.RestartPolicy; p != "" && p != corev1.RestartPolicyAlways { + errs = append(errs, field.NotSupported(podSpec.Child("restartPolicy"), p, []string{string(corev1.RestartPolicyAlways)})) + } + return append(errs, checkPodSpec(&template.Spec, podSpec, extraVolumes...)...) +} + +func checkJobTemplate(template *corev1.PodTemplateSpec, path *field.Path) field.ErrorList { + var errs field.ErrorList + podSpec := path.Child("spec") + if p := template.Spec.RestartPolicy; p != corev1.RestartPolicyOnFailure && p != corev1.RestartPolicyNever { + errs = append(errs, field.NotSupported(podSpec.Child("restartPolicy"), p, + []string{string(corev1.RestartPolicyOnFailure), string(corev1.RestartPolicyNever)})) + } + return append(errs, checkPodSpec(&template.Spec, podSpec)...) +} + +func checkPodSpec(spec *corev1.PodSpec, path *field.Path, extraVolumes ...string) field.ErrorList { + var errs field.ErrorList + + volumes := map[string]bool{} + for _, name := range extraVolumes { + volumes[name] = true + } + for i, v := range spec.Volumes { + vp := path.Child("volumes").Index(i) + if v.Name == "" { + errs = append(errs, field.Required(vp.Child("name"), "")) + } else if volumes[v.Name] { + errs = append(errs, field.Duplicate(vp.Child("name"), v.Name)) + } + volumes[v.Name] = true + // No source at all is fine: the API server defaults it to emptyDir. + if countSet(v.VolumeSource) > 1 { + errs = append(errs, field.Forbidden(vp, "may not specify more than 1 volume type")) + } + } + + if len(spec.Containers) == 0 { + errs = append(errs, field.Required(path.Child("containers"), "at least one container")) + } + names := map[string]bool{} + errs = append(errs, checkContainers(spec.InitContainers, path.Child("initContainers"), names, volumes)...) + errs = append(errs, checkContainers(spec.Containers, path.Child("containers"), names, volumes)...) + return errs +} + +func checkContainers(containers []corev1.Container, path *field.Path, names, volumes map[string]bool) field.ErrorList { + var errs field.ErrorList + for i, c := range containers { + cp := path.Index(i) + switch { + case c.Name == "": + errs = append(errs, field.Required(cp.Child("name"), "")) + case names[c.Name]: + errs = append(errs, field.Duplicate(cp.Child("name"), c.Name)) + default: + for _, msg := range utilvalidation.IsDNS1123Label(c.Name) { + errs = append(errs, field.Invalid(cp.Child("name"), c.Name, msg)) + } + } + names[c.Name] = true + if c.Image == "" { + errs = append(errs, field.Required(cp.Child("image"), "")) + } + for j, p := range c.Ports { + pp := cp.Child("ports").Index(j) + for _, msg := range utilvalidation.IsValidPortNum(int(p.ContainerPort)) { + errs = append(errs, field.Invalid(pp.Child("containerPort"), p.ContainerPort, msg)) + } + if p.Name != "" { + for _, msg := range utilvalidation.IsValidPortName(p.Name) { + errs = append(errs, field.Invalid(pp.Child("name"), p.Name, msg)) + } + } + } + for j, m := range c.VolumeMounts { + if m.Name != "" && !volumes[m.Name] { + errs = append(errs, field.NotFound(cp.Child("volumeMounts").Index(j).Child("name"), m.Name)) + } + } + } + return errs +} + +func checkService(svc *corev1.Service, spec *field.Path) field.ErrorList { + var errs field.ErrorList + if svc.Spec.Type == corev1.ServiceTypeExternalName { + if svc.Spec.ExternalName == "" { + errs = append(errs, field.Required(spec.Child("externalName"), "")) + } + return errs + } + headless := svc.Spec.ClusterIP == corev1.ClusterIPNone || + (len(svc.Spec.ClusterIPs) > 0 && svc.Spec.ClusterIPs[0] == corev1.ClusterIPNone) + if len(svc.Spec.Ports) == 0 && !headless { + errs = append(errs, field.Required(spec.Child("ports"), "e.g. ports: [{ port: 80, targetPort: 8080 }]")) + } + names := map[string]bool{} + for i, p := range svc.Spec.Ports { + pp := spec.Child("ports").Index(i) + for _, msg := range utilvalidation.IsValidPortNum(int(p.Port)) { + errs = append(errs, field.Invalid(pp.Child("port"), p.Port, msg)) + } + if len(svc.Spec.Ports) > 1 && p.Name == "" { + errs = append(errs, field.Required(pp.Child("name"), "required when the Service has more than one port")) + } + if p.Name != "" { + if names[p.Name] { + errs = append(errs, field.Duplicate(pp.Child("name"), p.Name)) + } + names[p.Name] = true + } + errs = append(errs, checkPortRef(p.TargetPort, pp.Child("targetPort"), true)...) + } + return errs +} + +// checkPortRef validates a port given as a number or an IANA name. An +// optional port may be 0 or "" (the API server defaults it). +func checkPortRef(port intstr.IntOrString, path *field.Path, optional bool) field.ErrorList { + var errs field.ErrorList + switch { + case optional && ((port.Type == intstr.Int && port.IntVal == 0) || (port.Type == intstr.String && port.StrVal == "")): + case port.Type == intstr.Int: + for _, msg := range utilvalidation.IsValidPortNum(int(port.IntVal)) { + errs = append(errs, field.Invalid(path, port.IntVal, msg)) + } + default: + for _, msg := range utilvalidation.IsValidPortName(port.StrVal) { + errs = append(errs, field.Invalid(path, port.StrVal, msg)) + } + } + return errs +} + +func checkIngress(ing *networkingv1.Ingress, spec *field.Path) field.ErrorList { + var errs field.ErrorList + if ing.Spec.DefaultBackend == nil && len(ing.Spec.Rules) == 0 { + errs = append(errs, field.Invalid(spec, "", "either `defaultBackend` or `rules` must be specified")) + } + if ing.Spec.DefaultBackend != nil { + errs = append(errs, checkIngressBackend(ing.Spec.DefaultBackend, spec.Child("defaultBackend"))...) + } + for i, rule := range ing.Spec.Rules { + if rule.HTTP == nil { + continue + } + for j, p := range rule.HTTP.Paths { + pp := spec.Child("rules").Index(i).Child("http", "paths").Index(j) + if p.PathType == nil { + errs = append(errs, field.Required(pp.Child("pathType"), "Prefix, Exact or ImplementationSpecific")) + } + errs = append(errs, checkIngressBackend(&p.Backend, pp.Child("backend"))...) + } + } + return errs +} + +func checkIngressBackend(b *networkingv1.IngressBackend, path *field.Path) field.ErrorList { + switch { + case b.Service != nil && b.Resource != nil: + return field.ErrorList{field.Invalid(path, "", "cannot set both service and resource")} + case b.Resource != nil: + return nil + case b.Service == nil: + return field.ErrorList{field.Required(path.Child("service"), "e.g. service: { name: , port: { number: 80 } }")} + } + var errs field.ErrorList + sp := path.Child("service") + if b.Service.Name == "" { + errs = append(errs, field.Required(sp.Child("name"), "")) + } + port := b.Service.Port + switch { + case port.Name != "" && port.Number != 0: + errs = append(errs, field.Invalid(sp.Child("port"), port, "cannot set both port name and port number")) + case port.Name != "": + for _, msg := range utilvalidation.IsValidPortName(port.Name) { + errs = append(errs, field.Invalid(sp.Child("port", "name"), port.Name, msg)) + } + default: + for _, msg := range utilvalidation.IsValidPortNum(int(port.Number)) { + errs = append(errs, field.Invalid(sp.Child("port", "number"), port.Number, msg)) + } + } + return errs +} + +func checkHPA(hpa *autoscalingv2.HorizontalPodAutoscaler, spec *field.Path) field.ErrorList { + var errs field.ErrorList + if hpa.Spec.ScaleTargetRef.Kind == "" { + errs = append(errs, field.Required(spec.Child("scaleTargetRef", "kind"), "")) + } + if hpa.Spec.ScaleTargetRef.Name == "" { + errs = append(errs, field.Required(spec.Child("scaleTargetRef", "name"), "")) + } + if hpa.Spec.MaxReplicas < 1 { + errs = append(errs, field.Invalid(spec.Child("maxReplicas"), hpa.Spec.MaxReplicas, "must be greater than or equal to 1")) + } + if min := hpa.Spec.MinReplicas; min != nil && *min > hpa.Spec.MaxReplicas { + errs = append(errs, field.Invalid(spec.Child("maxReplicas"), hpa.Spec.MaxReplicas, "must be greater than or equal to `minReplicas`")) + } + return errs +} + +func checkSecret(s *corev1.Secret) field.ErrorList { + keys := keysOfBytes(s.Data) + stringKeys := keysOf(s.StringData) + errs := checkDataKeys(field.NewPath("data"), keys, field.NewPath("stringData"), nil) + errs = append(errs, checkDataKeys(field.NewPath("stringData"), stringKeys, nil, nil)...) + + present := map[string]bool{} + for _, k := range append(keys, stringKeys...) { + present[k] = true + } + var required []string + switch s.Type { + case corev1.SecretTypeTLS: + required = []string{corev1.TLSCertKey, corev1.TLSPrivateKeyKey} + case corev1.SecretTypeDockerConfigJson: + required = []string{corev1.DockerConfigJsonKey} + case corev1.SecretTypeBasicAuth: + if !present[corev1.BasicAuthUsernameKey] && !present[corev1.BasicAuthPasswordKey] { + required = []string{corev1.BasicAuthUsernameKey} + } + } + for _, k := range required { + if !present[k] { + errs = append(errs, field.Required(field.NewPath("data").Key(k), fmt.Sprintf("needed by type %s", s.Type))) + } + } + return errs +} + +func checkDataKeys(path *field.Path, keys []string, otherPath *field.Path, otherKeys []string) field.ErrorList { + var errs field.ErrorList + other := map[string]bool{} + for _, k := range otherKeys { + other[k] = true + } + for _, k := range keys { + for _, msg := range utilvalidation.IsConfigMapKey(k) { + errs = append(errs, field.Invalid(path.Key(k), k, msg)) + } + if other[k] { + errs = append(errs, field.Invalid(otherPath.Key(k), k, "duplicate of key present in "+path.String())) + } + } + return errs +} + +func keysOf(m map[string]string) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + return sortedStrings(keys) +} + +func keysOfBytes(m map[string][]byte) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + return sortedStrings(keys) +} diff --git a/pkg/validate/validate.go b/pkg/validate/validate.go new file mode 100644 index 0000000..0564579 --- /dev/null +++ b/pkg/validate/validate.go @@ -0,0 +1,555 @@ +// Package validate checks rendered manifests before they reach a cluster. +// +// Every rule mirrors something the Kubernetes API server rejects on admission +// (unknown fields, wrong types, invalid names, a selector that doesn't match +// its template, a Job without restartPolicy, ...), so a clean result means +// `kubectl apply` won't fail on the shape of the objects. Built-in kinds are +// decoded strictly into the client-go types; custom resources, whose schemas +// live in their CRDs, only get metadata checks. +package validate + +import ( + "encoding/json" + "fmt" + "reflect" + "regexp" + "sort" + "strings" + + "github.com/cloudticon/ct/pkg/diag" + "github.com/cloudticon/ct/pkg/manifest" + apivalidation "k8s.io/apimachinery/pkg/api/validation" + pathvalidation "k8s.io/apimachinery/pkg/api/validation/path" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation" + k8slabels "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + kjson "k8s.io/apimachinery/pkg/runtime/serializer/json" + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/client-go/kubernetes/scheme" +) + +// Resources validates rendered objects. origin(i) returns the call chain in +// the user's code that registered object i, so each diagnostic points there. +func Resources(resources []manifest.Resource, origin func(i int) []diag.Frame) diag.List { + var list diag.List + for i, res := range resources { + for _, fe := range checkResource(res) { + d := diag.Diagnostic{ + Code: codeFor(fe), + Message: messageFor(fe), + Resource: manifest.Ref(res), + Path: fe.Field, + Hint: hintFor(fe), + } + if origin != nil { + d = d.AtChain(origin(i)) + } + list = append(list, d) + } + } + return list +} + +func messageFor(fe *field.Error) string { + switch fe.Type { + case unknownField: + return fe.Detail + case unknownKind: + if fe.Field == "kind" { + return fe.Detail + } + return fmt.Sprintf("unknown apiVersion %q: %s", fe.BadValue, fe.Detail) + } + return fe.ErrorBody() +} + +// Error types field.Error doesn't have. +const ( + unknownField field.ErrorType = "FieldValueUnknown" + unknownKind field.ErrorType = "KindUnknown" +) + +func codeFor(fe *field.Error) string { + switch fe.Type { + case unknownField: + return diag.CodeUnknownField + case unknownKind: + return diag.CodeUnknownKind + case field.ErrorTypeRequired: + return diag.CodeMissingField + default: + return diag.CodeInvalidValue + } +} + +func hintFor(fe *field.Error) string { + switch { + case fe.Type == unknownField && strings.HasPrefix(fe.Field, "spec.") && strings.Count(fe.Field, ".") == 1: + return "check the field name and nesting; for workloads, container fields (image, ports, env) go under spec.template.spec.containers[]" + case fe.Type == unknownField: + return "check the field name and nesting against the Kubernetes API reference (`kubectl explain`); if your cluster is newer than this ct build, pass --validate=false" + case fe.Type == unknownKind && fe.Field == "kind": + return "if the kind comes from a Kubernetes release newer than this ct build, pass --validate=false" + case strings.HasPrefix(fe.Detail, "expected a string, got"): + return "convert it in code with String(...), quote it in the values file, or pass it with --set-string" + case fe.Field == "metadata.name" && fe.Type == field.ErrorTypeRequired: + return "every object needs a name; factories usually take it as `name`" + case (fe.Field == "metadata.name" || fe.Field == "metadata.namespace") && fe.Type == field.ErrorTypeInvalid: + return "names are lowercase letters, digits and '-' (Services and Namespaces also no '.'), starting and ending with a letter or digit" + } + return "" +} + +var strictDecoder = kjson.NewSerializerWithOptions(kjson.DefaultMetaFactory, scheme.Scheme, scheme.Scheme, + kjson.SerializerOptions{Strict: true}) + +func checkResource(res manifest.Resource) field.ErrorList { + var errs field.ErrorList + apiVersion, _ := res["apiVersion"].(string) + kind, _ := res["kind"].(string) + if apiVersion == "" { + errs = append(errs, field.Required(field.NewPath("apiVersion"), "")) + } + if kind == "" { + errs = append(errs, field.Required(field.NewPath("kind"), "")) + } + meta, ok := res["metadata"].(map[string]interface{}) + if !ok { + return append(errs, field.Required(field.NewPath("metadata"), "metadata.name is needed")) + } + if apiVersion == "" || kind == "" { + return append(errs, checkMetadata(meta, kind, false)...) + } + + gvk := schema.FromAPIVersionAndKind(apiVersion, kind) + if r, ok := removedAPIs[apiVersion+"/"+kind]; ok { + return append(errs, field.Invalid(field.NewPath("apiVersion"), apiVersion, + fmt.Sprintf("%s %s was removed in Kubernetes %s; use %s", apiVersion, kind, r.removedIn, r.replacement))) + } + + builtin := scheme.Scheme.Recognizes(gvk) + if !builtin { + if alternatives := servedAs(gvk); alternatives != nil { + return append(errs, &field.Error{ + Type: unknownKind, + Field: "apiVersion", + BadValue: apiVersion, + Detail: fmt.Sprintf("%s is served as %s", kind, strings.Join(alternatives, " or ")), + }) + } + if gvk.Group == "core" || builtinGroups[gvk.Group] { + detail := fmt.Sprintf("Kubernetes has no kind %q in %s", kind, apiVersion) + if similar := similarKinds(kind); len(similar) > 0 { + detail += fmt.Sprintf("; did you mean %s?", strings.Join(similar, " or ")) + } + return append(errs, &field.Error{Type: unknownKind, Field: "kind", BadValue: kind, Detail: detail}) + } + } + errs = append(errs, checkMetadata(meta, kind, builtin)...) + if !builtin { + return append(errs, checkCustom(res, gvk)...) + } + + obj, decodeErrs := decodeStrict(res) + errs = append(errs, decodeErrs...) + if obj != nil { + errs = append(errs, checkTyped(obj)...) + } + return errs +} + +func checkMetadata(meta map[string]interface{}, kind string, builtin bool) field.ErrorList { + var errs field.ErrorList + metaPath := field.NewPath("metadata") + + name, _ := meta["name"].(string) + if name == "" { + detail := "" + if _, ok := meta["generateName"]; ok { + detail = "ct tracks objects by name; generateName is not supported" + } + errs = append(errs, field.Required(metaPath.Child("name"), detail)) + } else { + for _, msg := range nameValidator(kind, builtin)(name, false) { + errs = append(errs, field.Invalid(metaPath.Child("name"), name, msg)) + } + if kind == "CronJob" && builtin && len(name) > 52 { + errs = append(errs, field.TooLong(metaPath.Child("name"), name, 52)) + } + } + if ns, ok := meta["namespace"].(string); ok && ns != "" { + for _, msg := range apivalidation.ValidateNamespaceName(ns, false) { + errs = append(errs, field.Invalid(metaPath.Child("namespace"), ns, msg)) + } + } + + // Built-in kinds get type errors from strict decoding; report them here + // only for custom resources. + labels, labelErrs := stringMap(meta["labels"], metaPath.Child("labels")) + annotations, annotationErrs := stringMap(meta["annotations"], metaPath.Child("annotations")) + if !builtin { + errs = append(errs, labelErrs...) + errs = append(errs, annotationErrs...) + } + errs = append(errs, metav1validation.ValidateLabels(labels, metaPath.Child("labels"))...) + errs = append(errs, apivalidation.ValidateAnnotations(annotations, metaPath.Child("annotations"))...) + return append(errs, checkFinalizers(meta["finalizers"], metaPath.Child("finalizers"))...) +} + +// standardFinalizers may be used without a domain prefix. +var standardFinalizers = map[string]bool{ + "kubernetes": true, + metav1.FinalizerOrphanDependents: true, + metav1.FinalizerDeleteDependents: true, +} + +func checkFinalizers(v interface{}, path *field.Path) field.ErrorList { + list, ok := v.([]interface{}) + if !ok { + return nil // absent, or a type error strict decoding reports + } + var names []string + var errs field.ErrorList + for i, item := range list { + name, ok := item.(string) + if !ok { + continue + } + names = append(names, name) + if !strings.Contains(name, "/") && !standardFinalizers[name] { + errs = append(errs, field.Invalid(path.Index(i), name, + "name is neither a standard finalizer name nor is it fully qualified (use /, e.g. example.com/cleanup)")) + } + } + return append(apivalidation.ValidateFinalizers(names, path), errs...) +} + +// nameValidator returns the API server's name rule for a kind. +func nameValidator(kind string, builtin bool) apivalidation.ValidateNameFunc { + switch { + case !builtin: + return apivalidation.NameIsDNSSubdomain + case kind == "CertificateSigningRequest": + return func(string, bool) []string { return nil } // any name is accepted + case kind == "Namespace": + return apivalidation.ValidateNamespaceName + case kind == "Service": + return apivalidation.NameIsDNS1035Label + case kind == "Role" || kind == "ClusterRole" || kind == "RoleBinding" || kind == "ClusterRoleBinding": + return pathvalidation.ValidatePathSegmentName + default: + return apivalidation.NameIsDNSSubdomain + } +} + +func stringMap(v interface{}, path *field.Path) (map[string]string, field.ErrorList) { + if v == nil { + return nil, nil + } + m, ok := v.(map[string]interface{}) + if !ok { + return nil, field.ErrorList{field.Invalid(path, fmt.Sprintf("%T", v), "must be an object of strings")} + } + out := make(map[string]string, len(m)) + var errs field.ErrorList + for _, k := range sortedKeys(m) { + s, ok := m[k].(string) + if !ok { + errs = append(errs, field.Invalid(path.Key(k), m[k], "must be a string; quote numbers and booleans")) + continue + } + out[k] = s + } + return out, errs +} + +func sortedKeys(m map[string]interface{}) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +// servedAs lists the apiVersions a built-in kind is served under when the +// requested apiVersion is wrong (e.g. ConfigMap as "core/v1"). It returns nil +// for groups Kubernetes doesn't define, which belong to custom resources: +// serving.knative.dev/v1 Service is not a mistake for v1 Service. +func servedAs(gvk schema.GroupVersionKind) []string { + if gvk.Group != "core" && !builtinGroups[gvk.Group] { + return nil + } + var versions []string + for known := range scheme.Scheme.AllKnownTypes() { + if known.Kind != gvk.Kind || known.Version == runtime.APIVersionInternal { + continue + } + apiVersion := known.GroupVersion().String() + if _, removed := removedAPIs[apiVersion+"/"+known.Kind]; removed || !isStable(known.Version) { + continue + } + versions = append(versions, apiVersion) + } + sort.Strings(versions) + return versions +} + +var builtinGroups = func() map[string]bool { + groups := map[string]bool{} + for gvk := range scheme.Scheme.AllKnownTypes() { + groups[gvk.Group] = true + } + return groups +}() + +// similarKinds suggests built-in kinds for a misspelled one: same name in +// another case, or within two edits. +func similarKinds(kind string) []string { + seen := map[string]bool{} + var out []string + for known := range scheme.Scheme.AllKnownTypes() { + k := known.Kind + if seen[k] || known.Version == runtime.APIVersionInternal || strings.HasSuffix(k, "List") || strings.HasSuffix(k, "Options") { + continue + } + seen[k] = true + if strings.EqualFold(k, kind) || editDistance(strings.ToLower(k), strings.ToLower(kind)) <= 2 { + out = append(out, fmt.Sprintf("%q", k)) + } + } + sort.Strings(out) + return out +} + +func editDistance(a, b string) int { + prev := make([]int, len(b)+1) + for j := range prev { + prev[j] = j + } + for i := 1; i <= len(a); i++ { + cur := make([]int, len(b)+1) + cur[0] = i + for j := 1; j <= len(b); j++ { + cost := 1 + if a[i-1] == b[j-1] { + cost = 0 + } + cur[j] = min(prev[j]+1, cur[j-1]+1, prev[j-1]+cost) + } + prev = cur + } + return prev[len(b)] +} + +func isStable(version string) bool { + return !strings.Contains(version, "alpha") && !strings.Contains(version, "beta") +} + +type removal struct{ removedIn, replacement string } + +// removedAPIs are apiVersion/kind pairs no supported Kubernetes release serves +// any more, even though client-go still knows their Go types. +var removedAPIs = map[string]removal{} + +func init() { + add := func(removedIn, replacement string, apiVersion string, kinds ...string) { + for _, k := range kinds { + removedAPIs[apiVersion+"/"+k] = removal{removedIn, replacement} + } + } + add("1.16", "apps/v1", "extensions/v1beta1", "Deployment", "DaemonSet", "ReplicaSet") + add("1.16", "networking.k8s.io/v1", "extensions/v1beta1", "NetworkPolicy") + add("1.16", "apps/v1", "apps/v1beta1", "Deployment", "StatefulSet", "ReplicaSet", "ControllerRevision") + add("1.16", "apps/v1", "apps/v1beta2", "Deployment", "StatefulSet", "DaemonSet", "ReplicaSet", "ControllerRevision") + add("1.22", "networking.k8s.io/v1", "extensions/v1beta1", "Ingress") + add("1.22", "networking.k8s.io/v1", "networking.k8s.io/v1beta1", "Ingress", "IngressClass") + add("1.22", "rbac.authorization.k8s.io/v1", "rbac.authorization.k8s.io/v1beta1", "Role", "RoleBinding", "ClusterRole", "ClusterRoleBinding") + add("1.22", "apiextensions.k8s.io/v1", "apiextensions.k8s.io/v1beta1", "CustomResourceDefinition") + add("1.22", "admissionregistration.k8s.io/v1", "admissionregistration.k8s.io/v1beta1", "MutatingWebhookConfiguration", "ValidatingWebhookConfiguration") + add("1.22", "apiregistration.k8s.io/v1", "apiregistration.k8s.io/v1beta1", "APIService") + add("1.22", "certificates.k8s.io/v1", "certificates.k8s.io/v1beta1", "CertificateSigningRequest") + add("1.22", "coordination.k8s.io/v1", "coordination.k8s.io/v1beta1", "Lease") + add("1.22", "scheduling.k8s.io/v1", "scheduling.k8s.io/v1beta1", "PriorityClass") + add("1.22", "storage.k8s.io/v1", "storage.k8s.io/v1beta1", "CSIDriver", "CSINode", "StorageClass", "VolumeAttachment") + add("1.25", "batch/v1", "batch/v1beta1", "CronJob") + add("1.25", "discovery.k8s.io/v1", "discovery.k8s.io/v1beta1", "EndpointSlice") + add("1.25", "events.k8s.io/v1", "events.k8s.io/v1beta1", "Event") + add("1.25", "autoscaling/v2", "autoscaling/v2beta1", "HorizontalPodAutoscaler") + add("1.25", "policy/v1", "policy/v1beta1", "PodDisruptionBudget") + add("1.25", "Pod Security Admission", "policy/v1beta1", "PodSecurityPolicy") + add("1.25", "Pod Security Admission", "extensions/v1beta1", "PodSecurityPolicy") + add("1.25", "node.k8s.io/v1", "node.k8s.io/v1beta1", "RuntimeClass") + add("1.26", "autoscaling/v2", "autoscaling/v2beta2", "HorizontalPodAutoscaler") + add("1.26", "flowcontrol.apiserver.k8s.io/v1", "flowcontrol.apiserver.k8s.io/v1beta1", "FlowSchema", "PriorityLevelConfiguration") + add("1.27", "storage.k8s.io/v1", "storage.k8s.io/v1beta1", "CSIStorageCapacity") + add("1.29", "flowcontrol.apiserver.k8s.io/v1", "flowcontrol.apiserver.k8s.io/v1beta2", "FlowSchema", "PriorityLevelConfiguration") + add("1.32", "flowcontrol.apiserver.k8s.io/v1", "flowcontrol.apiserver.k8s.io/v1beta3", "FlowSchema", "PriorityLevelConfiguration") +} + +// decodeStrict decodes a built-in object the way the API server does. Type +// errors stop a decode, so each offending field is reported and removed, and +// decoding is retried to surface every problem in one run. +func decodeStrict(res manifest.Resource) (runtime.Object, field.ErrorList) { + var errs field.ErrorList + work := deepCopy(res).(map[string]interface{}) + for attempt := 0; attempt < 50; attempt++ { + data, err := json.Marshal(work) + if err != nil { + return nil, append(errs, field.InternalError(nil, err)) + } + obj, _, err := strictDecoder.Decode(data, nil, nil) + if err == nil { + return obj, errs + } + if strictErr, ok := runtime.AsStrictDecodingError(err); ok { + for _, e := range strictErr.Errors() { + errs = append(errs, strictFieldError(e.Error())) + } + return obj, errs + } + if m := typeErrorRe.FindStringSubmatch(err.Error()); m != nil { + path := m[2] + errs = append(errs, &field.Error{ + Type: field.ErrorTypeInvalid, + Field: path, + BadValue: field.OmitValueType{}, + Detail: fmt.Sprintf("expected %s, got %s", jsonTypeName(m[3]), m[1]), + }) + if !deletePath(work, strings.Split(path, ".")) { + return nil, errs + } + continue + } + detail := err.Error() + if strings.Contains(detail, "illegal base64") { + detail = "Secret data values must be base64-encoded; put plain text in stringData instead" + } + return nil, append(errs, &field.Error{Type: field.ErrorTypeInvalid, BadValue: field.OmitValueType{}, Detail: detail}) + } + return nil, errs +} + +// typeErrorRe matches sigs.k8s.io/json type errors, e.g. `json: cannot +// unmarshal string into Go struct field DeploymentSpec.spec.replicas of type int32`. +var typeErrorRe = regexp.MustCompile(`cannot unmarshal (.+?) into Go struct field \w+\.(\S+) of type (\S+)`) + +var unknownFieldRe = regexp.MustCompile(`^unknown field "(.+)"$`) + +func strictFieldError(msg string) *field.Error { + if m := unknownFieldRe.FindStringSubmatch(msg); m != nil { + return &field.Error{Type: unknownField, Field: m[1], BadValue: field.OmitValueType{}, Detail: "unknown field"} + } + return &field.Error{Type: field.ErrorTypeInvalid, BadValue: field.OmitValueType{}, Detail: msg} +} + +func jsonTypeName(goType string) string { + goType = strings.TrimLeft(goType, "*") + switch { + case strings.HasPrefix(goType, "int"), strings.HasPrefix(goType, "uint"): + return "an integer" + case strings.HasPrefix(goType, "float"): + return "a number" + case goType == "string": + return "a string" + case goType == "bool": + return "a boolean" + case strings.HasPrefix(goType, "[]"): + return "an array" + case strings.HasPrefix(goType, "map["): + return "an object" + default: + return goType + } +} + +// deletePath removes a dotted path, fanning out over arrays (type error paths +// carry no indexes). It reports whether anything was removed. +func deletePath(v interface{}, path []string) bool { + switch val := v.(type) { + case []interface{}: + removed := false + for _, item := range val { + removed = deletePath(item, path) || removed + } + return removed + case map[string]interface{}: + if len(path) == 1 { + _, ok := val[path[0]] + delete(val, path[0]) + return ok + } + next, ok := val[path[0]] + return ok && deletePath(next, path[1:]) + } + return false +} + +func deepCopy(v interface{}) interface{} { + switch val := v.(type) { + case map[string]interface{}: + out := make(map[string]interface{}, len(val)) + for k, item := range val { + out[k] = deepCopy(item) + } + return out + case []interface{}: + out := make([]interface{}, len(val)) + for i, item := range val { + out[i] = deepCopy(item) + } + return out + default: + return v + } +} + +// checkCustom covers custom resources and kinds outside client-go's scheme. +func checkCustom(res manifest.Resource, gvk schema.GroupVersionKind) field.ErrorList { + if gvk.Group != "apiextensions.k8s.io" || gvk.Kind != "CustomResourceDefinition" { + return nil + } + spec, _ := res["spec"].(map[string]interface{}) + group, _ := spec["group"].(string) + names, _ := spec["names"].(map[string]interface{}) + plural, _ := names["plural"].(string) + meta, _ := res["metadata"].(map[string]interface{}) + name, _ := meta["name"].(string) + if group == "" || plural == "" || name == "" { + return nil + } + if want := plural + "." + group; name != want { + return field.ErrorList{field.Invalid(field.NewPath("metadata", "name"), name, + fmt.Sprintf("must be spec.names.plural + \".\" + spec.group (%q)", want))} + } + return nil +} + +// labelSelectorMatches reports whether sel selects objects carrying labels. +func labelSelectorMatches(sel *metav1.LabelSelector, labels map[string]string) (bool, error) { + s, err := metav1.LabelSelectorAsSelector(sel) + if err != nil { + return false, err + } + return s.Matches(k8slabels.Set(labels)), nil +} + +func sortedStrings(s []string) []string { + sort.Strings(s) + return s +} + +// countSet counts non-nil pointer fields of a struct, e.g. how many sources a +// corev1.VolumeSource names. +func countSet(v interface{}) int { + rv := reflect.ValueOf(v) + n := 0 + for i := 0; i < rv.NumField(); i++ { + if f := rv.Field(i); f.Kind() == reflect.Pointer && !f.IsNil() { + n++ + } + } + return n +} diff --git a/pkg/validate/validate_test.go b/pkg/validate/validate_test.go new file mode 100644 index 0000000..e7acf9a --- /dev/null +++ b/pkg/validate/validate_test.go @@ -0,0 +1,322 @@ +package validate_test + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/cloudticon/ct/pkg/diag" + "github.com/cloudticon/ct/pkg/manifest" + "github.com/cloudticon/ct/pkg/validate" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// obj parses a JSON manifest the way the engine hands them over. +func obj(t *testing.T, js string) manifest.Resource { + t.Helper() + var res manifest.Resource + require.NoError(t, json.Unmarshal([]byte(js), &res), js) + return res +} + +func validateOne(t *testing.T, js string) diag.List { + t.Helper() + return validate.Resources([]manifest.Resource{obj(t, js)}, nil) +} + +const deployment = `{ + "apiVersion": "apps/v1", "kind": "Deployment", + "metadata": {"name": "web", "namespace": "prod", "labels": {"app": "web"}}, + "spec": { + "replicas": 2, + "selector": {"matchLabels": {"app": "web"}}, + "template": { + "metadata": {"labels": {"app": "web", "tier": "frontend"}}, + "spec": { + "containers": [{ + "name": "web", "image": "nginx:1.27", + "ports": [{"name": "http", "containerPort": 8080}], + "volumeMounts": [{"name": "tmp", "mountPath": "/tmp"}], + "resources": {"requests": {"cpu": "100m", "memory": 128974848}} + }], + "volumes": [{"name": "tmp", "emptyDir": {}}] + } + } + } +}` + +func TestValidate_AcceptsValidObjects(t *testing.T) { + valid := []string{ + deployment, + `{"apiVersion": "v1", "kind": "Service", "metadata": {"name": "web"}, "spec": {"selector": {"app": "web"}, "ports": [{"port": 80, "targetPort": "http"}]}}`, + `{"apiVersion": "v1", "kind": "Service", "metadata": {"name": "db"}, "spec": {"clusterIP": "None", "selector": {"app": "db"}}}`, + `{"apiVersion": "v1", "kind": "Service", "metadata": {"name": "ext"}, "spec": {"type": "ExternalName", "externalName": "db.example.com"}}`, + `{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "cfg"}, "data": {"app.properties": "a=b", "LOG_LEVEL": "info"}}`, + `{"apiVersion": "v1", "kind": "Secret", "metadata": {"name": "s"}, "stringData": {"password": "plain"}, "data": {"token": "c2VjcmV0"}}`, + `{"apiVersion": "v1", "kind": "Secret", "metadata": {"name": "tls"}, "type": "kubernetes.io/tls", "data": {"tls.crt": "Y3J0", "tls.key": "a2V5"}}`, + `{"apiVersion": "v1", "kind": "Namespace", "metadata": {"name": "team-a"}}`, + `{"apiVersion": "rbac.authorization.k8s.io/v1", "kind": "ClusterRole", "metadata": {"name": "system:aggregate-to-view"}, "rules": [{"apiGroups": [""], "resources": ["pods"], "verbs": ["get"]}]}`, + `{"apiVersion": "networking.k8s.io/v1", "kind": "Ingress", "metadata": {"name": "web"}, "spec": {"rules": [{"host": "a.example.com", "http": {"paths": [{"path": "/", "pathType": "Prefix", "backend": {"service": {"name": "web", "port": {"number": 80}}}}]}}]}}`, + `{"apiVersion": "autoscaling/v2", "kind": "HorizontalPodAutoscaler", "metadata": {"name": "web"}, "spec": {"scaleTargetRef": {"apiVersion": "apps/v1", "kind": "Deployment", "name": "web"}, "minReplicas": 2, "maxReplicas": 5}}`, + `{"apiVersion": "policy/v1", "kind": "PodDisruptionBudget", "metadata": {"name": "web"}, "spec": {"minAvailable": 1, "selector": {"matchLabels": {"app": "web"}}}}`, + `{"apiVersion": "batch/v1", "kind": "Job", "metadata": {"name": "migrate"}, "spec": {"template": {"spec": {"restartPolicy": "Never", "containers": [{"name": "m", "image": "app:1"}]}}}}`, + `{"apiVersion": "batch/v1", "kind": "CronJob", "metadata": {"name": "nightly"}, "spec": {"schedule": "0 3 * * *", "jobTemplate": {"spec": {"template": {"spec": {"restartPolicy": "OnFailure", "containers": [{"name": "c", "image": "app:1"}]}}}}}}`, + `{"apiVersion": "networking.k8s.io/v1", "kind": "NetworkPolicy", "metadata": {"name": "allow-all"}, "spec": {"podSelector": {}, "ingress": [{}]}}`, + // The API server defaults a volume without a source to emptyDir. + strings.Replace(deployment, `{"name": "tmp", "emptyDir": {}}`, `{"name": "tmp"}`, 1), + // StatefulSet containers may mount volumeClaimTemplates. + `{"apiVersion": "apps/v1", "kind": "StatefulSet", "metadata": {"name": "db"}, "spec": {"serviceName": "db", "selector": {"matchLabels": {"app": "db"}}, "volumeClaimTemplates": [{"metadata": {"name": "data"}, "spec": {"accessModes": ["ReadWriteOnce"], "resources": {"requests": {"storage": "1Gi"}}}}], "template": {"metadata": {"labels": {"app": "db"}}, "spec": {"containers": [{"name": "db", "image": "postgres:17", "volumeMounts": [{"name": "data", "mountPath": "/var/lib/postgresql"}]}]}}}}`, + // targetPort "" defaults to port; clusterIPs [None] is headless. + `{"apiVersion": "v1", "kind": "Service", "metadata": {"name": "web2"}, "spec": {"ports": [{"port": 80, "targetPort": ""}]}}`, + `{"apiVersion": "v1", "kind": "Service", "metadata": {"name": "db2"}, "spec": {"clusterIPs": ["None"], "selector": {"app": "db"}}}`, + // Native sidecars: init containers with restartPolicy Always. + strings.Replace(deployment, `"containers": [`, `"initContainers": [{"name": "proxy", "image": "envoy:1", "restartPolicy": "Always"}], "containers": [`, 1), + `{"apiVersion": "certificates.k8s.io/v1", "kind": "CertificateSigningRequest", "metadata": {"name": "User:Alice"}, "spec": {"request": "Y3Ny", "signerName": "kubernetes.io/kube-apiserver-client", "usages": ["client auth"]}}`, + // Custom resources: only metadata is checked. + `{"apiVersion": "serving.knative.dev/v1", "kind": "Service", "metadata": {"name": "hello"}, "spec": {"template": {"spec": {"containers": [{"image": "x"}]}}}}`, + `{"apiVersion": "cert-manager.io/v1", "kind": "Certificate", "metadata": {"name": "web-tls"}, "spec": {"anything": {"goes": true}}}`, + `{"apiVersion": "apiextensions.k8s.io/v1", "kind": "CustomResourceDefinition", "metadata": {"name": "widgets.example.com"}, "spec": {"group": "example.com", "names": {"kind": "Widget", "plural": "widgets"}}}`, + } + for _, js := range valid { + res := obj(t, js) + t.Run(manifest.Ref(res), func(t *testing.T) { + assert.Empty(t, validate.Resources([]manifest.Resource{res}, nil)) + }) + } +} + +type want struct { + code, path, message string +} + +func assertDiagnostics(t *testing.T, got diag.List, wants ...want) { + t.Helper() + require.Len(t, got, len(wants), "got: %v", got) + for i, w := range wants { + assert.Equal(t, w.code, got[i].Code, "diagnostic %d: %s", i, got[i]) + assert.Equal(t, w.path, got[i].Path, "diagnostic %d: %s", i, got[i]) + assert.Contains(t, got[i].Message, w.message, "diagnostic %d: %s", i, got[i]) + } +} + +func TestValidate_Rejects(t *testing.T) { + cases := []struct { + name string + js string + wants []want + }{ + { + "ConfigMap data under spec", + `{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "cfg"}, "spec": {"data": {"a": "b"}}}`, + []want{{diag.CodeUnknownField, "spec", "unknown field"}}, + }, + { + "core/v1 is not an apiVersion", + `{"apiVersion": "core/v1", "kind": "ConfigMap", "metadata": {"name": "cfg"}}`, + []want{{diag.CodeUnknownKind, "apiVersion", `unknown apiVersion "core/v1": ConfigMap is served as v1`}}, + }, + { + "wrong version of a built-in group", + `{"apiVersion": "apps/v2", "kind": "Deployment", "metadata": {"name": "web"}}`, + []want{{diag.CodeUnknownKind, "apiVersion", "Deployment is served as apps/v1"}}, + }, + { + "removed API version", + `{"apiVersion": "extensions/v1beta1", "kind": "Ingress", "metadata": {"name": "web"}}`, + []want{{diag.CodeInvalidValue, "apiVersion", "removed in Kubernetes 1.22; use networking.k8s.io/v1"}}, + }, + { + "container fields directly on the Deployment spec", + `{"apiVersion": "apps/v1", "kind": "Deployment", "metadata": {"name": "web"}, "spec": {"image": "nginx", "replicas": "3", "selector": {"matchLabels": {"app": "web"}}, "template": {"metadata": {"labels": {"app": "web"}}, "spec": {"containers": [{"name": "web", "image": "nginx"}]}}}}`, + []want{ + {diag.CodeInvalidValue, "spec.replicas", "expected an integer, got string"}, + {diag.CodeUnknownField, "spec.image", "unknown field"}, + }, + }, + { + "typo in a nested field", + strings.Replace(deployment, `"containerPort": 8080`, `"containerPort": 8080, "protocl": "TCP"`, 1), + []want{{diag.CodeUnknownField, "spec.template.spec.containers[0].ports[0].protocl", "unknown field"}}, + }, + { + "selector doesn't match template labels", + strings.Replace(deployment, `"matchLabels": {"app": "web"}`, `"matchLabels": {"app": "api"}`, 1), + []want{{diag.CodeInvalidValue, "spec.template.metadata.labels", "`selector` does not match template `labels`"}}, + }, + { + "missing selector, containers", + `{"apiVersion": "apps/v1", "kind": "Deployment", "metadata": {"name": "web"}, "spec": {"template": {"spec": {}}}}`, + []want{ + {diag.CodeMissingField, "spec.selector", "Required value"}, + {diag.CodeMissingField, "spec.template.spec.containers", "Required value"}, + }, + }, + { + "container problems", + strings.NewReplacer(`"image": "nginx:1.27"`, `"image": ""`, `"name": "http"`, `"name": "http-metrics-port"`, `{"name": "tmp", "mountPath": "/tmp"}`, `{"name": "data", "mountPath": "/data"}`).Replace(deployment), + []want{ + {diag.CodeMissingField, "spec.template.spec.containers[0].image", "Required value"}, + {diag.CodeInvalidValue, "spec.template.spec.containers[0].ports[0].name", "must be no more than 15 characters"}, + {diag.CodeInvalidValue, "spec.template.spec.containers[0].volumeMounts[0].name", "Not found"}, + }, + }, + { + "volume with two sources", + strings.Replace(deployment, `{"name": "tmp", "emptyDir": {}}`, `{"name": "tmp", "emptyDir": {}, "configMap": {"name": "x"}}`, 1), + []want{{diag.CodeInvalidValue, "spec.template.spec.volumes[0]", "may not specify more than 1 volume type"}}, + }, + { + "misspelled built-in kinds", + `{"apiVersion": "apps/v1", "kind": "Deploymnet", "metadata": {"name": "web"}, "spec": {"junk": 1}}`, + []want{{diag.CodeUnknownKind, "kind", `no kind "Deploymnet" in apps/v1; did you mean "Deployment"?`}}, + }, + { + "wrong case of a core kind", + `{"apiVersion": "v1", "kind": "Configmap", "metadata": {"name": "cfg"}}`, + []want{{diag.CodeUnknownKind, "kind", `did you mean "ConfigMap"?`}}, + }, + { + "fractional number in an integer field doesn't hide later errors", + strings.NewReplacer(`"replicas": 2`, `"replicas": 1.5`, `"image": "nginx:1.27",`, `"image": "nginx:1.27", "env": [{"name": "A", "value": 3}],`).Replace(deployment), + []want{ + {diag.CodeInvalidValue, "spec.replicas", "expected an integer, got number 1.5"}, + {diag.CodeInvalidValue, "spec.template.spec.containers.env.value", "expected a string, got number"}, + }, + }, + { + "Deployment with restartPolicy Never", + strings.Replace(deployment, `"containers": [`, `"restartPolicy": "Never", "containers": [`, 1), + []want{{diag.CodeInvalidValue, "spec.template.spec.restartPolicy", `Unsupported value: "Never"`}}, + }, + { + "Job without restartPolicy", + `{"apiVersion": "batch/v1", "kind": "Job", "metadata": {"name": "migrate"}, "spec": {"template": {"spec": {"containers": [{"name": "m", "image": "app:1"}]}}}}`, + []want{{diag.CodeInvalidValue, "spec.template.spec.restartPolicy", `supported values: "OnFailure", "Never"`}}, + }, + { + "CronJob name too long and no schedule", + `{"apiVersion": "batch/v1", "kind": "CronJob", "metadata": {"name": "` + strings.Repeat("a", 53) + `"}, "spec": {"jobTemplate": {"spec": {"template": {"spec": {"restartPolicy": "Never", "containers": [{"name": "c", "image": "x"}]}}}}}}`, + []want{ + {diag.CodeInvalidValue, "metadata.name", "may not be more than 52"}, + {diag.CodeMissingField, "spec.schedule", "Required value"}, + }, + }, + { + "Service ports", + `{"apiVersion": "v1", "kind": "Service", "metadata": {"name": "web"}, "spec": {"ports": [{"port": 80}, {"port": 70000, "targetPort": "a-very-long-port-name"}]}}`, + []want{ + {diag.CodeMissingField, "spec.ports[0].name", "more than one port"}, + {diag.CodeInvalidValue, "spec.ports[1].port", "between 1 and 65535"}, + {diag.CodeMissingField, "spec.ports[1].name", "more than one port"}, + {diag.CodeInvalidValue, "spec.ports[1].targetPort", "no more than 15 characters"}, + }, + }, + { + "Service without ports", + `{"apiVersion": "v1", "kind": "Service", "metadata": {"name": "web"}, "spec": {"selector": {"app": "web"}}}`, + []want{{diag.CodeMissingField, "spec.ports", "Required value"}}, + }, + { + "Ingress path without pathType", + `{"apiVersion": "networking.k8s.io/v1", "kind": "Ingress", "metadata": {"name": "web"}, "spec": {"rules": [{"http": {"paths": [{"path": "/", "backend": {"service": {"name": "web", "port": {"number": 80}}}}]}}]}}`, + []want{{diag.CodeMissingField, "spec.rules[0].http.paths[0].pathType", "Required value"}}, + }, + { + "Secret data not base64", + `{"apiVersion": "v1", "kind": "Secret", "metadata": {"name": "s"}, "data": {"password": "plain text!"}}`, + []want{{diag.CodeInvalidValue, "", "put plain text in stringData"}}, + }, + { + "TLS Secret without key", + `{"apiVersion": "v1", "kind": "Secret", "metadata": {"name": "tls"}, "type": "kubernetes.io/tls", "stringData": {"tls.crt": "x"}}`, + []want{{diag.CodeMissingField, "data[tls.key]", "Required value"}}, + }, + { + "invalid names", + `{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "My_Config", "namespace": "Prod"}}`, + []want{ + {diag.CodeInvalidValue, "metadata.name", "RFC 1123 subdomain"}, + {diag.CodeInvalidValue, "metadata.namespace", "RFC 1123 label"}, + }, + }, + { + "Service name must start with a letter", + `{"apiVersion": "v1", "kind": "Service", "metadata": {"name": "1web"}, "spec": {"ports": [{"port": 80}]}}`, + []want{{diag.CodeInvalidValue, "metadata.name", "DNS-1035 label"}}, + }, + { + "missing name", + `{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"generateName": "cfg-"}}`, + []want{{diag.CodeMissingField, "metadata.name", "generateName is not supported"}}, + }, + { + "bad labels on a built-in kind", + `{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "cfg", "labels": {"my label": "x", "version": 2}}}`, + []want{ + {diag.CodeInvalidValue, "metadata.labels", "name part must consist of alphanumeric"}, + {diag.CodeInvalidValue, "metadata.labels", "expected a string, got number"}, + }, + }, + { + "bad labels on a custom resource", + `{"apiVersion": "example.com/v1", "kind": "Widget", "metadata": {"name": "w", "labels": {"version": 2}}}`, + []want{{diag.CodeInvalidValue, "metadata.labels[version]", "must be a string"}}, + }, + { + "finalizer without a domain", + `{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "cfg", "finalizers": ["foo", "example.com/cleanup", "kubernetes"]}}`, + []want{{diag.CodeInvalidValue, "metadata.finalizers[0]", "neither a standard finalizer name nor is it fully qualified"}}, + }, + { + "CRD name must be plural.group", + `{"apiVersion": "apiextensions.k8s.io/v1", "kind": "CustomResourceDefinition", "metadata": {"name": "widget"}, "spec": {"group": "example.com", "names": {"kind": "Widget", "plural": "widgets"}}}`, + []want{{diag.CodeInvalidValue, "metadata.name", `"widgets.example.com"`}}, + }, + { + "no apiVersion, kind or metadata", + `{"spec": {}}`, + []want{ + {diag.CodeMissingField, "apiVersion", "Required value"}, + {diag.CodeMissingField, "kind", "Required value"}, + {diag.CodeMissingField, "metadata", "Required value"}, + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assertDiagnostics(t, validateOne(t, tc.js), tc.wants...) + }) + } +} + +func TestValidate_PointsAtOrigin(t *testing.T) { + resources := []manifest.Resource{ + obj(t, `{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "ok"}}`), + obj(t, `{"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "bad"}, "spec": {}}`), + } + origins := [][]diag.Frame{ + {{File: "main.ct", Line: 3, Column: 1}}, + {{File: "lib/cm.ct", Line: 2, Column: 3}, {File: "main.ct", Line: 7, Column: 1}}, + } + + got := validate.Resources(resources, func(i int) []diag.Frame { return origins[i] }) + + require.Len(t, got, 1) + assert.Equal(t, "lib/cm.ct", got[0].File) + assert.Equal(t, 2, got[0].Line) + assert.Equal(t, []diag.Frame{{File: "main.ct", Line: 7, Column: 1}}, got[0].Stack) + assert.Equal(t, "unknown field", got[0].Message) + assert.Equal(t, `ConfigMap "bad"`, got[0].Resource) + assert.NotEmpty(t, got[0].Hint) +} + +func TestValidate_DoesNotMutateInput(t *testing.T) { + res := obj(t, `{"apiVersion": "apps/v1", "kind": "Deployment", "metadata": {"name": "web"}, "spec": {"replicas": "3"}}`) + before, _ := json.Marshal(res) + + validate.Resources([]manifest.Resource{res}, nil) + + after, _ := json.Marshal(res) + assert.JSONEq(t, string(before), string(after)) +}