Skip to content

Control Plane and REST API

Mohammad Rasoul Kazemi edited this page Nov 20, 2026 · 11 revisions

Control Plane and REST API

kingresd is the control-plane server of KingresDB. It runs on every server of a cluster and serves, on one port (default 127.0.0.1:8091), the management REST API and the embedded Web Console. The REST contract is kingres/api/openapi.yaml, revision 0.13.0, OpenAPI 3.1, base path /api/v1.

Roles of kingresd

  • Agent. On each server it creates, configures, starts and stops the PostgreSQL instances (initdb, postgresql.conf, pg_hba.conf, pg_ctl), holds the server's certificates, and sends heartbeats.
  • Manager (leader). One server is the manager leader: the server that runs the primary of the map group (ADR 0018). It runs tasks and the recurring jobs. A mutating cluster operation that reaches another server is forwarded to the leader, and the response is the leader's.
  • Client router. An optional TCP entry point that forwards client connections to the current primary, or to a local standby for lag-tolerant reads (see High Availability).

kingres-cli is named in the documents as a second client of the API. This checkout has no kingres-cli command in kingres/control-plane/cmd (only kingresd and kingres-watchdog), so use the REST API or the console.

State that belongs to the control plane (tasks, cluster settings, server groups, alerts, managed network rules) lives in a system database, kingres_system, schema kingres_cp, with embedded migrations (ADR 0019). There is no bundled metrics store: kingresd samples and exports metrics itself (ADR 0020). Panel accounts are PostgreSQL roles (ADR 0015).

Status

Phase 3 (control plane, REST API, panel, package) is done, and the control plane passes its integration suite on PostgreSQL 18 and 19. Later phases added rebalancing, high availability, the ledger operations and configuration from the console; for their review state see Status and Roadmap. The control plane and the packaging have not been checked on 19 beyond that suite.

Running it

cd kingres/control-plane
go build -o kingresd ./cmd/kingresd
./kingresd -pg-dsn "host=127.0.0.1 port=5432 dbname=postgres user=kingresd password=..." -data-dir ./data

While a node is uninitialized, kingresd writes a one-time setup token to <data-dir>/setup-token and logs only the file name. GET /api/v1/setup/state and /healthz work at once.

Start a one-server cluster by hand (from the README):

kingresd -data-dir /var/lib/kingres -pg-bin-dir /opt/kingres/bin -listen 127.0.0.1:8091
curl -s -X POST http://127.0.0.1:8091/api/v1/setup/init-cluster \
  -H "X-Setup-Token: $(cat /var/lib/kingres/setup-token)" -H 'Content-Type: application/json' \
  -d '{"clusterName":"prod","admin":{"username":"root_admin","password":"a-long-password"},
       "dataPaths":{"dataDirectory":"/var/lib/kingres"},"memoryQuota":{"totalMegabytes":4096}}'
curl -s http://127.0.0.1:8091/api/v1/setup/state

See Cluster Setup for the whole procedure, ports and certificates. A second server joins with POST /api/v1/setup/join-cluster (it registers with the leader at existingNodeAddress, receives the certificates, and creates a primary of a new shard group and the standby of a neighbouring group; it appears as pendingRebalance and no data moves until a rebalance is started). Joining, adding and removing servers need internal-listen, the mutual-TLS listener of the internal server-to-server API (by convention the REST port plus one). See Configuration for the settings and Installing and Packaging for the package.

Rebalance

A rebalance is one task of kind rebalance on the leader: check the cluster, compute the plan with kingres.rebalance_plan(), move buckets one at a time with kingres.move_bucket(...), write the report. It can be stopped and started again, is taken over after a restart or a leader change, and has a page in the console. Several moves at once, the strategy by disk size and draining a server are phase 10 and are not built. The reviews found and fixed fencing defects; the latest round's fixes have not been reviewed again (Status and Roadmap). See Rebalancing for the procedure and Sharding for bucket moves in the extension.

Authentication model

  • POST /auth/login signs in a PostgreSQL role by user name and password. The role needs LOGIN and membership in at least one cluster role. The response sets the kingres_session cookie (HttpOnly, Secure, SameSite=Strict) and a CSRF token that browsers send as X-CSRF-Token on every mutating request. With issueToken: true the response also holds a bearer token for scripts.
  • A session belongs to the server that created it: the same value on another server is 401, and a restart ends the session. A client signs in once per server.
  • The four cluster roles are memberships in kingres_admin, kingres_ops, kingres_readonly and kingres_stats, with the hierarchy admin > ops > readonly > stats. Every operation names its minimum role in x-required-role (the contract has 43 operations for admin, 21 for ops, 57 for readonly, 4 for stats and 7 without a role).
  • The setup operations use the one-time X-Setup-Token header, and only from loopback addresses unless allow-remote-setup is true.
  • Every request passes one guard in this order: node-state gating, cross-site check, rate limit, authentication, CSRF check, role check, query-parameter validation, then the handler. Audited operations are written to an append-only audit log.
  • Errors are RFC 9457 application/problem+json; long-running operations answer 202 with a Task and a Location header.

See Security Model.

Operation groups

All paths are below /api/v1. The list is taken from openapi.yaml; the full list of 132 operations with their roles, the error codes and the versioning rules are on REST API Reference.

