pgrator
Kubernetes operator for the nais platform that manages Postgres, Valkey, and OpenSearch resources. It reconciles opinionated nais CRDs into the resources needed to run these services on GCP.
Managed resources
| CRD |
API group |
Backend |
Creates |
Postgres |
nais.io/v1 |
CloudNativePG |
CNPG Cluster, Pooler, network and optional WAL archive/backup resources |
PostgresBinding |
nais.io/v1 |
CloudNativePG |
Workload database roles, connection/certificate Secrets and NetworkPolicies |
PostgresAccess |
nais.io/v1 |
CloudNativePG |
Time-limited personal role, credentials, relay mapping and database ingress policy |
Valkey |
nais.io/v1 |
Aiven |
Aiven Valkey instance + ServiceIntegration (metrics) |
OpenSearch |
nais.io/v1 |
Aiven |
Aiven OpenSearch instance + ServiceIntegration (metrics) |
Getting started
Prerequisites
- mise — manages all tool versions and tasks
- Docker — for building images
- A Kubernetes cluster (for e2e tests)
Setup
# Install all tools (Go, golangci-lint, controller-gen, etc.)
mise install
# Run all checks and tests
mise run all
# Run unit and integration tests in both Go modules
mise run test
# Run only linting
mise run check:lint
Available tasks
Use mise tasks to get a list of available tasks, with descriptions
Git hooks
Lefthook is configured for pre-commit (fmt, lint, vet, generate check) and pre-push (tests). Install hooks with:
lefthook install
Architecture
See ARCHITECTURE.md for detailed information about project structure, conventions, and design patterns.
Postgres
Postgres directly owns its CNPG Cluster, Pooler, roles, network policies and, when WAL archiving is enabled, its archive bucket and backups. Physical names keep the historical main component (see ADR 0007), and pods keep the postgres.nais.io/branch: main label used by metrics and Console. Branches are no longer a concept: databases created under the earlier branch model must have completed adoption with the previous release; a database without an ownership checkpoint, or with an unfinished adoption, is rejected.
Point-in-time recovery creates a new, independent Postgres from a source in the same namespace through the immutable spec.recovery (see postgres-pitr.md). It does not modify the source or reconnect workloads.
If CNPG reports an unrecoverable recovery Cluster and a permanently failed full-recovery Job controlled by that Cluster, pgrator persists RecoveryFailed=True with reason Unrecoverable, the Cluster identity, original target, and CNPG phase/reason. CNPG can report Initialized=True before recovery finishes, so initialization alone does not prove success. Jobs are observed read-only; pgrator neither owns nor retries them. It also sets Ready=False and reconcilePhase: Failed. This terminal condition stops resource reconciliation without pruning the failed Cluster or its supporting resources, even if the source archive disappears. Deleting the failed Cluster does not retry recovery. To request another recovery, create a new Postgres with an explicit target; pgrator never adjusts the timestamp automatically. Ordinary readiness failures and later outages without recovery-job failure are not terminal recovery failures; databases with a recorded RecoveryCompleted milestone retain their successful status. A source cannot be deleted while recoveries still depend on its archive.
Deprecated fields, kept for existing objects: Postgres.spec.activeBranch, status.activeBranch and PostgresBinding.spec.branch accept only main (or empty); PostgresAccess.spec.postgresBranch is an immutable legacy reference, new accesses use spec.postgres.
PostgresBinding supplies workloads with a stable connection Secret, NetworkPolicies and DatabaseRoles for a Postgres.
Application database and extensions
Every database gets a CNPG Database named <cluster-name>-app that declares the app database created at bootstrap (owner app, databaseReclaimPolicy: retain). Only name, owner and requested extensions are declared, so adopting existing or recovered databases changes nothing else. spec.extensions lists extensions for it, and all are activated with CREATE EXTENSION in app. Names are SQL extension names and limited to an allowlist: most extensions bundled in the CNPG standard image (PostgreSQL contrib and vector) plus postgis and timescaledb. Contrib extensions that reach outside the database or modify storage (dblink, postgres_fdw, file_fdw, pg_surgery), and deprecated or example ones (xml2, intagg, refint, autoinc, insert_username, moddatetime, dict_int, dict_xsyn, uuid-ossp), are excluded. postgis and timescaledb are also mounted from the CNPG image catalog (timescaledb from its timescaledb-oss entry), and timescaledb is additionally added to shared_preload_libraries (ahead of the libraries CNPG manages). Removing an entry makes CNPG drop the extension as postgres (ensure: absent, DROP EXTENSION without CASCADE), so no tenant privileges are needed. postgis and timescaledb stay mounted, and timescaledb preloaded, until the Database reports the drop applied for its current generation; only then are the entry, image and library removed. The drop fails, and CNPG retries it, while other objects depend on the extension: remove those (e.g. hypertables or geometry columns) or re-add the entry. Adding timescaledb to an existing cluster, or completing its removal, restarts its pods. pg_stat_statements and pgaudit are not in the allowlist because CNPG already manages them. Multiple databases are not supported.
Automatic execution plans
Set spec.autoExplain: true on a nais.io/v1 Postgres to log JSON execution
plans for statements taking at least one second.
Omitting autoExplain or setting it to false leaves the module disabled.
The module is bundled in the CNPG standard image, and CNPG manages preloading
automatically; no image extension or spec.extensions entry is needed. Enabling
or disabling it on an existing cluster requires a rolling restart.
Execution statistics add instrumentation overhead even for statements below the
logging threshold. Parameter values are hidden, but SQL text and plans can still
contain sensitive literals.
Namespace alerts
Pgrator reconciles one PrometheusRule, nais-postgres-alerts, in each namespace
with a Postgres. All databases in the namespace share it; removing one database
keeps the rule, and deleting the last removes it. Changes to platform alert
expressions and thresholds overwrite local rule edits.
Each PostgresBinding connection Secret contains ca.crt and, for every requested
credential (admin, read, readwrite), <credential>.tls.crt,
<credential>.tls.key (the original PEM private key), and <credential>.tls.pk8
(the same key encoded as unencrypted PKCS#8 DER for pgJDBC). PKCS#8 is a key
format, not a different key algorithm; EC certificates continue to use EC keys.
Both representations are published in the same validated snapshot and rotate
with the client certificate. Incomplete or invalid source material does not
replace the last complete snapshot.
Naiserator owns the workload mount paths and exposes a role-prefixed PGJDBCURL
using the DER file. Existing PEM files and PGSSLKEY remain unchanged.
Personal access
PostgresAccess grants a person time-limited access to one Postgres. It creates a short-lived password, a CNPG DatabaseRole (PostgreSQL role name is the authenticated email), an owned RelayAccess and token Secret, and a database-ingress policy. Its Ready condition requires the role applied at the current generation, a persisted token and the owned relay mapping's published endpoint; Ready does not establish SQL connectivity. The relay operator publishes the public endpoint after persisting its egress policy, and pgrator copies that endpoint into PostgresAccess.status.relayEndpoint for the API's owner-only connection response. Expiry and deletion remove transport resources and credentials, disable SQL login and the password, and remove role memberships. Pgrator waits for CNPG to apply the inactive role configuration before deleting its DatabaseRole resource. ReclaimPolicy: Retain preserves the PostgreSQL role and its objects. Cleanup can remain pending while CNPG is unavailable; this is not a hard cutoff for existing SQL sessions. Existing roles created under older naming are not migrated or re-owned automatically. See ADR 0005 for identity history and ADR 0006 for relay transport.
The generated CRD documentation describes public fields.
spec.accessLevel supports read, readwrite, admin and maintain, plus
the deprecated readwritecreate level for compatibility. Personal admin grants
membership in the existing app owner role: the same database privileges as the
workload admin credential, including creating schemas and managing app-owned
objects, without PostgreSQL superuser privileges. The login remains the person's
email. This works with existing and recovered clusters without a bootstrap migration.
Objects created as the personal role remain personally owned. For workload-owned
objects and the app role's default privileges, use SET ROLE app before DDL;
session_user still identifies the person, while current_user becomes app.
Membership does not apply the owner's default privileges to personally created objects.
readwritecreate keeps its original privileges (read/write and CREATE in public),
not database ownership. Existing access is not upgraded automatically, and the
app_readwritecreate SQL role and existing objects are not removed.
The personal-only maintain level grants direct membership in PostgreSQL's
pg_monitor and pg_maintain roles, without application data privileges,
database ownership or superuser privileges. It allows server-wide monitoring
and maintenance across databases in the selected PostgreSQL cluster, not just
the application schema. Monitoring can expose sensitive query text, and
maintenance can acquire locks that affect availability. pg_maintain requires
PostgreSQL 17 or newer. This level is not available to applications through
PostgresBinding; their admin credential is unchanged. admin is the
application database owner, while maintain grants monitoring and maintenance
of the PostgreSQL instance.
Why every database has a -personal-access DatabaseRole
Pgrator creates a CNPG DatabaseRole named
<cluster-name>-personal-access for every database, even when nobody has
requested personal access. This is a database-owned authentication group, not a
PostgresAccess or a personal user. Its SQL name is nais_pa_<hash>;
it has NOLOGIN, no password and no database privileges.
When a person requests a PostgresAccess, that controller creates the user's
DatabaseRole and grants membership in:
- the database's authentication group, allowing TLS/SCRAM password authentication
through the Cluster's
pg_hba rule; and
- the selected privilege group (
app_read, app_readwrite or the legacy
app_readwritecreate), the app owner role for admin, or directly
pg_monitor and pg_maintain for maintain, determining what the user may
do in the database or instance.
The authentication group must be unique per database because recovery copies
SQL roles, memberships and passwords from the source. The restored cluster's
pg_hba rule requires its own group, so copied personal credentials do not
automatically grant password access to the destination. A new PostgresAccess
targeting that database grants the required membership.
Unlike the privilege groups created by postInitSQL, this group is managed by
a separate DatabaseRole: bootstrap SQL runs only for initdb, not recovery.
Putting it only in bootstrap SQL would copy the source group during restore
without creating the destination group. The DatabaseRole covers new, existing
and recovered clusters and is controller-owned by the Postgres with
ReclaimPolicy: Delete; the user's access-owned DatabaseRole uses Retain.
An event such as Updated DatabaseRole ...-personal-access concerns this group,
not a personal access request. In versions that update children unconditionally,
it can also appear when the group configuration is unchanged.
Implementation entry points:
Dashboards
The Postgres dashboards are plain Grafana dashboard JSON in
grafana/, synced by Grafana Git Sync from main (setup).
No provisioning Job or Helm release is needed.
CI/CD
GitHub Actions runs the repository's mise checks and tests and publishes image and Helm chart artifacts for non-Dependabot branch pushes. Deployment via Fasit remains restricted to main. Changes confined to grafana/**, its workflow and existing ignored Markdown paths skip this pipeline and use Dashboard checks instead.
Pull requests also run E2E tests in a kind cluster using Chainsaw, via the mise run test:ci task. The same dashboard-only exclusion applies; mixed operator/dashboard changes still run E2E.
Contributing
Development workflow
- Install tools —
mise install sets up Go, golangci-lint, controller-gen, helm, and all other dependencies at pinned versions.
- Make changes — edit code, CRD types, or Helm chart.
- Regenerate — if you changed types in
pkg/api/, run mise run generate to update CRDs and DeepCopy methods.
- Test locally —
mise run test runs standard Go tests in both the root and pkg/api modules. Controller integration tests use envtest (a real API server + etcd, no cluster needed).
- Commit — lefthook pre-commit hooks run fmt, lint, vet, and generate-check automatically.
- Push — pre-push hook runs tests. CI runs the full matrix in parallel.
Running operator in local cluster
mise run dev:setup-cluster to start a local cluster.
mise run dev:tilt to use tilt to install dependencies into the cluster, and build and install the operator.
mise run test:e2e to run E2E tests in the local cluster.
mise run dev:stop-cluster to stop the cluster.
The cluster uses kind by default, but can be changed to any cluster engine supported by ctlptl.
To select a different engine, create a local mise config, overriding the env-variable DEV_CLUSTER_ENGINE with a ctlptl product name.
Adding a new golden test case
Golden tests are data-driven: each test case is a directory under internal/controller/testdata/{resource}/{case-name}/:
my-test-case/
├── object.yaml # Input CRD spec to reconcile
├── prepared_data.yaml # Optional: set engine, projectID, etc.
├── related_objects/ # Optional: pre-existing objects in cluster
├── contains/ # Assert actions contain at least these (use for partial checks)
│ └── cluster.yaml
└── consists_of/ # Assert actions match exactly these (use for full coverage)
└── cluster.yaml
Each expected file in contains/ or consists_of/ specifies:
action: the concrete action type, for example create, createOrUpdate, or exclusiveCreateOrUpdate
matcher: Equal (exact match) or Subset (only specified fields must match)
object: the expected Kubernetes resource
Writing Go tests
Use the standard library testing package. Prefer table-driven tests with
t.Run when several cases exercise the same contract; use a focused TestXxx
function when setup or behavior differs materially. Test observable behavior,
not implementation branches. Golden fixtures are the preferred contract tests
for reconciler output.
Running tests
mise run test # Root + pkg/api Go tests; sets up envtest automatically
mise run test:e2e # E2E tests (requires running mise run dev:tilt in a separate terminal)
mise run test:ci # Starts a cluster, runs E2E tests
go test ./... can be used for a single module when KUBEBUILDER_ASSETS is
already configured. The mise task is the authoritative full test command because
Go does not traverse into the nested pkg/api module automatically.
Code generation
After modifying types in pkg/api/ or RBAC markers (+kubebuilder:rbac):
mise run generate # Regenerate CRDs + DeepCopy + copy to Helm chart
mise run generate-check # Verify nothing is out of date (CI runs this)
Some code generated with GitHub Copilot
This repository occasionally uses GitHub Copilot to generate code.