Управляемый сервис PostgreSQL
PostgreSQL в настоящее время является лидирующим выбором среди реляционных баз данных и известен своей надёжной функциональностью и производительностью. Управляемый сервис PostgreSQL использует реализацию на стороне платформы для предоставления самовосстанавливающегося реплицируемого кластера. Этот кластер эффективно управляется с помощью широко признанного оператора CloudNativePG, получившего популярность в сообществе.
Детали развёртывания
Этот управляемый сервис контролируется оператором CloudNativePG, обеспечивающим эффективное управление и бесперебойную работу.
- Документация: https://cloudnative-pg.io/docs/
- Github: https://github.com/cloudnative-pg/cloudnative-pg
Операции
Резервное копирование PostgreSQL имеет два уровня, и в рекомендуемой конфигурации используются оба уровня вместе, а не один из них:
| Слой | Что делает | Настраивается через |
|---|---|---|
| Архивная инфраструктура (чарт, устаревший вариант) | Формирует spec.plugins (со ссылкой на barman-cloud ObjectStore) в ресурсе Cluster cnpg.io начиная с helm-install. CNPG запускает плагин barman-cloud как сайдкар-архиватор WAL: каждое переключение WAL отправляется в объектное хранилище, и любой драйвер резервного копирования получает полную цепочку WAL для начала воспроизведения. Формируется только когда backup.enabled=true, useSystemBucket=false, destinationPath не пусто И заданы встроенные или внешние учётные данные. Пропускается в платформенном режиме useSystemBucket=true — драйвер резервного копирования CNPG применяет ObjectStore через SSA и патчит spec.plugins на живом Cluster в момент первого BackupJob; до этого момента архивирование WAL через плагин не активно, и WAL накапливается на PVC. Запустите разовый BackupJob сразу после включения флага на существующих релизах. | Устаревший вариант: backup.enabled=true плюс backup.destinationPath, backup.endpointURL, и либо backup.s3AccessKey+backup.s3SecretKey, либо backup.s3CredentialsSecret. Платформенный: backup.enabled=true плюс backup.useSystemBucket=true — без полей S3. |
| Оркестрация резервного копирования (рекомендуется) | Управляет разовыми и плановыми резервными копиями, политикой хранения и восстановлениями на основе ресурсов backups.cozystack.io, которые могут охватывать несколько приложений Postgres в тенанте. Драйвер применяет собственный barman-cloud ObjectStore через SSA и патчит spec.plugins с ForceOwnership (так что настройки сжатия/цели берутся из шаблона стратегии, при этом serverName живого Cluster — его префикс S3 для архива WAL — всегда сохраняется); значения, управляемые чартом, покрывают тот же пункт назначения, поэтому конфликта на живом Cluster не возникает. | strategy.backups.cozystack.io/CNPG + BackupClass + Plan (регулярное) или BackupJob (разовое), восстановление через RestoreJob |
| Устаревшее плановое резервное копирование, формируемое чартом | Чарт также может напрямую формировать cnpg.io/ScheduledBackup. Заменён путём BackupClass + Plan, оставлен для кластеров, которые не были мигрированы. Отключён по умолчанию — формируется только когда заданы одновременно backup.enabled и backup.schedule. При backup.schedule="" архивирование WAL через плагин продолжает работать; отключается только формируемое чартом плановое резервное копирование. | backup.enabled=true плюс backup.schedule (cron в формате CNPG из 6 полей, например "0 2 * * * *") |
Канонический вариант настройки зависит от того, поставляется ли в кластере платформенный BackupClass cozy-default.
Платформенный вариант (рекомендуется для новых кластеров) — включается через backup.useSystemBucket: true со ссылкой на cozy-default в BackupJob/Plan/RestoreJob. Чарт оставляет координаты S3 пустыми; драйвер CNPG применяет barman-cloud ObjectStore через SSA и патчит spec.plugins координатами управляемого платформой бакета в момент первого BackupJob.
spec:
backup:
enabled: true
useSystemBucket: true # platform projects cozy-backups-creds + driver SSA-applies ObjectStore + patches spec.plugins
Устаревший вариант, управляемый чартом — для кластеров, созданных до появления платформенного BackupClass, или использующих настроенный нестандартный бакет. Укажите все координаты S3 напрямую (или через s3CredentialsSecret.name); spec.plugins и barman-cloud ObjectStore формируются начиная с helm-install.
spec:
backup:
enabled: true # архивировать WAL в объектное хранилище
destinationPath: s3://my-bucket/pg-src/
endpointURL: https://seaweedfs-s3.tenant-foo:8333
s3CredentialsSecret:
name: pg-src-cnpg-backup-creds
endpointCA:
name: pg-src-cnpg-backup-ca
# backup.schedule намеренно оставлен пустым — BackupClass / Plan
# ниже управляют повторяющимся резервным копированием; никакой
# формируемый чартом ScheduledBackup не должен конкурировать с этим расписанием.
в паре со strategy.backups.cozystack.io/CNPG + BackupClass + Plan
в том же тенанте. Сквозной e2e-фикстур в
examples/backups/postgres/ служит
каноническим примером (05-postgres-src.yaml показывает сторону чарта,
10-cnpg-strategy.yaml и 15-backupclass.yaml показывают сторону
оркестрации, 25-backupjob-adhoc.yaml и 40-restorejob-to-copy.yaml показывают
разовое резервное копирование и восстановление).
Почему нужны оба уровня, а не один? Архивирование WAL выполняется сайдкар-архиватором плагина barman-cloud — CNPG может подключать или отключать плагин во время работы, но любой WAL, закрытый до начала архивирования плагином, теряется безвозвратно. В резервной копии, снятой с такого кластера, отсутствует WAL, на который указывает её
begin_wal, и последующее восстановление завершается ошибкойWAL not found. Если чарт подключает плагин с момента helm-install, эта гонка исключается.
Как включить резервное копирование (предпочтительно: BackupClass + Plan)
Сквозные манифесты находятся в
examples/backups/postgres/.
Кратко, задействованные компоненты:
strategy.backups.cozystack.io/CNPGописывает целевой бакет и шаблонизирует barman-cloudObjectStore(включая ссылку на Secret с учётными данными S3 — эти учётные данные никогда не появляются в.specCR Postgres; см. примечание о безопасности ниже).backups.cozystack.io/BackupClassназывает стратегию и выбирается черезapplicationRef, соответствующийKind/Nameприложения Postgres.backups.cozystack.io/Plan(регулярный) илиBackupJob(разовый), ссылающийся на BackupClass. Контроллер материализует артефактBackup, когда завершается Backup cnpg.io; восстановления затем ссылаются на этот Backup черезRestoreJob.
Поддерживаются как восстановление на месте (перезапись данных исходного приложения), так и
восстановление в копию (восстановление в отдельное целевое приложение Postgres в том же
пространстве имён) через поле
RestoreJob.spec.targetApplicationRef.
Безопасность: при использовании пути BackupClass учётные данные S3 хранятся в доступном тенанту Secret, на который ссылается шаблон стратегии. Драйвер CNPG передаёт эту ссылку на Secret в поле
spec.backup.s3CredentialsSecretприложения Postgres при восстановлении, поэтому ключи доступа никогда не попадают в.specCR Postgres, объектное хранилище etcd или выводkubectl get -o yaml. Предпочитайте этот путь управляемому чартом варианту, когда это возможно.
Как включить управляемые чартом плановые резервные копии (устаревший вариант)
Чарт также может напрямую формировать cnpg.io/ScheduledBackup без
BackupClass. Заменён путём BackupClass + Plan выше и оставлен
для кластеров, которые не были мигрированы. По умолчанию не работает —
backup.schedule по умолчанию является пустой строкой, что отключает
шаблон ScheduledBackup чарта. Чтобы включить, укажите cron-выражение
CNPG из 6 полей:
## @param backup.enabled Включить архивирование WAL через плагин + сформировать управляемый чартом ScheduledBackup
## @param backup.schedule Cron-расписание (формат CNPG из 6 полей). Пусто означает отсутствие управляемого чартом ScheduledBackup
## @param backup.retentionPolicy Политика хранения
## @param backup.destinationPath Путь для хранения резервной копии (например, s3://bucket/path/to/folder)
## @param backup.endpointURL Конечная точка S3, используемая для загрузки данных в облако
## @param backup.s3AccessKey Ключ доступа для S3, используемый для аутентификации
## @param backup.s3SecretKey Секретный ключ для S3, используемый для аутентификации
backup:
enabled: true
retentionPolicy: 30d
destinationPath: s3://bucket/path/to/folder/
endpointURL: http://minio-gateway-service:9000
schedule: "0 2 * * * *" # включение — пусто (по умолчанию) означает отсутствие управляемого чартом расписания
s3AccessKey: oobaiRus9pah8PhohL1ThaeTa4UVa7gu
s3SecretKey: ju3eum4dekeich9ahM1te8waeGai0oog
Как восстановить из резервной копии (предпочтительно: RestoreJob)
Для резервных копий, управляемых через BackupClass, создайте backups.cozystack.io/RestoreJob,
ссылающийся на нужный Backup. См.
examples/backups/postgres/35-restorejob-in-place.yaml
и
examples/backups/postgres/40-restorejob-to-copy.yaml.
При восстановлении в копию контроллер заменяет spec.databases и spec.users
целевого приложения снимком исходного spec, сохранённым
в Backup.status.underlyingResources, так что post-install init-job чарта
не теряет восстановленные роли или базы данных.
Покрытие e2e: восстановление в копию в том же пространстве имён (шаги 0-7) оставляет исходное приложение работающим и служит детерминированным сквозным сигналом; остаётся ручным / dev-cluster эталонным сценарием, не входящим в автоматизированный набор e2e-тестов. Кросс-тенантный вариант (целевой Postgres в другом тенанте, отличном от seaweedfs источника) остаётся ручным / dev-cluster упражнением — доступность заблокирована политикой исходящего трафика Cilium на уровне тенанта. Кодовый путь восстановления на месте поставляется и покрыт на уровне модульных тестов
TestClusterHasRecoveryBootstrap_TerminatingCluster,TestCNPGBackupWALArchived,TestCNPGPurgeNeededи остальными тестами набораinternal/backupcontroller/cnpgstrategy_controller_test.go.
Как восстановить резервную копию (управляемая чартом начальная загрузка)
CloudNativePG поддерживает восстановление на момент времени (point-in-time-recovery). Восстановление резервной копии выполняется путём создания нового экземпляра базы данных и восстановления в него данных.
Создайте новое приложение PostgreSQL с другим именем, но идентичной конфигурацией.
Установите bootstrap.enabled в true и укажите имя экземпляра базы данных, из которого нужно восстановиться, и время восстановления:
## @param bootstrap.enabled Восстановить кластер базы данных из резервной копии
## @param bootstrap.recoveryTime Метка времени (PITR), до которой будет выполнено восстановление, в формате RFC 3339. Если оставить пустым, будет восстановлена последняя
## @param bootstrap.oldName Имя кластера базы данных до удаления
##
bootstrap:
enabled: false
recoveryTime: "" # оставьте пустым для последней или укажите точную метку времени; пример: 2020-11-26 15:22:00.00000+00
oldName: "<previous-postgres-instance>"
Как переключить первичную/вторичную реплику
См.:
storageClassпомечен как неизменяемый (immutable) в схеме чарта — см.docs/storage-immutability.md, где описан этот контракт и какие потребители его обеспечивают.
TLS для серверных подключений
CNPG управляет цепочкой сертификатов сквозным образом. Оператор автоматически генерирует самоподписанный CA, подписывает им конечные (leaf) сертификаты сервера, клиента и репликации и ротирует их по мере необходимости. Чарт не формирует никаких объектов Issuer/Certificate cert-manager — этот путь взаимоисключающий с управляемой оператором цепочкой на admission webhook CNPG.
What the chart contributes: when TLS is on and external: true, the chart sets spec.certificates.serverAltDNSNames on the CNPG Cluster CR to inject the external hostnames <release>.<_namespace.host> and <release>.postgres.<_namespace.host> into the auto-generated server certificate’s SAN list. The second is the per-engine name meant for SNI routing through a TLS-passthrough listener on the tenant Gateway. The certificate covers that name for any client, but routing through such a listener works only when the TLS handshake is the first thing on the wire. With the default negotiation a PostgreSQL client first sends a plaintext SSLRequest, so the listener can route only clients using direct TLS negotiation: PostgreSQL 17 or later on the server and a client connecting with sslnegotiation=direct, such as libpq 17 or pgx 5.7.5. CNPG’s default SAN coverage already includes the three built-in ClusterIP services (-rw, -r, -ro) across the four DNS forms (<svc>, <svc>.<ns>, <svc>.<ns>.svc, <svc>.<ns>.svc.<cluster-domain>); only the external hostnames need to be added.
Трёхпозиционный параметр tls.enabled определяет, внедряет ли чарт serverAltDNSNames:
tls.enabled: null(the default) — TLS posture inherits fromexternal. Whenexternal: true, the chart injects the external hostnames into the operator-managed cert.tls.enabled: truewithexternal: true— same effect as the default.tls.enabled: truewithexternal: false— noserverAltDNSNamesinjection is needed (there is no external hostname to add); CNPG’s auto-generated cert covers internal services.tls.enabled: false— the chart skipsserverAltDNSNamesinjection. Note: CNPG keeps its built-in TLS on the wire regardless of this flag; this toggle only controls whether the external hostnames are added to the cert. To force PostgreSQL to drop TLS entirely you would need to setpostgresql.parameters.ssl = "off"at the CNPG layer, which is out of scope for this flag.
Refusing plaintext sessions. CNPG offers TLS but its built-in last pg_hba rule, host all all all, also accepts plaintext, so a client using sslmode=disable gets an unencrypted session. The tri-state tls.required closes that:
tls.required: null(the default) — followsexternal. Withexternal: truethe chart rendersspec.postgresql.pg_hbaashostssl all all all scram-sha-256followed byhost all all all reject. CNPG puts these after its fixed rules and before its default rule, and the first matching rule wins, so only TLS sessions are authenticated.tls.required: true— the same rules regardless ofexternal.tls.required: false— nopg_hbarules are rendered and CNPG’s default applies, which accepts plaintext.
The rules cover every client, in-cluster ones included, because the pod network cannot be told apart from an external client. libpq’s default sslmode=prefer already negotiates TLS, so only clients that disable TLS explicitly are refused. Instances that were external before this setting existed refuse such clients after the upgrade; set tls.required: false to keep accepting them. See the CloudNativePG
pg_hba documentation.
Получение CA-бандла для проверки на стороне клиента:
The trust anchor is published as postgres-<name>.tenant-ca, where <name> is the name of the Postgres resource: an object holding ca.crt and nothing else, created for every release and delivered to tenants through the core.cozystack.io/tenantsecrets API that the base tenant roles already grant. The postgres- prefix comes from the release naming this application definition applies, so a Postgres named foo gets postgres-foo.tenant-ca.
kubectl --context <ctx> --namespace <tenant> \
get tenantsecret postgres-<name>.tenant-ca \
--output jsonpath='{.data.ca\.crt}' | base64 --decode
That object is the only one that hands over the CA certificate without also handing over a private key, which is why it exists. CNPG creates its own <release>-ca Secret, but that one stores the CA private key (ca.key) alongside the certificate — read access to it would let the holder issue certificates for anything, so it is never granted to a tenant.
It is reached through tenantsecrets rather than by reading the Secret directly, and that is deliberate: tenantsecrets surfaces only objects the platform has vouched for (those the application’s definition selects), whereas a direct grant on the name would convey whatever happens to occupy that name.
Подключение с полной проверкой (пример psql):
psql "host=<host> port=5432 dbname=app user=app \
sslmode=verify-full sslrootcert=ca.crt"
Чтобы sslmode=verify-full работал, полученный выше CA-бандл должен быть сохранён в ca.crt. Без него используйте sslmode=require (шифрует, но не проверяет серверный сертификат).
Параметры
Общие параметры
| Name | Description | Type | Value |
|---|---|---|---|
replicas | Number of Postgres replicas. Under active autoscaling this is the resting/seed count, not the live count — KEDA drives the live count via /scale. Disabling autoscaling does NOT automatically bring the live count back to replicas: the client-side merge writes instances only when the rendered value changes, so a cluster KEDA grew past replicas stays there with no autoscaler left to reduce it — lower replicas to the count you want and it rebases down (shedding the surplus replicas + PVCs). Lowering it below the live count, or disabling/dry-running while it sits below the live count, sheds in one step past the scaleDown pacing; stage it to the live count first (suspend the HelmRelease and kubectl scale if needed) to avoid a transient. Must stay greater than quorum.maxSyncReplicas. | int | 2 |
resources | Explicit CPU and memory configuration for each PostgreSQL replica. When omitted, the preset defined in resourcesPreset is applied. | object | {} |
resources.cpu | CPU available to each replica. | quantity | "" |
resources.memory | Memory (RAM) available to each replica. | quantity | "" |
resourcesPreset | Default sizing preset used when resources is omitted. | string | t1.micro |
size | Persistent Volume Claim size available for application data. | quantity | 10Gi |
storageClass | StorageClass used to store the data. | string | "" |
external | Enable external access from outside the cluster. | bool | false |
version | PostgreSQL major version to deploy | string | v18 |
flavor | PostgreSQL image flavor, fixed when the cluster is created. postgresql uses the CloudNativePG PostgreSQL image. postgis uses the CloudNativePG PostGIS image, which adds postgis, postgis_raster, postgis_topology, postgis_sfcgal, postgis_tiger_geocoder and address_standardizer; enable them per database in databases.<name>.extensions. Changing the flavor of an existing cluster is refused, and a backup restores only into a cluster of the flavor it was taken from: to change flavor, create a new cluster and move the data with a logical dump (pg_dump / pg_restore). | string | postgresql |
Конфигурация TLS
| Name | Description | Type | Value |
|---|---|---|---|
tls | TLS configuration for server connections. | object | {} |
tls.enabled | Tri-state switch controlling whether the chart injects the external hostnames into the operator-managed CNPG cert via spec.certificates.serverAltDNSNames. When omitted, the chart injects them if external: true and skips them otherwise. Set explicitly to true to inject regardless of external (no-op when external: false since there is no external hostname to add). Set to false to skip injection. Note that CNPG keeps its built-in TLS on the wire regardless of this flag — this toggle only controls the chart-side SAN injection; to disable PostgreSQL TLS entirely set postgresql.parameters.ssl = "off" at the CNPG layer. | *bool | null |
tls.required | Tri-state switch controlling whether the server refuses sessions that are not encrypted. When omitted, it is on if external: true and off otherwise. When on, the chart renders spec.postgresql.pg_hba with hostssl all all all scram-sha-256 (md5 on PostgreSQL 13, matching CloudNativePG’s default rule) followed by host all all all reject, so a client that connects with sslmode=disable is refused instead of getting a plaintext session; in-cluster clients are held to the same rule, since the pod network cannot be told apart from an external client. Set to false to keep accepting plaintext sessions on an external instance, or to true to require TLS on an in-cluster one. Rendering fails if postgresql.parameters.ssl is off while this is in effect. | *bool | null |
Параметры, специфичные для приложения
| Name | Description | Type | Value |
|---|---|---|---|
postgresql | PostgreSQL server configuration. | object | {} |
postgresql.sharedPreloadLibraries | Libraries loaded at server start, restricted to an allowlist of modules already shipped in the PostgreSQL image. CloudNativePG also preloads pg_stat_statements, auto_explain and pgaudit by itself whenever parameters sets a key under their prefix (e.g. pg_stat_statements.track), so removing one of them from this list does not unload it while such a key is set; pg_prewarm is preloaded only through this list. Changing the list restarts PostgreSQL on every instance, the primary included, so writes pause briefly. | []string | [] |
postgresql.parameters | PostgreSQL server parameters. Values may be strings or integers; integers are coerced to strings by the template (e.g. both max_connections: 100 and max_connections: "100" are accepted). BLOCKED (enable arbitrary code execution): archive_command, restore_command, ssl_passphrase_command, archive_cleanup_command, recovery_end_command, dynamic_library_path, local_preload_libraries, session_preload_libraries, shared_preload_libraries. Do NOT override CloudNativePG-managed parameters: archive_mode, primary_conninfo, wal_level, max_replication_slots. | map[string]intOrString | {} |
Синхронная репликация на основе кворума
| Name | Description | Type | Value |
|---|---|---|---|
quorum | Quorum configuration for synchronous replication. | object | {} |
quorum.minSyncReplicas | Minimum number of synchronous replicas required for commit. | int | 0 |
quorum.maxSyncReplicas | Maximum number of synchronous replicas allowed (must be less than total replicas). Under autoscaling it also sets the scale-down floor (the effective minimum is max(minReplicas, maxSyncReplicas+1, 2)); the chart fails to render if that floor exceeds autoscaling.maxReplicas. | int | 0 |
Autoscaling
| Name | Description | Type | Value |
|---|---|---|---|
autoscaling | Read-replica autoscaling configuration. | object | {} |
autoscaling.enabled | Enable horizontal autoscaling of read replicas. Requires the platform keda package to be enabled by an administrator first; the chart fails to render (rather than break the release) if KEDA is not installed. Prerequisite: the queried vmselect must hold BOTH the CNPG metrics (cnpg_backends_total / container CPU) AND kube_pod_labels (kube-state-metrics). This holds for a tenant on the shared root monitoring stack (monitoring: false, both land in tenant-root). A tenant running its OWN Monitoring app (monitoring: true) has the CNPG metrics but not kube_pod_labels (KSM is root-only), so it must set serverAddress to a vmselect carrying both series or autoscaling never actuates. | bool | false |
autoscaling.serverAddress | Override the Prometheus/vmselect URL the ScaledObject queries. Empty (default) derives http://vmselect-shortterm.<monitoring-ns>.svc:8481/select/0/prometheus. Set it when the derived vmselect does not hold both the CNPG metrics and kube_pod_labels (e.g. monitoring: true tenants, or a non-default metricsStorages name). SSRF constraint: the host must be an in-cluster Service DNS name (<svc>.<ns>.svc[.<clusterDomain>]) whose namespace is within the tenant’s own subtree (its namespace, its parents, or tenant-root) — the cluster-privileged KEDA operator fetches this URL every poll, so it is refused a metadata endpoint, an external host, or a sibling/system namespace. Residual surface (accepted trade-off): tenant-root is always allowed because the derived default points there, so a tenant can still aim the operator at any Service in tenant-root on any port/path (a blind in-cluster reachability probe — the operator reads no response body back to the tenant); the egress NetworkPolicy does not narrow that. | string | "" |
autoscaling.minReplicas | Minimum total instances; raised to the synchronous-quorum floor (maxSyncReplicas + 1) and to 2 when either is higher. | int | 2 |
autoscaling.maxReplicas | Maximum total instances. Must be >= minReplicas and >= the synchronous-quorum floor (maxSyncReplicas+1); the chart fails to render (rather than silently run an unbounded instance count) if the effective floor exceeds it - raise maxReplicas. HAZARD: lowering maxReplicas below the live count makes the HPA cut straight to the new maximum in one step (the current>max branch bypasses the scale-down pacing), shedding the surplus replicas + PVCs at once; to lower it deliberately, suspend the HelmRelease and pin the live count with kubectl scale first. | int | 6 |
autoscaling.metric | Read-load signal to scale on. | string | ReadConnections |
autoscaling.target | Target read load per read-serving replica (unit depends on metric: active connections, or CPU millicores). Dimensionless integer - a resource.Quantity here would accept 150m, which PromQL reads as 150 minutes and KEDA cannot use as a threshold. | int | 150 |
autoscaling.maxReplicationLagSeconds | Freeze scaling while replication lag exceeds this (seconds) and the primary is writing. 0 disables the brake. Default 0: the freeze branch has only been validated on a live cluster in its non-braking (pass-through) form, so the lag brake is opt-in until the braking path is exercised under load; set a positive value (e.g. 30) to enable it. | int | 0 |
autoscaling.dryRun | Recommendation mode: keep the static count and render the ScaledObject with both scaling directions paused, so KEDA keeps the HPA and keeps serving its trigger metric but actuates neither way. Note both scaling policies are disabled, so the HPA’s desiredReplicas is frozen to the current count - read the recommendation from the matching read-load dashboard panel for your metric (connections or CPU): desired = 1 + ceil(read load / target), clamped to [effectiveMin..maxReplicas] where effectiveMin = max(minReplicas, maxSyncReplicas+1, 2), not from the desired-replicas line. Like disabling, flipping a LIVE autoscaled cluster into dryRun re-renders instances: replicas (the raw static value, which can be below the autoscaling floor); if replicas is below the live count, stage it to the live count first (see the enablement note) or the cluster sheds down to replicas. No shed occurs when the rendered value is unchanged (replicas already equals the active seed) — client-side merge is then a no-op and the live count is preserved. Permanent, unlike transition. | bool | false |
autoscaling.transition | Migration phase 1: render .spec.instances from replicas (which the operator stages to the current live count) AND pause the ScaledObject in both directions, so KEDA stands up with its HPA present but not actuating. Flip to false (phase 2) to hand the runtime count to KEDA. Because the both-direction pause keeps the HPA (not the HPA-deleting full pause), KEDA is genuinely warm at phase 2 — no HPA recreate — and because the active seed is max(replicas, effectiveMin), phase 2 re-renders the same instance count phase 1 did (when replicas is staged at/above the floor), so the flip is a merge no-op with no dip. The HPA’s scaleUp stabilization window still smooths the first actuation. | bool | false |
Конфигурация пользователей
| Name | Description | Type | Value |
|---|---|---|---|
users | Users configuration map. Passwords are always auto-generated and stored in the <release>-credentials Secret; they cannot be set from values — read a user’s password from that Secret. A password left over in values from before the field was removed is ignored by the render and draws an admission warning, but it is not inert on an upgraded release: the chart preserves whatever password is already in the Secret, which on the first upgrade is the value that was set before removal, so that value stays the live credential until it is rotated (dedicated rotation is tracked in cozystack/community#72). The live password lives only in the Secret. | map[string]object | {} |
users[name].replication | Whether the user has replication privileges. | bool | false |
users[name].createRole | Whether the user can create and manage roles (CREATEROLE). Requires PostgreSQL 16 or newer. Setting it back to false withdraws the attribute only: the roles the user created, and its ADMIN and SET memberships in them, stay. Once any user has held it, the chart no longer adopts an existing role it did not create, so a user or database declared later under the name of such a role fails the init job until a platform administrator drops that role. | bool | false |
users[name].bypassRls | Whether the user can bypass row-level security policies (BYPASSRLS). A role can only create other roles carrying BYPASSRLS if it holds the attribute itself, so this is required alongside createRole to provision a privileged service role. | bool | false |
Конфигурация баз данных
| Имя | Описание | Тип | Значение |
|---|---|---|---|
databases | Карта конфигурации баз данных. | map[string]object | {} |
databases[name].roles | Роли, назначенные пользователям. | object | {} |
databases[name].roles.admin | Список пользователей с правами администратора. | []string | [] |
databases[name].roles.readonly | Список пользователей с правами только на чтение. | []string | [] |
databases[name].extensions | Список включённых расширений PostgreSQL. | []string | [] |
Параметры резервного копирования
| Имя | Описание | Тип | Значение |
|---|---|---|---|
backup | Конфигурация резервного копирования. | object | {} |
backup.enabled | Включить регулярное резервное копирование. | bool | false |
backup.useSystemBucket | Опциональная функция: при true пропускается формируемый чартом Secret <release>-s3-creds, И spec.plugins (а также barman-cloud ObjectStore) остаётся НЕ ЗАДАННЫМ в формируемом чартом Cluster — драйвер BackupClass cozy-default применяет ObjectStore через SSA (с destinationPath/endpointURL/учётными данными) и патчит spec.plugins на живом Cluster при запуске первого BackupJob. Следствие: архивирование WAL через плагин НЕ активно до момента срабатывания этого первого BackupJob; тем временем WAL накапливается на PVC, поэтому запустите разовый BackupJob сразу после включения флага на существующих релизах. Используйте вместе с платформенным BackupClass cozy-default — тенантам не нужно заполнять s3AccessKey/s3SecretKey или destinationPath/endpointURL. Путь назначения автоматически ограничивается s3://cozy-backups/<namespace>/<release>/. | bool | false |
backup.schedule | Устаревшее. Cron-расписание (формат CNPG из 6 полей) для формируемого чартом ScheduledBackup. Пусто означает отсутствие управляемого чартом расписания, что является рекомендуемой настройкой, когда BackupClass из backups.cozystack.io уже управляет оркестрацией резервного копирования. В устаревшем управляемом чартом варианте spec.plugins вместе с barman-cloud ObjectStore формируется, когда backup.enabled=true И useSystemBucket=false И destinationPath не пусто И заданы встроенные или внешние учётные данные; в платформенном варианте useSystemBucket=true чарт пропускает формирование spec.plugins, а драйвер CNPG применяет ObjectStore через SSA и патчит spec.plugins на живом Cluster в момент первого BackupJob. | string | "" |
backup.retentionPolicy | Политика хранения (например, “30d”). | string | 30d |
backup.destinationPath | УСТАРЕЛО. Настройка S3 на уровне тенанта заменена управляемым платформой BackupClass cozy-default и системным бакетом cozy-backups. Оставьте пустым для новых установок; драйвер BackupClass использует управляемые системой координаты. Сохранено для совместимости при обновлении на месте. | string | s3://bucket/path/to/folder/ |
backup.endpointURL | УСТАРЕЛО. См. destinationPath. | string | http://minio-gateway-service:9000 |
backup.s3AccessKey | УСТАРЕЛО. Тенанты больше не предоставляют ключи S3; системный Secret с бакетом проецируется в пространство имён тенанта контроллером резервного копирования. Игнорируется, если задан s3CredentialsSecret.name или useSystemBucket равен true. Чарт пропускает материализацию <release>-s3-creds, если это поле пустое, чтобы стандартная установка не раскрывала заглушки учётных данных в пространство имён тенанта. | string | "" |
backup.s3SecretKey | УСТАРЕЛО. См. s3AccessKey. | string | "" |
backup.s3CredentialsSecret | УСТАРЕЛО. Существующий Secret с учётными данными S3. Используйте вместо этого управляемый платформой BackupClass cozy-default. Если задан, чарт ссылается на этот Secret напрямую (устаревший управляемый чартом вариант). Драйвер резервного копирования CNPG записывает это поле при восстановлении, поэтому учётные данные никогда не попадают в .spec CR. | object | {} |
backup.s3CredentialsSecret.name | Имя Secret в пространстве имён приложения. Пусто означает, что чарт материализует <release>-s3-creds из s3AccessKey/s3SecretKey. | string | "" |
backup.s3CredentialsSecret.accessKeyIDKey | Ключ в Secret, содержащий идентификатор ключа доступа. По умолчанию AWS_ACCESS_KEY_ID. | string | "" |
backup.s3CredentialsSecret.secretAccessKeyKey | Ключ в Secret, содержащий секретный ключ доступа. По умолчанию AWS_SECRET_ACCESS_KEY. | string | "" |
backup.endpointCA | УСТАРЕЛО. Существующий Secret с пакетом CA, которому должен доверять плагин barman-cloud при обращении к самоподписанной конечной точке S3. Используется как для резервного копирования, так и для восстановления при начальной загрузке в устаревшем управляемом чартом варианте. | object | {} |
backup.endpointCA.name | Имя Secret в пространстве имён приложения. Пусто означает, что endpointCA не формируется (плагин использует системное хранилище доверия). | string | "" |
backup.endpointCA.key | Ключ в Secret, содержащий пакет CA. По умолчанию ca.crt. | string | "" |
Параметры начальной загрузки (восстановления)
| Name | Description | Type | Value |
|---|---|---|---|
bootstrap | Bootstrap configuration. | object | {} |
bootstrap.enabled | Whether to restore from a backup. | bool | false |
bootstrap.recoveryTime | Timestamp (RFC3339) for point-in-time recovery; empty means latest. | string | "" |
bootstrap.backupID | Barman ID of the base backup to recover from, passed as recoveryTarget.backupID. Empty lets the barman-cloud plugin pick one: the newest backup when recoveryTime is empty, otherwise the newest one ending at or before it, on any timeline. The CNPG backup driver sets this on restore. | string | "" |
bootstrap.oldName | Previous cluster name before deletion. | string | "" |
bootstrap.serverName | Server name (S3 path prefix) used by the original cluster when writing backups; passed to the barman-cloud plugin via externalClusters[].plugin.parameters.serverName. Defaults to bootstrap.oldName. Set this only when the original cluster wrote backups under an explicit server name that differed from its Kubernetes resource name. | string | "" |
bootstrap.newServerName | WAL-archive server name (S3 path prefix) the RESTORED cluster writes to. Must differ from serverName (the recovery source) so a restored cluster archives to a fresh, empty prefix and barman-cloud-check-wal-archive passes while it recovers from the source’s prefix. The CNPG backup driver sets this on restore; empty means the cluster archives under its own name. | string | "" |
Примеры и справочник по параметрам
resources и resourcesPreset
resources and resourcesPreset
resources sets explicit CPU and memory configurations for each replica.
Every resource it leaves unset is taken from the preset defined in resourcesPreset.
resources:
cpu: 4000m
memory: 4Gi
resourcesPreset задаёт именованные конфигурации CPU и памяти для каждой реплики.
Эта настройка игнорируется, если задано соответствующее значение resources.
Presets follow a cloud-style <series>.<size> naming convention. Five series cover the full CPU-to-memory ratio range (t1 1:0.5, c1 1:1, s1 1:2, u1 1:4, m1 1:8) and each series ships eight sizes (nano through 4xlarge). The legacy flat names (nano, micro, small, medium, large, xlarge, 2xlarge) remain accepted as deprecated aliases and keep their original sizes, which do not follow one series: nano through small equal the t1 sizes of the same name, while medium equals c1.small rather than c1.medium.
См.
docs/operations/resource-presets.md, где приведены полная матрица размеров и сопоставление устаревших имён с типами инстансов.
users
users:
user1: {}
user2: {}
airflow: {}
debezium:
replication: true
Passwords cannot be set here — they are auto-generated and stored in the <release>-credentials Secret. Read a user’s password with kubectl get secret <release>-credentials -o json | jq -r '.data["user1"]' | base64 -d (a username may contain a ., which jsonpath would treat as a path step and return nothing).
databases
databases:
myapp:
roles:
admin:
- user1
- debezium
readonly:
- user2
airflow:
roles:
admin:
- airflow
extensions:
- hstore
A database name may contain only letters, digits and -._, and must be at most 54 characters. Renaming a database by changing its key in values makes the init-job drop the old database with its data. To keep the data, a platform administrator first renames it as the CNPG superuser (ALTER DATABASE "<old>" RENAME TO <new>, ALTER ROLE "<old>_admin" RENAME TO <new>_admin and the same for _readonly), and only then is the key changed; the chart then adopts the renamed database on the next reconcile.