GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Caproni
  • Getting started
  • For GitLab
  • Source
  • Edit this page →

This view

  • Original page
  • New address

GeezerVison is showing gitlab-org.gitlab.io — Architecture

Contributing
Architecture

Architecture

Caproni is a general-purpose CLI for orchestrating local Kubernetes development environments. It is a deployment orchestrator, not a configuration generator: it points Helm at charts, passes values files through, and sequences the workflow. Helm is the sole source of truth for application configuration. Caproni knows nothing about GitLab, webservice, gitaly, or any other specific application.

Goal: close the gap between local development and production Kubernetes by composing open, standard cloud-native tools (Helm, Kubernetes, mirrord, Skaffold, k3d, Colima) rather than inventing proprietary abstractions. The plugin registry pattern means new tools and workflows can be added without changing the core.

Lesson from GDK: tight coupling to a single application turns a developer tool into a maintenance burden for every feature team. Caproni deliberately avoids that path — every design decision is evaluated against whether it would work for a team unrelated to GitLab.

Test question for every feature: “Could the Switchboard team use this feature without modification?”

If no, redesign.


Related documentation

FileCovers
AGENTS.mdDevelopment conventions, mock generation, commit rules
docs/design/*.mdPer-feature design documents
docs/configuration.mdFull configuration reference
.gitlab/duo/mr-review-instructions.yamlCode review standards

Non-negotiable design rules

  1. Application-agnostic. No hardcoded resource names, namespaces, or secrets. All application-specific knowledge lives in caproni.yaml.

  2. Config in caproni.yaml, not env vars. os.Getenv() is never used for application config. Env vars bypass schema validation, discovery, and caproni config migrate. Exception: meta-config that controls which config file to load.

  3. Helm-first. Caproni must not become a fourth configuration system alongside Omnibus, Helm Charts, and GDK. It does not generate manifests, template application config, or translate between formats.

  4. No business logic in cmd/. cmd/ packages wire CLI flags to internal/ calls. Logic that belongs in cmd/ is untestable without the CLI framework.

  5. No global state. Dependencies flow through constructors. Constructors panic on nil dependencies (fail-fast, not silent NPE later).


What caproni up does

1. Generate per-profile dev CA           (internal/pki)
2. Verify create-time settings           (cluster.Verify over the driver's Checks(), NeedProfile)
3. Start the local cluster               (internal/cluster + driver)
4. Wait for the cluster API              (kubectl.WithReadiness polls /readyz)
5. Verify every setting, apply fixes     (cluster.Verify at NeedAPI, then up's policy)
6. Clone git repos for edit-mode         (internal/update)
7. Reload config                         (picks up caproni-project.yaml from freshly-cloned repos)
8. Run edit_mode_prepare hooks           (internal/lifecyclehooks)
9. Deploy all deployers                  (internal/deploy Orchestrator, topological sort on `needs`)

caproni run follows with the reloaders (mirrord, Skaffold).

Cluster verification. Start creates or resumes the cluster; it never compares settings. A driver declares the settings it can compare as cluster.Check values, each with what applying the configured value costs (Remedy: in place, restart, recreate) and what the observation needs (Need: the profile, a running cluster, the API). cluster.Verify runs the checks a caller can satisfy and hands back plain Mismatch data. The policy lives in cmd/up: before Start it runs the profile-level checks, skipping restart-class ones on a stopped cluster; after the readiness wait it runs everything, applies the in-place fixes drivers provide, warns about log-only differences, and fails on the rest with the hint for their remedy. See internal/cluster/README.md.

Cluster verification in doctor. caproni doctor runs the cluster driver’s checks (cluster.Verify over Checks(), see internal/cluster/README.md) in any cluster state and only reports: one warning per difference with what applies the configured value, one per setting it could not read. It never runs a fix.


Directory map

cmd/                        CLI commands — flag parsing, context extraction, delegation only
  factory.go                Wiring: before/after hooks, anonymous imports that trigger init()
internal/
  backends/{git,helm,kubectl,hosts,docker,kustomize}/
                            Stateless wrappers around CLI tools; each has interface.go + client.go + mocks/
  deployer/                 Manager interface + registry; implementations: helm/, kustomize/, namespace/
  reloader/                 Manager interface + registry; implementations: mirror/ (mirrord), skaffold/
  cluster/                  Manager interface + registry; drivers: k3d/, colima/, auto/, external/, vcluster/
  deploy/                   Orchestrator: sequences deployers via topological sort on `needs` graph
  diagnostics/              Automated diagnostics for self-serve troubleshooting
  config/                   Two-level config system (see below)
  executor/                 CommandRunner interface — the single CLI execution abstraction
  kubeconfig/               Materializes kubeconfig YAML into a temp file for injection
  pki/                      Per-profile dev CA generation and loading
  update/                   Git repository update strategies (clone-only, pull)
  lifecyclehooks/           edit_mode_prepare / edit_mode_start / edit_mode_stop
  variables/                Variable resolver: expands ${VAR} across the config tree
  infra/assets/             Embedded Kustomize overlays: builtin:dev-ca, builtin:traefik-tlsstore
  naming/                   Profile name resolution (static hash, directory name)
  registrycache/            Local zot OCI registry cache
schema/config.v2.schema.json   JSON schema for caproni.yaml (validated at config load time)
examples/                   Educational only — not production configs

Core patterns

1. Stateless backends + stateful managers

Backends are thin, stateless wrappers around external tools. Managers orchestrate workflows and hold state; they never call CLI tools directly.

internal/backends/{tool}/
├── interface.go       Backend interface
├── client.go          Implementation
└── mocks/             mockery-generated mocks + for_testing_only.go guard

This is the architectural boundary that makes unit testing possible: inject a mock backend, test the manager’s logic without running real CLI commands.

Never let a manager import a concrete backend type — only the interface.

2. Plugin registries + init() bootstrap

All three domains (deployer, reloader, cluster) use the same registry shape: a map[string]FactoryFunc with Register, NewManager, and ListTypes.

Implementations register in init():

// internal/deployer/helm/manager.go
func init() {
    deployer.Register("helm", func(kubeconfig string) deployer.Manager {
        exec := executor.NewClient()
        return NewManager(helm.NewClient(exec), kubeconfig)
    })
}

cmd/factory.go triggers all registrations with blank imports:

_ "gitlab.com/.../internal/deployer/helm"
_ "gitlab.com/.../internal/deployer/kustomize"
_ "gitlab.com/.../internal/reloader/mirror"
_ "gitlab.com/.../internal/cluster/auto"   // auto also imports colima and k3d

3. Conditionals behind the interface (Strategy pattern)

Platform selection belongs inside an implementation, not in callers:

// internal/cluster/auto — the only place runtime.GOOS appears
func init() {
    cluster.Register("auto", func(cfg types.ClusterConfig, profileName string) cluster.Manager {
        if runtime.GOOS == "linux" {
            return k3d.NewDriver(cfg, profileName)
        }
        return colima.NewDriver(cfg, profileName)
    })
}

Callers use cluster.NewManager(cfg, profileName) with cfg.Driver = "auto" and never branch on OS themselves.

4. Virtual kubeconfig

Caproni never reads from ~/.kube/config. The internal/kubeconfig/ package materializes a kubeconfig YAML string (from the cluster driver’s GetKubeconfig) into a short-lived temp file:

kc, _ := kubeconfig.Create(kubeconfigYAML)
defer kc.Close()
// kc.Environ() returns KUBECONFIG=<tempfile>, KUBECACHEDIR=...

All backends (helm, kubectl) and lifecycle hooks receive kc.Environ(). This isolates Caproni’s clusters from the user’s global kubeconfig and makes concurrent operations safe. No cluster driver may write to ~/.kube/config either, which is why the colima driver passes --activate=false and the k3d driver --kubeconfig-update-default=false.

The one sanctioned exception is caproni set-kube-context, which merges the cluster into the user’s kubeconfig under a profile-derived context name. It is a command the user runs deliberately, never something a Caproni workflow does on their behalf.

5. Executor abstraction

Every shell invocation goes through executor.CommandRunner. This makes backends mockable without shelling out, and enables the mise decorator (wraps commands through mise exec for tool version pinning). No backend calls exec.Command directly.

Backends and drivers get the runner from the context with executor.FromContext(ctx) instead of holding it in a field. FromContext panics if no runner is on the context, so tests must attach the mock first with ctx = executor.WithContext(ctx, mockExec).

6. Infrastructure services as ordinary deployers

Cluster-wide services (cert-manager, ingress controller, the dev CA) are declared by the rig as regular deployers — not composed by Caproni. Caproni embeds two Kustomize overlays reachable via builtin: paths:

  • builtin:dev-ca — dev CA Secret, ClusterIssuer, trust Bundle, wildcard Certificate
  • builtin:traefik-tlsstore — makes the dev cert Traefik’s default TLS store

Both need an explicit deployer declaration to be installed. caproni config print shows exactly what will be installed and in what order.

Do not add new builtin overlays unless they directly enable Caproni’s own functionality. The dev CA and Traefik TLS store exist because HTTPS is a prerequisite for production-like local development — that is Caproni’s core job. Everything else (Postgres operators, cert-manager, ingress controllers) belongs in the rig’s deployer declarations, not in the Caproni binary.


Configuration system

Two levels

LevelTypeStored inRetrieved with
Globalconfig.GlobalConfigcontextconfig.MustFromContext(ctx)
Applicationlatest.CaproniConfigloaded per commandconfig.LoadCaproniConfig(globalCfg)

Load pipeline (11 steps)

  1. Read caproni.yaml
  2. Resolve extends: — recursively merge remote HTTPS fragments (TTL-cached)
  3. Merge caproni.local.yaml on top
  4. Detect version: field
  5. Apply caproni-project.yaml from cloned edit-mode repos
  6. Seed variable resolver from decoded (pre-default) config
  7. Resolve ProfileName via naming strategy (static or directory)
  8. Expand ${VAR} across the entire YAML tree (skipping mirrord regex fields and cluster driver fields)
  9. Validate against schema/config.v2.schema.json (compiled once, embedded in binary)
  10. Unmarshal into latest.CaproniConfig, apply defaults, run upgrade chain
  11. Semantic validation; inject embedded CI tool versions

Schema change checklist

When changing the configuration schema:

  1. schema/config.v2.schema.json — update the schema
  2. internal/config/v2/config.go — update Go types
  3. examples/ — add or update an example; run caproni config validate against it
  4. docs/configuration.md — update the reference if user-visible behavior changes

Only mark fields required if they truly have no sensible default.


Testing

Managers are unit-tested by injecting mock backends. Mocks are generated by mockery (run ./scripts/generate.sh), configured in .mockery.yaml. Every mocks/ directory has a for_testing_only.go guard:

func init() {
    if !testing.Testing() {
        panic("package helm/mocks must only be used in tests")
    }
}

Mocks use regular .go files (not _test.go) to allow cross-package import in tests.

Variadic args in mock expectations — the generated mock packs variadic args into a slice before calling _mock.Called. Pass them as a single slice to EXPECT():

// Correct
mockExec.EXPECT().ReadStdout(ctx, "k3d", []string{"cluster", "list", "-o", "json"}).Return(...)

// Wrong — individual args do not match the recorded []string
mockExec.EXPECT().ReadStdout(ctx, "k3d", "cluster", "list", "-o", "json").Return(...)

internal/cluster.Manager uses a hand-written mock in internal/cluster/mock/ registered programmatically in tests, rather than mockery.


Anti-patterns

Anti-patternWhy it breaks things
Hardcoded resource/secret namesCouples CLI to one application
Generating manifests or config templatesCaproni becomes a fourth config system
Business logic in cmd/Untestable without the CLI framework
Global state / singletonsHidden dependencies, testing hell
os.Getenv() for application configBypasses validation, discovery, migration
Conditionals in front of an interfaceShould live inside an implementation
Raw command output from backendsBackends must return structured data
Capability flags on registriesUse configuration instead (see cluster.<driver>.k3s.disable)
New builtin infrastructure overlaysShip as rig deployers unless they enable Caproni’s own functionality
Last updated on November 17, 2026
Decisions
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.