mirror of
https://github.com/NVIDIA/OpenShell.git
synced 2026-10-26 06:52:57 +08:00
* test(server): add a local PostgreSQL test runner
The openshell-server tests that need a real PostgreSQL server are
ignored by default and had no shared way to run. The mutation-replay
test reads its own OPENSHELL_REPLAY_TEST_DATABASE_URL, so every
contributor had to provision a database by hand, and the advisory-lock
tests that follow in this series need the same setup.
Add mise run test:rust:postgres. It runs every ignored postgres_* test
in openshell-server against OPENSHELL_TEST_POSTGRES_URL, or starts a
disposable PostgreSQL container with Docker or Podman (CONTAINER_ENGINE
selects one) on the image pinned by the Kubernetes e2e fixture and
removes it on exit. Tests run one at a time because advisory locks are
database-wide. The runner always points the legacy replay variable at
the selected database, so an inherited URL cannot send that test to a
different server. test:postgres-runner checks that selection with a fake
cargo and needs no database or container engine. CI does not run the
PostgreSQL tests; TESTING.md documents the task.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* fix(server): hold the mutation guard while deleting a provider
DeleteProvider checked that no sandbox referenced the provider and then
deleted the record without holding the sandbox mutation guard. Sandbox
create and provider attach take that guard while they write provider
references, so one of them could add a reference after the attached
sandbox check passed, and the delete then removed a provider that a
sandbox spec still named.
Take the guard before the attached sandbox check, as provider create and
update already do, so the check and the delete run against a stable
set of sandbox references, and reject an empty name after authorization
but before the guard. A new test holds the guard, attaches the provider
while the delete waits, and asserts that the delete fails with
FailedPrecondition and leaves the provider in place.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* fix(server): release staged credentials when a refresh fails early
A provider credential refresh stages the minted values under new
credential handles before it commits the provider update, and deletes
those handles when validation or persistence fails. Two earlier returns
skipped that cleanup. The minted expiry was converted to a protobuf
timestamp only after staging, so an expiry outside the timestamp range
failed the refresh and left the staged values in the credential driver.
A failure to acquire the sandbox mutation guard returned the same way.
Convert the expiry before staging anything, so a bad value fails before
any handle exists, and delete the staged handles when the guard cannot
be acquired. A new test refreshes a stored credential with an expiry of
i64::MAX and asserts that the call fails, the provider keeps its
original handles, and the credential driver holds the same number of
values as before. The guard failure path has no test here, because the
SQLite guard used by unit tests cannot fail.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): acquire mutation locks on a dedicated PostgreSQL lock pool
The cross-object mutation guard took its advisory-lock session from the
10-connection data pool and closed it on every release, so each guarded
mutation opened a new database connection, and lock holders competed
with their own critical sections for data connections. A lock wait that
hit the 10 second lock_timeout surfaced as INTERNAL.
Add a lazy, dedicated 4-connection lock pool and a new
persistence::mutation_lock module for the lock key, mode and set types.
Store::acquire_distributed_mutation_guard now takes a lock set and a
deadline, and each lock statement sets lock_timeout to the time left
before that deadline, so a cancelled acquisition never waits past it on
the server. Returned connections are scrubbed with
pg_advisory_unlock_all() and reused, and each return is bounded by 5
seconds so a stalled session cannot keep a pool permit.
A lock statement that PostgreSQL ends with SQLSTATE 55P03 fails with a
new LockTimeout error, and so does a wait for a lock connection during
which every one was checked out at some point, or that started with less
than a second left, too little to open one. The API returns it as
UNAVAILABLE with reason MUTATION_LOCK_TIMEOUT and a 1 second retry
delay, because the mutation lock was not acquired, so the request's
guarded writes did not run. Only the guard acquisition classifies 55P03;
any other 55P03 stays a database error. A lock connection that
PostgreSQL does not open by the deadline despite at least a second to do
so (refused, out of connection slots, starting up, or not answering, all
of which SQLx retries silently) is a database error, not a lock timeout.
Mutations still take the legacy global key exclusively, so old and new
replicas keep excluding each other during a rolling upgrade. Each
PostgreSQL-backed gateway pod can now open up to 14 database
connections (10 data plus 4 lock) instead of 10, and the chart's
autoscaling.maxReplicas comment says what its default of 4 needs. The
SSH host identity lock stays on a data connection, because sandbox
creation takes it while holding its mutation guard and a second
lock-pool connection there could exhaust the pool. The provider
credential refresh lock stays there too, so a refresh still progresses
while every lock connection is in use.
Part of #3528
Co-authored-by: divesh <dgude@nvidia.com>
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* perf(server): partition mutation locks by workspace and sandbox
Every cross-object mutation, and every lifecycle and supervisor update,
took one process-wide mutex and, on PostgreSQL, one fleet-wide advisory
lock. Unrelated sandboxes and providers therefore serialized across all
replicas, and one slow critical section delayed every other mutation in
the fleet.
Replace that lock with hierarchical intention locks on a global key, one
key per workspace and one key per sandbox, each held shared or
exclusive. Global settings and policy writers and platform-scope profile
writers hold the global key exclusively. Provider and workspace-scoped
profile writers, including DeleteProvider and credential refresh, hold
their workspace key exclusively. Sandbox writers and supervisor reports
hold their sandbox key exclusively under shared global and workspace
keys. Lifecycle, driver-watch and reconcile paths take only
process-local keys and keep relying on compare-and-swap across replicas.
Workspace and sandbox keys are domain-separated SHA-256 prefixes. Each
guard takes its local keys and then its advisory locks in ascending
order under one 10 second deadline, and no path nests guards. The
settings mutex is removed, since the global and sandbox keys cover it.
Sandbox settings are keyed by sandbox name, which a sandbox key no
longer covers once another sandbox reuses the name, so a settings
update returns NOT_FOUND unless its sandbox still holds the name after
the read, and ABORTED if the settings row was recreated before the
write.
The global key keeps its legacy value, so older replicas, which hold it
exclusively for every mutation, still exclude new ones during a rolling
upgrade. Guards now also give up after 10 seconds on SQLite, and
provider refresh reports a guard timeout as UNAVAILABLE instead of
INTERNAL. A supervisor report for a missing sandbox returns NOT_FOUND.
Startup endpoint-status reconciliation still holds the global key for
its whole scan.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* fix(server): reconcile endpoint status on startup one sandbox at a time
Startup endpoint-status reconciliation held the global mutation key
exclusively for its whole scan. On PostgreSQL that blocked every guarded
mutation on every replica until the starting gateway had walked all
sandboxes, and the scan first waited behind every in-flight sandbox
mutation. It also paged with an offset, so sandboxes deleted mid-scan
shifted rows between pages, and a write that raced the scan (a Conflict
from a lifecycle update on another replica, or a sandbox deleted after
it was listed) failed gateway startup.
Walk the sandboxes with keyset paging instead, and reset each candidate
under its own sandbox-scoped guard, up to four at a time to match the
lock pool. A candidate with a fresh shared owner is skipped before any
guard is taken. Under the guard the reconciliation re-checks the owner,
re-reads the sandbox, skips it when it is gone or no longer carries
endpoint status, and writes against the version it just read. A Conflict
or a database error at write time, which is how a row deleted after the
re-read surfaces, is retried with a fresh read, at most five attempts
per sandbox. A lock timeout on the guard is retried the same way, so a
holder of the sandbox, its workspace or the global key that releases
within the retry window cannot stop a replica from starting. No
lock-timeout retry starts once the scan has run for three lock timeouts,
so a scan stuck behind a long holder fails within about 40 seconds,
inside the chart's 60-second startup probe, and logs the sandbox it gave
up on. Store::list_all_messages loses its only caller and is removed.
Reconciliation stays fail-closed: a holder that outlasts the retry
window, an owner lookup failure, or a sandbox that keeps changing still
fails startup, so stale endpoint success is never served. User-visible
change: a restarting gateway no longer stalls mutations of unrelated
sandboxes and providers on its peers while it reconciles.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* perf(server): skip the endpoint-status lock when a session was replaced
When a supervisor session ends, the gateway resets that sandbox's tool
server endpoint evidence unless a replacement session already owns
endpoint observation. The replacement check ran only after the reset
had read the sandbox and taken its sandbox mutation guard, so a reset
whose supervisor had already reconnected still queued behind other
mutations of that sandbox, and on PostgreSQL it used a lock-pool
connection, only to find it had nothing to do.
Check for a replacement first: a live local session, or a fresh owner
record on a peer. When one exists, return without reading the sandbox
or taking the guard. Otherwise take the guard and repeat the same check
under it, because a replacement's pre-acknowledgement reset runs under
the same sandbox key and resetting after it would wipe the
replacement's fresh evidence. Both checks share one helper, so they
cannot drift apart. When no replacement exists, the reset costs one
extra owner-row read.
This helps most when a replica notices a dead stream late, after the
supervisor has already reconnected elsewhere (a network partition or a
keepalive expiry).
Deferring to a replacement leaves the old session's evidence to the
replacement's pre-acknowledgement reset, which can time out on its
bounded mutation lock wait. That reset's failure path removed the
replacement and released its owner record but scheduled no
invalidation, so the old session's success evidence could outlive both
sessions. An old session that ended after its replacement registered
already deferred this way, and the unguarded check now makes every
disconnect that finds the replacement defer too. When the reset fails
while the replacement is still current, also schedule the retried
invalidation that follows a session end. That failure path keeps the
lifecycle demotion from abandon_session_setup, but runs it in the
spawned task before the retry and only while this session is still
current, so a timed-out reset returns promptly.
Part of #3528
Co-authored-by: divesh <dgude@nvidia.com>
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* test(server): cover staged credential cleanup on a lock timeout
A provider credential refresh deletes its staged handles when it cannot
acquire the provider mutation guard, but that path had no test: the
SQLite guard used by unit tests could not fail. Mutation locks now
acquire under a deadline that tests can shorten, so the timeout path
can be exercised directly.
The new test shortens the lock deadline to 50 ms, holds the workspace
mutation guard, and refreshes a provider that already stores an AWS
access key. The refresh returns UNAVAILABLE with the
MUTATION_LOCK_TIMEOUT reason, the provider keeps its original handle,
which still resolves to the old key, and the credential driver holds
the same number of values as before the refresh.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): export mutation lock wait and timeout metrics
A handler mutation guard can now wait up to 10 seconds for its keys and
then fail with UNAVAILABLE, but nothing showed operators how long guards
waited or how often they gave up, short of reading warning logs on each
replica.
Export openshell_server_mutation_lock_wait_seconds, a histogram of the
time one guard took to acquire all of its keys (local registry plus
PostgreSQL advisory locks), recorded on success, and
openshell_server_mutation_lock_timeouts_total, a counter of guard
acquisitions that timed out. Both carry a bounded scope label: global,
workspace or sandbox. The platform scope, whose workspace is empty,
counts as global. The histogram uses the same 1 ms to 15 s buckets as
the relay and peer histograms, and the timeout counter starts at 0 for
every scope, so rate() works on an idle replica. The timeout warning
now also logs the scope. A guard that fails for another reason, such as
a lock connection PostgreSQL did not open, is not counted as a timeout
and logs a "mutation lock acquisition failed" warning instead.
Lifecycle, driver-watch and reconcile paths take only process-local
locks and never time out, so they are not recorded.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* test(server): add PostgreSQL mutation lock integration tests
The scoped mutation locks were only unit-tested on SQLite, where the
database layer is a no-op. Add ignored postgres_* tests that run the
advisory-lock layer against a real PostgreSQL through mise run
test:rust:postgres, each in its own disposable schema (TestSchema).
persistence/mutation_lock_pg_tests.rs uses two stores on one database
as two replicas. It covers disjoint sandbox scopes holding at once, a
workspace key blocking only sandboxes in that workspace, the global key
blocking every scope, and exclusion in both directions against a raw
holder of the legacy global key, whose 55P03 stays a database error
outside a guard acquisition. It checks that timed-out and cancelled
acquisitions release the keys they already took, that a released lock
connection returns to the pool without residual locks, that a release
stalled on the network closes its session and the pool recovers, and
that the lock pool never grows past its size. It also checks that a
full lock pool times out as lock contention, while a lock connection
that PostgreSQL never answers fails as a database error.
compute/mutation_guard.rs runs the random scope mix across two
PostgreSQL runtimes and checks that a by-id guard waits for a workspace
writer on the other replica. The provider refresh lock test moves onto
the runner too, and checks that a refresh proceeds while every lock
connection is held.
A bench_postgres_* capacity check measures a paced burst of 500
reconnects 12 ms apart into one replica and fails when the p99 lock
wait reaches a fifth of the lock timeout. Machine load moves those
waits, so mise run test:rust:postgres skips it and mise run
test:rust:postgres:bench runs it alone, through a new
OPENSHELL_TEST_POSTGRES_PREFIX setting in the runner.
The tests add test-only helpers: the lock pool's size and idle count
and the backend pid of a held lock session. Nothing changes outside
tests and the test runner.
Part of #3528
Co-authored-by: divesh <dgude@nvidia.com>
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* ci: run the PostgreSQL-backed server tests
Branch Checks now runs the postgres_* tests through the same runner
developers use, on an x86_64 Linux runner with Docker. They cover lock
scope exclusion, interop with replicas still on the old global key,
cancellation, lock-pool bounds and connection failures, which no other
CI lane checks directly. The load-sensitive bench_postgres_* capacity
checks stay local.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* docs: document scoped mutation locks and lock-pool sizing
In the High Availability guide, size PostgreSQL for 14 connections per
gateway pod, 10 for data and 4 for the new lock pool, so three or more
replicas now exceed what the PostgreSQL default leaves, and keep
headroom for lock sessions that cancelled requests leave behind.
Explain which changes lock a sandbox, a workspace, or the whole fleet,
and that a lock wait over 10 seconds returns a retryable UNAVAILABLE
with reason MUTATION_LOCK_TIMEOUT. A new upgrade subsection says to
raise max_connections to the 14-per-pod size before upgrading, because
the rollout already runs new pods at that count, and warns that older
replicas keep serializing every mutation until the rollout finishes.
Monitor Capacity gains the lock metrics and their queries, and names
slow driver, credential, middleware, or profile source calls as another
cause of lock waits.
List the lock wait histogram and timeout counter, with their scope
label, on the Gateway Metrics page. The counter also counts background
work and leaves out lock connections that PostgreSQL does not open
although at least a second of the wait remained.
In the cluster debugging skill, replace the single advisory-lock
paragraph with the lock levels and pool, what each timeout detail
means, how a lock connection that PostgreSQL does not open shows up,
when terminating a lock backend is safe, a pg_locks query that shows
holders and waiters, and how to spot the global key. The per-pod greps
also read the timeout counter, and new rows cover lock timeouts and
lock connections that PostgreSQL does not open.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): check mutation lock ordering in debug builds
The mutation lock ordering rules were prose only, so a nested guard on
a different key passed every test and could only deadlock under
contention. Debug builds now register each held guard with the Tokio
task (or the thread, outside a task) that acquired it, and panic before
waiting when a local key, a blocking lifecycle gate or the SSH identity
lock would break rules 1, 4 or 5. Startup endpoint-status
reconciliation and the tests that hold a guard while driving guarded
code run under lock_order::branch(), which marks deliberate concurrency
within one task. Release builds compile the check out.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* fix(server): do not hold gateway shutdown for the endpoint-status retry
When a replacement supervisor session failed its endpoint-status reset,
the spawned cleanup task kept the session lifetime guard through
retry_endpoint_status_after_supervisor_disconnect. That retry only ends
once the reset is durable, so a gateway shutdown during a database or
lock outage waited the full 10 s and reported ownership cleanup as
incomplete. The guard now covers only the lifecycle demotion, as in
finish_supervisor_session, and a SQLite test checks that shutdown
completes while the retry is still blocked.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* refactor(server): make the platform profile lock scope explicit
Platform-scope provider profile writers (import, update, delete) pass an
empty workspace on purpose and need X(global), because they validate
sandboxes in every workspace. MutationScope::profiles() now names that
escalation and picks Global for the platform scope, instead of relying
on MutationScope::Workspace("") to mean it. An empty workspace name now
trips a debug assertion, and release builds keep X(global) as a
fail-safe that over-locks rather than under-locks.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* perf(server): amortize local mutation lock table sweeps
LocalMutationLocks swept its whole table on every key lookup, so a
burst of N concurrent acquisitions on one replica cost O(N^2) under a
blocking mutex. The table is now swept only when a new key grows it
past the larger of 64 and twice the live entries left by the last
sweep, which makes acquisition amortized O(1). Released entries,
including those of cancelled waiters, stay bounded at about twice the
peak live set. The lifecycle gate registry keeps its per-call sweep.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): make the database pool ceiling configurable
Both stores hardcoded their pool ceiling: 10 connections for Postgres, 5
for on-disk SQLite. One pool is shared by every database-backed RPC, so
that number is also the gateway's ceiling on concurrent database work.
Once every connection is checked out, callers queue on acquire and sqlx
logs "time to acquire exceeded slow threshold"; sandbox creates then time
out and are retried, which adds load rather than shedding it.
The right ceiling is deployment-specific — it depends on how many gateway
replicas share the database and what max_connections the server itself
allows — so it cannot be a single number baked into the binary.
Expose it on the same config surface as the rest of the gateway's
settings: --db-max-connections, OPENSHELL_DB_MAX_CONNECTIONS, and the
TOML key database_max_connections, resolved in that precedence order.
Helm deployments set the key through gatewayConfig. Omitting it keeps
each backend's previous value, so existing deployments do not move.
Values below 1 are rejected rather than silently replaced by the default:
a zero pool would block every acquire, and quietly ignoring a typo would
reproduce the ceiling the operator is trying to lift. An in-memory SQLite
database stays pinned to one connection, since the database lives inside
that connection.
Refs: #2561
Signed-off-by: Bryce Wilkinson <22760097+bjw123@users.noreply.github.com>
(cherry picked from commit 33517b32bd)
[emacchi: dropped the server.dbMaxConnections Helm value; operators set
the key through gatewayConfig]
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): make the mutation lock pool size configurable
The mutation lock pool was fixed at 4 connections per replica. That
number rests on one reconnect-burst bench rather than scale testing, so
a gateway that serves many more sandboxes needs a way to raise it
without a rebuild. Add --db-lock-max-connections,
OPENSHELL_DB_LOCK_MAX_CONNECTIONS and the database_lock_max_connections
gateway.toml key next to the data pool knob, resolved in the same order;
Helm deployments set it through gatewayConfig. The default stays 4,
zero is rejected, SQLite ignores it with a warning, and the gateway logs
both pool sizes at startup. PostgreSQL now needs at least 2 data
connections, because the SSH identity lock keeps one while it queries
the pool. The connection sizing docs, the HA guide formula and the
debug skill now count data plus lock connections.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): export mutation lock errors and lock connections in use
A mutation lock acquisition that failed without timing out, such as a
lock connection PostgreSQL never opened or a failed lock statement,
only logged a warning, and readiness stays healthy because it pings the
data pool. Count those failures in
openshell_server_mutation_lock_errors_total{scope}, kept apart from
timeouts because they point at PostgreSQL capacity or connectivity
rather than contention. Export
openshell_server_mutation_lock_connections_in_use as a gauge slot held
by each checked-out lock connection, next to
openshell_server_mutation_lock_connections_capacity, which reads the
configured lock pool size; both exist only with PostgreSQL. The metrics
catalog, the HA guide's signals and PromQL examples, and the debug
skill cover the new series.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
* feat(server): time mutation lock holds and test a stalled holder
Nothing bounds how long a mutation guard is held, so a holder stuck in
a compute driver, credential backend or middleware call keeps its scope
locked while waiters time out. Each guard now records its hold in
openshell_server_mutation_lock_hold_seconds{scope} when it is released,
and logs a warning when the hold outlasted the lock wait timeout, so
operators can find the replica and scope behind those timeouts. A
PostgreSQL test with a stalled holder pins the current contract:
waiters on its sandbox, workspace and global scopes fail by their
deadline, other scopes proceed, the holder keeps its key, and a full
lock pool on one replica leaves the other working. The metrics catalog,
the HA guide and the debug skill describe the new signals, which
observe holds without bounding them.
Part of #3528
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
---------
Signed-off-by: Emilien Macchi <emacchi@redhat.com>
Co-authored-by: divesh <dgude@nvidia.com>
Co-authored-by: Bryce Wilkinson <22760097+bjw123@users.noreply.github.com>
517 lines
24 KiB
Plaintext
517 lines
24 KiB
Plaintext
---
|
||
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
||
# SPDX-License-Identifier: Apache-2.0
|
||
title: "High Availability"
|
||
sidebar-title: "High Availability"
|
||
description: "Run multiple OpenShell gateway replicas on Kubernetes with shared PostgreSQL, authenticated peer routing, capacity metrics, and optional autoscaling."
|
||
keywords: "Generative AI, Cybersecurity, Kubernetes, High Availability, HA, Gateway, PostgreSQL, Replicas, Failover, Autoscaling, HPA, Metrics"
|
||
position: 3
|
||
---
|
||
|
||
Run two or more gateway replicas when the OpenShell control plane must remain
|
||
available during a gateway pod failure or rolling update. Every replica can
|
||
serve API requests. The replicas share persistent state through PostgreSQL and
|
||
relay session-bound requests to the replica connected to each sandbox
|
||
supervisor.
|
||
|
||
<Warning>
|
||
Gateway replicas do not make PostgreSQL highly available. Use a managed
|
||
PostgreSQL service or a separately operated PostgreSQL cluster with its own
|
||
backup and failover plan.
|
||
</Warning>
|
||
|
||
## Requirements
|
||
|
||
An HA gateway deployment requires:
|
||
|
||
- Two or more schedulable Kubernetes nodes or failure domains.
|
||
- PostgreSQL reachable from every gateway pod.
|
||
- A Kubernetes Secret in the OpenShell namespace with the PostgreSQL connection
|
||
URI in a key named `uri`.
|
||
- `workload.kind: deployment`. The default StatefulSet and per-pod SQLite
|
||
database are intended for a single gateway replica.
|
||
- An ingress or load balancer that routes clients to the gateway Service. Refer
|
||
to [Ingress](/kubernetes/ingress) for a Gateway API configuration.
|
||
- PostgreSQL connection capacity for every replica, including pods that are
|
||
starting or terminating during a rollout. Refer to
|
||
[Size PostgreSQL Connections](#size-postgresql-connections).
|
||
|
||
The Helm chart rejects `replicaCount` values above `1` unless
|
||
`server.externalDbSecret` is set. It also rejects a multi-replica StatefulSet
|
||
unless `workload.allowMultiReplicaStatefulSet` is explicitly enabled. Use a
|
||
Deployment for the standard HA configuration.
|
||
|
||
## Create the PostgreSQL Secret
|
||
|
||
Provision PostgreSQL outside the OpenShell chart, then create the connection
|
||
Secret. The chart does not install PostgreSQL.
|
||
|
||
```shell
|
||
kubectl create namespace openshell
|
||
|
||
kubectl -n openshell create secret generic openshell-postgres \
|
||
--from-literal=uri='postgresql://openshell:<password>@<postgres-host>:5432/openshell'
|
||
```
|
||
|
||
Use your PostgreSQL provider's required TLS parameters in the connection URI.
|
||
Keep the Secret in the same namespace as the gateway release.
|
||
|
||
## Configure Gateway Replicas
|
||
|
||
Create `values-ha.yaml`:
|
||
|
||
```yaml
|
||
replicaCount: 2
|
||
|
||
workload:
|
||
kind: deployment
|
||
|
||
server:
|
||
externalDbSecret: openshell-postgres
|
||
|
||
affinity:
|
||
podAntiAffinity:
|
||
requiredDuringSchedulingIgnoredDuringExecution:
|
||
- labelSelector:
|
||
matchLabels:
|
||
app.kubernetes.io/name: openshell
|
||
app.kubernetes.io/instance: openshell
|
||
topologyKey: kubernetes.io/hostname
|
||
```
|
||
|
||
The anti-affinity rule places the two replicas on different nodes. The
|
||
`app.kubernetes.io/instance` value must match the Helm release name. Change the
|
||
topology key to a zone label when replicas must span availability zones. A
|
||
required rule leaves a replica Pending when the cluster does not have enough
|
||
matching failure domains; use preferred anti-affinity when scheduling the
|
||
replica is more important than strict separation.
|
||
|
||
Install or upgrade OpenShell:
|
||
|
||
```shell
|
||
helm upgrade --install openshell \
|
||
oci://ghcr.io/nvidia/openshell/helm-chart \
|
||
--version <version> \
|
||
--namespace openshell \
|
||
--values values-ha.yaml \
|
||
--wait
|
||
```
|
||
|
||
The chart shares its retained sandbox JWT signing material, TLS material, and
|
||
default credential-storage encryption key across the gateway pods. Do not
|
||
create different copies of those Secrets for individual replicas.
|
||
|
||
## Verify the Deployment
|
||
|
||
Wait for all gateway replicas to become ready:
|
||
|
||
```shell
|
||
kubectl -n openshell rollout status deployment/openshell
|
||
kubectl -n openshell get pods \
|
||
-l app.kubernetes.io/name=openshell,app.kubernetes.io/instance=openshell \
|
||
-o wide
|
||
```
|
||
|
||
Confirm that the client-facing Service and headless peer Service have ready
|
||
endpoints:
|
||
|
||
```shell
|
||
kubectl -n openshell get service openshell openshell-peer
|
||
kubectl -n openshell get endpointslice \
|
||
-l app.kubernetes.io/service-name=openshell
|
||
kubectl -n openshell get endpointslice \
|
||
-l app.kubernetes.io/service-name=openshell-peer
|
||
```
|
||
|
||
If you changed the chart's generated names with `nameOverride` or
|
||
`fullnameOverride`, use the rendered Service names instead.
|
||
|
||
After registering the gateway with the CLI, verify that requests succeed:
|
||
|
||
```shell
|
||
openshell status
|
||
openshell sandbox list
|
||
```
|
||
|
||
## Protect Voluntary Disruptions
|
||
|
||
Add a PodDisruptionBudget so a voluntary disruption, such as node maintenance,
|
||
does not evict every ready gateway pod at once:
|
||
|
||
```yaml
|
||
apiVersion: policy/v1
|
||
kind: PodDisruptionBudget
|
||
metadata:
|
||
name: openshell
|
||
namespace: openshell
|
||
spec:
|
||
minAvailable: 1
|
||
selector:
|
||
matchLabels:
|
||
app.kubernetes.io/name: openshell
|
||
app.kubernetes.io/instance: openshell
|
||
```
|
||
|
||
Apply the manifest separately from the OpenShell chart. Match the namespace and
|
||
release labels to your installation. A PodDisruptionBudget controls voluntary
|
||
evictions; it does not protect against an unavailable node or failure domain.
|
||
|
||
## How Peer Routing Works
|
||
|
||
A sandbox supervisor keeps one active control stream to one gateway replica.
|
||
That replica records ownership in PostgreSQL. When Kubernetes sends a client
|
||
request to another replica, the receiving gateway relays exec, forwarding,
|
||
file-sync, service, and status traffic to the owner through the headless peer
|
||
Service.
|
||
|
||
Peer RPCs use a projected, pod-bound ServiceAccount token with the
|
||
`openshell-gateway-peer` audience. The receiving gateway validates the token
|
||
with the Kubernetes TokenReview API, verifies the live pod identity and release
|
||
labels, and authorizes only peer methods. When gateway TLS is enabled, peer
|
||
connections also use the chart's TLS materials.
|
||
|
||
You do not need session affinity at the ingress or client-facing Service.
|
||
|
||
## Failure and Rollout Behavior
|
||
|
||
When a non-owner gateway pod stops, Kubernetes removes it from ready Service
|
||
endpoints and new requests go to another replica. Existing requests through the
|
||
stopped pod disconnect and must be retried.
|
||
|
||
When an owner gateway pod stops gracefully, it re-reads gateway membership and
|
||
redirects its connected supervisors to the replicas that now own them,
|
||
including replicas that started moments earlier. After a crash, supervisors
|
||
reconnect through the gateway Service. Either way, they publish new ownership. Other replicas re-read ownership
|
||
while waiting to relay a request. A request fails if no fresh, reachable owner
|
||
appears before its normal deadline.
|
||
|
||
A stopping owner waits up to five seconds for a redirected supervisor to
|
||
publish its new session before it marks the sandbox not ready, so a sandbox
|
||
stays `Ready` through a graceful handoff. Supervisors reconnect with
|
||
exponential backoff that restarts after each accepted session, so repeated
|
||
gateway restarts do not lengthen later reconnects.
|
||
|
||
Established streams do not move between gateway replicas. An interrupted exec,
|
||
forwarding, or service stream must reconnect. File sync retries with a new SSH
|
||
session instead of resuming the interrupted byte stream. Rolling updates can
|
||
temporarily concentrate supervisor sessions on the replicas that stayed up;
|
||
client requests remain routable through peer relay.
|
||
|
||
## Monitor Capacity
|
||
|
||
Each gateway replica exposes Prometheus metrics on port `9090`
|
||
(`service.metricsPort`). Scrape every gateway pod, not the Service, because
|
||
these signals describe one replica. Refer to
|
||
[Gateway Metrics](/observability/gateway-metrics) for the full catalog, scrape
|
||
configuration, and access control.
|
||
|
||
| Signal | Metrics | Use |
|
||
|---|---|---|
|
||
| Sessions per replica | `openshell_server_supervisor_sessions` | Placement and skew. Do not scale on it. |
|
||
| Relay utilization | `openshell_server_relay_pending`, `openshell_server_relay_pending_capacity` | Graph it. It is transient and usually near 0, so alert on rejections instead. |
|
||
| Relay rejections | `openshell_server_relay_rejected_total` | Alert on any increase. |
|
||
| Relay claims | `openshell_server_relay_claim_duration_seconds`, `openshell_server_relay_expired_total` | Supervisor connect-back time for exec, SSH, forwarding, and service traffic, including relays requested through peers. A high 99th percentile while rejections stay flat points at the supervisor or its node, not at relay capacity. Relays not claimed within 10 seconds are missing from the histogram and count as expired, so alert on any increase. |
|
||
| Routed requests | `openshell_server_routed_request_attempts_total`, `openshell_server_peer_request_duration_seconds` | Local/peer relay setup mix and outbound peer rate, failures, and latency. Counts completed or cancelled attempts, including retries. Spikes of `grpc_code="unavailable"` during rollouts are expected. Do not use as an HPA target. |
|
||
| Lock contention | `openshell_server_mutation_lock_wait_seconds`, `openshell_server_mutation_lock_hold_seconds`, `openshell_server_mutation_lock_timeouts_total` | Alert on any timeout. Long holds on a scope make its waiters wait, and holds longer than 10 seconds make them time out. |
|
||
| Lock errors | `openshell_server_mutation_lock_errors_total` | Alert on any increase, separately from timeouts. PostgreSQL ran out of connection slots, restarted, or became unreachable. Readiness can stay healthy, because it uses established data connections. |
|
||
| Lock pool | `openshell_server_mutation_lock_connections_in_use`, `openshell_server_mutation_lock_connections_capacity` | PostgreSQL only. Graph in use over capacity per replica. Values that stay near 1 mean that guarded operations on this replica hold their lock connections, or wait in PostgreSQL for a lock held elsewhere, often by another replica, and lock waits and timeouts follow. |
|
||
|
||
These queries assume that Prometheus labels each series with `namespace` and
|
||
`pod`:
|
||
|
||
```promql
|
||
# Relay capacity used on each replica. Usually near 0; graph it and alert
|
||
# on rejections instead.
|
||
max by (namespace, pod) (openshell_server_relay_pending / openshell_server_relay_pending_capacity)
|
||
|
||
# Relays rejected for capacity. Alert on any increase.
|
||
sum by (namespace, pod, reason) (increase(openshell_server_relay_rejected_total[5m]))
|
||
|
||
# 99th percentile time for supervisors to claim a relay on each replica.
|
||
histogram_quantile(0.99, sum by (namespace, pod, le) (rate(openshell_server_relay_claim_duration_seconds_bucket[5m])))
|
||
|
||
# Completed or cancelled relay setup attempts, by replica, relay kind, and route.
|
||
sum by (namespace, pod, relay_kind, route) (rate(openshell_server_routed_request_attempts_total{operation="relay"}[5m]))
|
||
|
||
# Session skew across replicas. 1 means balanced. Starting and stopping pods
|
||
# raise it during rollouts.
|
||
max(openshell_server_supervisor_sessions)
|
||
/ clamp_min(avg(openshell_server_supervisor_sessions), 1)
|
||
|
||
# Failed peer requests as a share of attempts, by operation.
|
||
sum by (operation) (rate(openshell_server_routed_request_attempts_total{route="peer",outcome!="success"}[5m]))
|
||
/ sum by (operation) (rate(openshell_server_routed_request_attempts_total{route="peer"}[5m]))
|
||
|
||
# 99th percentile peer request latency across the fleet.
|
||
histogram_quantile(0.99, sum by (le, operation) (rate(openshell_server_peer_request_duration_seconds_bucket{outcome="success"}[5m])))
|
||
|
||
# 99th percentile mutation lock wait by scope. Watch scope="sandbox" during rollouts.
|
||
histogram_quantile(0.99, sum by (le, scope) (rate(openshell_server_mutation_lock_wait_seconds_bucket[5m])))
|
||
|
||
# Mutation lock timeouts by scope. Alert on any increase.
|
||
sum by (scope) (increase(openshell_server_mutation_lock_timeouts_total[10m]))
|
||
|
||
# 99th percentile time a mutation lock is held, by replica and scope.
|
||
# Conflicting acquisitions time out after 10 seconds.
|
||
histogram_quantile(0.99, sum by (namespace, pod, le, scope) (rate(openshell_server_mutation_lock_hold_seconds_bucket[5m])))
|
||
|
||
# Mutation lock acquisitions that failed without timing out. Timeouts do not
|
||
# include them, so alert on any increase here as well.
|
||
sum by (namespace, pod, scope) (increase(openshell_server_mutation_lock_errors_total[10m]))
|
||
|
||
# Lock-pool connections in use on each replica, PostgreSQL only. Values that
|
||
# stay near 1 mean the pool is close to full.
|
||
max by (namespace, pod) (max_over_time(openshell_server_mutation_lock_connections_in_use[5m]) / openshell_server_mutation_lock_connections_capacity)
|
||
```
|
||
|
||
Relay capacity is used on the replica that owns the sandbox's supervisor
|
||
session, including relays that other replicas request through peers, so
|
||
adding replicas does not relieve a busy owner. A relay whose client gave up
|
||
stays counted for up to about 40 seconds, the 10-second claim timeout plus the
|
||
30-second cleanup interval. Routed request counts include retries during
|
||
rollouts.
|
||
|
||
Each supervisor that reconnects takes one or two short sandbox-scoped locks on
|
||
the replica that receives it. When a gateway pod stops during a rollout, its
|
||
supervisors reconnect to the other replicas, so watch
|
||
`openshell_server_mutation_lock_wait_seconds` and
|
||
`openshell_server_mutation_lock_timeouts_total` with `scope="sandbox"` on the
|
||
receiving replicas. Rising waits or any timeout mean that those replicas
|
||
receive reconnects faster than they can absorb them, or that slow compute
|
||
driver, credential backend, middleware, or provider profile source calls during
|
||
sandbox and provider changes hold their locks longer. Guarded work has no time
|
||
limit of its own, so such a call holds its lock until it returns:
|
||
`openshell_server_mutation_lock_hold_seconds` shows how long, and the replica
|
||
logs `mutation lock held longer than the lock wait timeout` when it releases a
|
||
lock held longer than 10 seconds.
|
||
|
||
## Scale the Gateway
|
||
|
||
Scale the gateway by changing a fixed replica count or by letting a
|
||
HorizontalPodAutoscaler choose one. In both cases, keep at least two ready
|
||
replicas when availability must survive one gateway pod failure, and size
|
||
PostgreSQL and the cluster nodes for the largest replica count.
|
||
|
||
### Scale Manually
|
||
|
||
Change `replicaCount` in `values-ha.yaml`, then apply the release again:
|
||
|
||
```shell
|
||
helm upgrade openshell \
|
||
oci://ghcr.io/nvidia/openshell/helm-chart \
|
||
--version <version> \
|
||
--namespace openshell \
|
||
--values values-ha.yaml \
|
||
--wait
|
||
```
|
||
|
||
### Autoscale with a HorizontalPodAutoscaler
|
||
|
||
Set `autoscaling.enabled` to render an `autoscaling/v2`
|
||
HorizontalPodAutoscaler for the gateway Deployment, or for a StatefulSet with
|
||
`workload.allowMultiReplicaStatefulSet`. Add these values to
|
||
`values-ha.yaml`:
|
||
|
||
```yaml
|
||
resources:
|
||
requests:
|
||
cpu: 500m
|
||
memory: 512Mi
|
||
|
||
autoscaling:
|
||
enabled: true
|
||
minReplicas: 2
|
||
maxReplicas: 6
|
||
targetCPUUtilizationPercentage: 70
|
||
```
|
||
|
||
With autoscaling enabled, the chart stops setting `spec.replicas` and ignores
|
||
`replicaCount`. Kubernetes computes CPU and memory utilization against the
|
||
container request, so those targets need a matching `resources.requests`
|
||
entry. A `resources.limits` entry also works, because Kubernetes copies a
|
||
limit into an unset request. The chart rejects an `autoscaling.maxReplicas`
|
||
above `1` without `server.externalDbSecret`. Each scale-down hands the removed
|
||
replica's supervisor sessions to the remaining replicas, so the default behavior removes at most one pod every two minutes
|
||
after a five-minute stabilization window. Override it with
|
||
`autoscaling.behavior`, or set `autoscaling.behavior.scaleDown` to `null` to
|
||
drop the default. New replicas do not take existing sessions.
|
||
|
||
<Note>
|
||
A scale-down moves every supervisor session on the removed pod at once, and
|
||
requests through that pod must be retried. To choose when that happens,
|
||
set `autoscaling.behavior.scaleDown.selectPolicy` to `Disabled` so the
|
||
autoscaler only adds replicas, and remove replicas yourself with
|
||
`kubectl scale` at a quiet time.
|
||
</Note>
|
||
|
||
Check the autoscaler after you apply the release:
|
||
|
||
```shell
|
||
kubectl -n openshell get hpa openshell
|
||
kubectl -n openshell describe hpa openshell
|
||
```
|
||
|
||
<Warning>
|
||
Enabling autoscaling on an existing release removes `spec.replicas` from the
|
||
workload in that upgrade. Kubernetes can reset the workload to one replica
|
||
until the HPA scales it back to at least `autoscaling.minReplicas`, which moves
|
||
supervisor sessions from the other gateway pods to the remaining replica. Enable autoscaling
|
||
when you install the chart, or during a maintenance window. On an existing
|
||
release, upgrade with `--reset-then-reuse-values`, which needs Helm 3.14 or
|
||
later. With an older Helm, save the values with
|
||
`helm get values <release> -o yaml > values.yaml` and upgrade with
|
||
`--reset-values -f values.yaml`. `--reuse-values` keeps the
|
||
previous chart version's defaults, which lack the autoscaling values,
|
||
including the scale-down `behavior`, when that release predates them. For background, refer to
|
||
[Migrating Deployments and StatefulSets to horizontal autoscaling](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/#migrating-deployments-and-statefulsets-to-horizontal-autoscaling).
|
||
Disabling autoscaling renders `spec.replicas` from `replicaCount` again,
|
||
which defaults to 1, so set `replicaCount` to the replica count you want in
|
||
that upgrade.
|
||
</Warning>
|
||
|
||
### Autoscale on Custom Metrics
|
||
|
||
The HPA can also scale on a per-pod metric that a metrics adapter publishes.
|
||
The chart passes `autoscaling.metrics` to the HPA unchanged and does not
|
||
install Prometheus or an adapter. A custom metric needs these pieces:
|
||
|
||
- Prometheus scrapes every gateway pod and labels each series with
|
||
`namespace` and `pod`.
|
||
- A metrics adapter, such as prometheus-adapter, maps those labels to
|
||
Kubernetes resources and publishes a per-pod metric through the
|
||
`custom.metrics.k8s.io` API.
|
||
- `autoscaling.metrics` references that metric as a `Pods` metric with an
|
||
`AverageValue` target.
|
||
|
||
Scale on signals that fall when you add replicas, such as CPU utilization. Do
|
||
not scale on supervisor sessions, relay utilization, relay claim latency, or
|
||
peer request rate. New replicas do not take existing sessions, relay load stays
|
||
on the replica that owns each session, and peer traffic grows with the replica
|
||
count. Alert on those signals instead.
|
||
|
||
```yaml
|
||
autoscaling:
|
||
enabled: true
|
||
minReplicas: 2
|
||
maxReplicas: 6
|
||
targetCPUUtilizationPercentage: 70
|
||
metrics:
|
||
- type: Pods
|
||
pods:
|
||
metric:
|
||
name: <metric-name>
|
||
target:
|
||
type: AverageValue
|
||
averageValue: "100"
|
||
```
|
||
|
||
Replace `<metric-name>` with the name your adapter publishes, and set
|
||
`averageValue` to the per-pod value at which you want another replica. Check
|
||
that the adapter serves the metric for the gateway pods:
|
||
|
||
```shell
|
||
kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/namespaces/openshell/pods/*/<metric-name>"
|
||
```
|
||
|
||
### Size PostgreSQL Connections
|
||
|
||
With the default settings, each gateway pod opens up to 14 PostgreSQL
|
||
connections on demand: 10 for data access (`database_max_connections`) and 4
|
||
for mutation locks (`database_lock_max_connections`), both set under
|
||
`gatewayConfig.openshell.gateway`. A request cancelled during
|
||
a lock wait can leave its lock session open for up to 10 seconds, so keep
|
||
headroom. The chart uses the Kubernetes default rolling update strategy for
|
||
each workload kind, so the number of pods that run during a rollout depends on
|
||
the kind.
|
||
|
||
A Deployment rollout adds up to 25 percent of the replica count, rounded up,
|
||
as surge pods. Kubernetes does not count terminating pods against that surge,
|
||
and each replaced pod can keep its connections throughout its termination
|
||
grace period. A rollout can therefore run up to twice the replica count at
|
||
once, and an eviction or an autoscaler scale-down during the rollout adds more
|
||
terminating pods. Set PostgreSQL `max_connections` to at least
|
||
`(2 × replicas + surge) × (data + lock connections)`, which leaves one surge
|
||
of margin for those pods, plus headroom for your other clients and
|
||
administration. Use `autoscaling.maxReplicas` as the replica count when
|
||
autoscaling is enabled. With the defaults, that is
|
||
`(2 × replicas + surge) × 14`:
|
||
|
||
| Replicas | Surge | Minimum `max_connections` |
|
||
|---|---|---|
|
||
| 2 | 1 | `(4 + 1) × 14 = 70` |
|
||
| 3 | 1 | `(6 + 1) × 14 = 98` |
|
||
| 4 | 1 | `(8 + 1) × 14 = 126` |
|
||
| 6 | 2 | `(12 + 2) × 14 = 196` |
|
||
|
||
With a Deployment, three or more replicas exceed what the PostgreSQL default of
|
||
100 leaves for the gateway, because PostgreSQL reserves 3 connections for
|
||
superusers. Raise `max_connections` or use a larger managed instance. Let one
|
||
rollout finish before you start another, because each overlapping rollout adds
|
||
its own terminating pods.
|
||
|
||
If you run several replicas as a StatefulSet with
|
||
`workload.allowMultiReplicaStatefulSet`, a rollout adds no surge pods. It
|
||
replaces one pod at a time and creates each replacement only after the old pod
|
||
exits. Set `max_connections` to at least
|
||
`replicas × (data + lock connections)`, 14 per replica with the defaults,
|
||
using `autoscaling.maxReplicas` when autoscaling is enabled, plus headroom for
|
||
your other clients and administration.
|
||
|
||
Raise `database_lock_max_connections` only when mutation lock timeouts on a
|
||
replica come from a full lock pool: the gateway logs them with the detail
|
||
`waiting for a mutation lock connection`, and
|
||
`openshell_server_mutation_lock_connections_in_use` stays at
|
||
`openshell_server_mutation_lock_connections_capacity`. Also check that the
|
||
replica's own acquisitions are not mostly waiting behind another holder: few
|
||
of its timeouts carry the detail `waiting for a PostgreSQL advisory lock` or
|
||
`canceling statement due to lock timeout`, and `pg_locks` shows the pod's lock
|
||
sessions granted rather than waiting. Otherwise, find the slow holder first,
|
||
because a larger pool only queues more waiters behind it. Each extra lock
|
||
connection adds `2 × replicas + surge` to the minimum `max_connections` for a
|
||
Deployment.
|
||
|
||
If a connection pooler sits between the gateway and PostgreSQL, use session
|
||
pooling. The gateway holds session-level advisory locks, which transaction
|
||
pooling breaks.
|
||
|
||
Mutations lock only what they change. Sandbox operations lock their own
|
||
sandbox, provider and workspace-profile changes lock their workspace, and
|
||
gateway-global policy, settings, and platform-profile changes lock the whole
|
||
fleet. Sandbox start, stop, and delete lock only on the replica that runs them,
|
||
and only a gateway-global change on that replica blocks them directly.
|
||
Provider, workspace-profile, and other replicas' gateway-global changes delay
|
||
them only while another operation on the same sandbox waits behind the change.
|
||
Sandbox create, start, restart, and delete also take one fleet-wide lock while
|
||
they provision or remove the sandbox's SSH host identity, so that step runs for
|
||
one sandbox at a time across all replicas. For other
|
||
mutations, a lock wait longer than 10 seconds returns `UNAVAILABLE` with the
|
||
reason `MUTATION_LOCK_TIMEOUT`, and clients can retry the request. A request
|
||
that carried a `request_id` leaves its admission unresolved, like any other
|
||
error, so a retry with the same ID returns `REQUEST_OUTCOME_UNCERTAIN`. Observe
|
||
resource state and reconcile effects, then send a new request with a new
|
||
`request_id`. Refer to
|
||
[Durable Request Admission](/sdk/api-errors#durable-request-admission).
|
||
|
||
### Upgrade from an Earlier Release
|
||
|
||
With the default settings, each gateway pod now opens up to 14 PostgreSQL
|
||
connections instead of 10. The upgrade rollout already runs new pods at that
|
||
count, so raise `max_connections` to the minimum in
|
||
[Size PostgreSQL Connections](#size-postgresql-connections) before you upgrade.
|
||
|
||
While gateways from the earlier release and the new release run together
|
||
during the upgrade, the older replicas serialize every mutation across the
|
||
fleet. Mutations can be slower and can briefly fail under load until the
|
||
rollout finishes.
|
||
|
||
## Next Steps
|
||
|
||
- To expose the gateway through a highly available data path, refer to
|
||
[Ingress](/kubernetes/ingress).
|
||
- To configure automatic certificate renewal, refer to
|
||
[Managing Certificates](/kubernetes/managing-certificates).
|
||
- To configure user authentication and authorization, refer to
|
||
[Access Control](/kubernetes/access-control).
|
||
- To scrape and alert on gateway metrics, refer to
|
||
[Gateway Metrics](/observability/gateway-metrics).
|