Tag Paths (examples)
Health /healthz, /readyz
Auth /auth/login, /auth/logout, /auth/session
Setup /setup/state, /setup/init-cluster, /setup/join-cluster, /setup/token-check
This server /this-server, /this-server/resources, /this-server/instances, /this-server/instances/{instanceId}/start, /stop, /restart, /this-server/settings, /this-server/leave-cluster, /this-server/logs
Cluster, Servers /cluster, /cluster/summary, /servers, /servers/{serverId}, /servers/{serverId}/failover, /servers/{serverId}/certificates/renewals, /servers/{serverId}/certificates/revocations, /server-groups
Databases, Tables, Shards /databases, /databases/{databaseName}, /databases/{databaseName}/tables, .../tables/{tableName}/distribution, /databases/{databaseName}/colocation-groups, /databases/{databaseName}/bucket-distribution
Replication, failover /replication/topology, /replication/restore-preferred-primaries, /failover, /failover/reports, /settings/cluster/auto-failover/reset
Rebalance /rebalance (status and start), /rebalance/plan, /rebalance/stop, /rebalance/reports, /rebalance/reports/{reportId}
Tasks /tasks, /tasks/{taskId}, /tasks/{taskId}/cancel
Roles, Grants, Network access, Audit, Settings /roles, /roles/{roleName}, /cluster-roles, /grants, /settings/network-access, /audit, /settings/cluster
Configuration (0.8.0) /config/parameters, /config/changes/preview, /config/changes, /config/servers, /config/time, /config/restarts
Ledger /ledger/status, /databases/{databaseName}/ledger/blocks, .../digests, .../verifications, .../inclusion-proofs, /ledger/signing/keys, /ledger/publication, /ledger/anchor-targets, .../ledger/anchors, .../ledger/bundles, .../ledger/client-keys
Query /query, /query/statements/{statementId}/cancel
Alerts, Logs, Metrics /alerts, /logs, /metrics/query

Some phase-7 ledger operations in the contract are not built and answer 422 unsupported_operation. The reference is openapi.yaml itself; conventions are in kingres/api/README.md. Example calls:

POST /api/v1/auth/login        {"username":"alice","password":"s3cret","issueToken":true}
GET  /api/v1/rebalance
POST /api/v1/servers/{serverId}/failover   (body: {"mode":"hard","dryRun":true})

Process model

  • One unit. The package has one systemd unit, kingres.service: kingresd starts and adopts the PostgreSQL instances, which are independent processes. A crash or a restart of kingresd leaves the database running (to restart only the manager send it SIGTERM); systemctl stop stops the database too (ExecStop runs kingresd -stop-instances; KillMode=process, TimeoutStopSec=120). kingresd sends READY=1 and STOPPING=1 to systemd. The unit is sandboxed (no capabilities, ProtectSystem=strict, writes only under /var/lib/kingres).
  • Watchdog. kingres-watchdog is a small standard-library program next to kingresd; it covers a dead or hung kingresd by reading a lease file that kingresd replaces after every renewal (it holds no time of day) and stopping the instance with an immediate shutdown when the lease would have lapsed. See High Availability.
  • Scheduler. The manager leader runs the recurring jobs. On becoming leader it waits one lease-margin, increments the term and starts its jobs; every write made under a term is guarded by it.
  • Task engine. Tasks are durable, resumable step by step, and fenced by leases and an epoch: a holder that lost a lease writes nothing. A task is claimed by one server at a time.

Internal API

Servers talk to each other over a separate TLS 1.3 listener (internal-listen, mutual TLS under the cluster certificate authority; the public listener never accepts a client certificate and the internal listener never accepts a session or token). It is not part of the public contract, carries the header X-Kingres-Internal-Version and a server answers 409 version_mismatch to a peer of another version. The certificate is checked at every request, and a revoked or expired certificate is refused. The calls are authorised by a fixed table: leader-only calls (instances, trust, certificates, globals, apply) cannot be made by a server that is not the leader. See Cluster Setup and Security Model. Reference: internal-api.md.

Headers and cookies

Every response of the listener, including errors, the console files and /metrics, carries a strict content security policy (default-src 'self', no inline script or style, no external origin, frame-ancestors 'none'), X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer, Cross-Origin-Opener-Policy and Cross-Origin-Resource-Policy: same-origin, and a Permissions-Policy that disables camera, microphone and geolocation. Strict-Transport-Security is sent only when TLS is on (tls-cert-file set), never over plain HTTP, and X-Forwarded-Proto is not trusted. API responses, errors and /metrics are no-store; index.html is no-cache; hashed assets are public, max-age=31536000, immutable. A TLS-terminating proxy in front of a plain kingresd must add HSTS itself. The session cookie is kingres_session, HttpOnly; Secure; SameSite=Strict, with no Domain; Secure is set even without TLS, as the contract states.

Observability

Structured logs (text or JSON, no query strings, headers or bodies), the audit log audit.jsonl, alerts (GET /alerts), cluster-wide log search, and metrics: a short in-memory history for the console charts and a Prometheus-format /metrics endpoint for an external store (no bundled metrics store, ADR 0020). The alert kinds and their meaning are on Monitoring and Alerts.

Related pages

Administrator Guide, REST API Reference, Cluster Setup, Servers Databases and Roles, Rebalancing, High Availability, Configuration, Web Console, Upgrades.

Tests

go vet ./..., gofmt -l ., golangci-lint run ./... and go test ./... need no database. Integration tests run against real PostgreSQL instances when KINGRES_PG_BIN is set; scripts/run-integration.ps1 runs them in WSL2 and takes -Install to test another major. See Development and Testing.

Sources

Clone this wiki locally