mirror of
https://github.com/cozystack/cozystack.git
synced 2026-12-02 21:30:46 +09:00
Refs #5459 (item 3: "Waiting for rollout eats Job budget").
**Depends on #5505.** Merge #5505 first or together with this PR. Here a
failed repair no longer fails the HelmRelease. #5505 makes the
WorkloadMonitor report the failed repair Job as `WorkloadsReady=False`
with reason `JobFailed`. Without it the failure shows only on the Job
itself.
Moving tenant PostgreSQL to another image (for example bullseye `17.7`
to `17.12-standard-trixie`) fails the first Helm upgrade of every
release whose clients keep sessions open. The collation repair at the
end of the post-upgrade init-job waits for CNPG to move the primary to
the new image. CNPG rolls the primary last, and every instance spends up
to `smartShutdownTimeout` (180 s) in smart shutdown, so the wait uses up
the init-job's 540 s deadline and the HelmRelease goes `UpgradeFailed`
until Flux retries. When the repair instead meets the primary restart,
psql fails with `FATAL: the database system is shutting down` and the
upgrade fails the same way.
The one commit moves the repair out of the hook. A short
post-install/post-upgrade hook, run after the init-job, creates a
`<release>-collation-repair` Job through the API (outside the release,
so helm-controller does not wait for it) and returns. That Job keeps the
OID mark / fingerprint resume and the in-place attempt records. It waits
for the new image whenever the image changes, not only when an index
already depends on a versioned collation: a plan built on the previous
primary would miss an index created meanwhile, which the release
recorded at the end would then claim as repaired. In the hook that wait
was too expensive to make unconditional. The Job gets an hour, is owned
by the Cluster, and its fixed name keeps two repairs from running at
once. It carries the WorkloadMonitor's selector labels plus the opt-in
`workloads.cozystack.io/report-failure: "true"` from #5505, and has no
`ttlSecondsAfterFinished`, so a failed repair stays until the next
upgrade replaces it (see the proposal in #5459). Both Jobs now rerun
their idempotent script on psql exit status 2 (connection refused or
dropped) with backoff instead of failing.
Decisions for reviewers:
- **Repair failures no longer fail the HelmRelease.** A repair that
cannot finish (for example duplicates under a UNIQUE index) shows up as
a Failed `<release>-collation-repair` Job and its log, kept until the
next upgrade starts a new run. The next upgrade retries it. Before, it
showed up as `UpgradeFailed`.
- **The repair also runs after install.** The install-time init-job used
to record which Debian release each database starts on. Without that
record, a cluster whose first upgrade moves the image would have its C.*
indexes rebuilt only if the repair reached the primary before it
restarted. On a fresh cluster the run only writes that record. The Job
sets `PGCONNECT_TIMEOUT=10`.
- **A failed rebuild no longer holds back the PostGIS update.** The
update runs after the collation pass whatever it found, and the Job
still fails at the end if a rebuild failed.
- **The e2e upgrades twice.** The second upgrade finds the first repair
Job complete on the same image, and the test waits for its replacement
to complete.
- **Lock waits are bounded by the Job's remaining hour, not about 8
minutes.** This is harmless for `REINDEX CONCURRENTLY`. For the in-place
rebuild of an exclusion-constraint index, writers to that table can
queue behind its lock wait for longer. Capping it separately means
touching the per-index code that the parallel PRs on #5459 also edit, so
I left it out.
- **The hook's Role** has `get`/`delete` on the repair Job and `get` on
the release's Cluster, both by `resourceNames`. It also has `create` on
jobs, which RBAC cannot narrow by name. The SA, Role and RoleBinding are
deleted once the hooks succeed.
- **Verified under Flux.** helm-controller v1.5.0 runs the post-upgrade
hooks about a second after it patches the Cluster, without waiting for
the rollout. The rollout therefore no longer counts against the release
timeout. Details in the PR thread.
Rebased onto main after #5477 and #5485. The PostGIS extension update
from #5477 waits for the same rollout, so it moves into `repair.sh`
after the collation pass; left in the init-job, it would bring the
hook-budget problem back for postgis clusters. Every message about a
repair or update that did not finish says that the next upgrade of the
release starts it again. The starter and the repair Job take their names
from one base, which stays distinct and within 63 characters for any
release name.
- `helm unittest packages/apps/postgres`: 32 suites, 257 tests pass,
including a new `collation_repair_test.yaml`. It checks gating (upgrade
only, skipped while bootstrap is on), hook order after the init-job, the
Role rules, RBAC removal on success, name length, and the init-job
command.
- Docker, with the rendered `run.sh` + `repair.sh` against
`postgres:17-bullseye` and stale ICU / en_US collations:
- Killing the `REINDEX INDEX CONCURRENTLY` backend mid-rebuild made the
pass exit 2. `run.sh` reran it, the already rebuilt index was skipped by
the OID mark, and the other index was rebuilt. amcheck was clean and the
versions were refreshed.
- With the server stopped before the first connection, the script
retried with 5 s and 10 s pauses and finished once the server came back.
- An SQL error exits 1 and is not retried.
- dev7 (cozystack v1.7.0): two 3-instance v17 releases installed from
v1.7.1 (bullseye `17.7`), with ICU and en_US UNIQUE indexes on 200k rows
and `pg_sleep(3600)` sessions held on `-rw` and `-ro`. Both were
upgraded with `helm upgrade --timeout 10m`:
- origin/main: the init-job waited for `PostgreSQL 17.12 pgdg13`, hit
`DeadlineExceeded`, and the command failed with `UPGRADE FAILED:
post-upgrade hooks failed: resource Job/tenant-root/rr-main-init-job not
ready. status: Failed` (exit 1 after 611 s).
- This branch: exit 0 after 70 s (init-job 9 s, starter 10 s, starter
RBAC removed afterwards). The repair Job waited out the rollout and
rebuilt `t_u` and `t_k`. Collation versions were refreshed to `2.41` /
`153.128`, `bt_index_check(..., true)` passed on all three instances,
and the resume mark was reset.
- A second upgrade replaced the finished repair Job, and the rerun found
nothing to do.
- The rebuild sat in `waiting for old snapshots` behind the test
client's open transaction. That is expected for `REINDEX CONCURRENTLY`;
I ended that session to finish the run.
Walked against the diff (the new template, test and init-script/init-job
changes in `packages/apps/postgres`). The diff changes no values,
schema, `ApplicationDefinition`, Secret or Service names, package
layout, or tooling. The only new objects are a hook-scoped
ServiceAccount/Role/RoleBinding/Job and a Job created at runtime, which
no listed repository refers to.
- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:
- Flux (dev cluster, helm-controller v1.5.0): a tenant app on the v1.7.0
chart (bullseye `17.7`, 3 instances, sessions held on `-rw`/`-ro`) was
upgraded by switching the platform's postgres chart.
- With this PR, the HelmRelease reached `UpgradeSucceeded` in 21 s, and
the repair Job finished after the rollout with `bt_index_check` clean on
all instances.
- With main, the upgrade took 7 min 06 s of the 10-minute timeout.
- Docker: the rendered `repair.sh` for the postgis flavor moved PostGIS
3.6.1 → 3.7.0 after the collation pass. A tenant trigger on
`spatial_ref_sys` did not run.
```release-note
[postgres] An image change of a tenant PostgreSQL no longer fails the Helm upgrade while CNPG rolls the instances. The collation repair now runs in a separate `<release>-collation-repair` Job, started after each upgrade, which waits for the new image and retries after connection drops. Check that Job's status and log to confirm the repair finished.
```
release-1.6 has no postgis flavor, so the PostGIS extension update that
follows the collation pass in repair.sh on main is not carried over, and
repair.sh ends with the collation pass's own exit status; nothing in the
chart reads .Values.flavor. It has no adopted-restore record either, so
the step that writes one, which the split moved to the end of init.sh on
main, is not carried over. The init-job comment no longer describes the
collation pass, which left that Job here, and says what JOB_DEADLINE
bounds there now: the reruns of run.sh.
(cherry picked from commit c8ffc87717)
Assisted-By: LLM
Signed-off-by: Andrey Kolkov <androndo@gmail.com>
578 lines
34 KiB
YAML
578 lines
34 KiB
YAML
{{- $existingSecret := lookup "v1" "Secret" .Release.Namespace (printf "%s-credentials" .Release.Name) }}
|
|
{{- $passwords := dict }}
|
|
|
|
{{- with (index $existingSecret "data") }}
|
|
{{- range $k, $v := . }}
|
|
{{- $_ := set $passwords $k (b64dec $v) }}
|
|
{{- end }}
|
|
{{- end }}
|
|
|
|
{{- range $user, $u := .Values.users }}
|
|
{{- if $u.password }}
|
|
{{- $_ := set $passwords $user $u.password }}
|
|
{{- else if not (index $passwords $user) }}
|
|
{{- $_ := set $passwords $user (randAlphaNum 16) }}
|
|
{{- end }}
|
|
{{- end }}
|
|
|
|
{{- if .Values.users }}
|
|
apiVersion: v1
|
|
kind: Secret
|
|
metadata:
|
|
name: {{ .Release.Name }}-credentials
|
|
stringData:
|
|
{{- range $user, $u := .Values.users }}
|
|
{{ quote $user }}: {{ quote (index $passwords $user) }}
|
|
{{- end }}
|
|
{{- end }}
|
|
{{/*
|
|
Skip the init-script Secret while bootstrap.recovery is in effect.
|
|
It only feeds the init-job Job, which is also skipped in that mode
|
|
(see init-job.yaml header comment). Keeping it would leave a stale
|
|
Secret without a consumer; dropping it keeps the chart output minimal.
|
|
*/}}
|
|
{{- if not .Values.bootstrap.enabled }}
|
|
---
|
|
apiVersion: v1
|
|
kind: Secret
|
|
metadata:
|
|
name: {{ .Release.Name }}-init-script
|
|
stringData:
|
|
run.sh: |
|
|
#!/bin/bash
|
|
{{- /*
|
|
Both Jobs reach the server through the -rw Service while CNPG may be
|
|
restarting the instance behind it. psql exits with status 2 both when the
|
|
server refuses the connection ("the database system is shutting down")
|
|
and when it drops one mid-session, and each script is safe to run again
|
|
from the top, so that status reruns the script after a growing pause
|
|
instead of failing the Job; any other status is final. The child is
|
|
handed $SECONDS, which bash keeps counting from, so every bound a script
|
|
measures against it still counts from the first attempt.
|
|
*/}}
|
|
delay=5
|
|
until SECONDS=$SECONDS bash "$1"; do
|
|
status=$?
|
|
if [ "$status" -ne 2 ] || [ $((SECONDS + delay)) -ge $((JOB_DEADLINE - 60)) ]; then
|
|
exit "$status"
|
|
fi
|
|
echo "lost the connection to the server; running $1 again in ${delay}s" >&2
|
|
sleep "$delay"
|
|
delay=$((delay * 2 > 60 ? 60 : delay * 2))
|
|
done
|
|
init.sh: |
|
|
#!/bin/bash
|
|
set -e
|
|
|
|
until pg_isready ; do sleep 5; done
|
|
|
|
echo "== create users"
|
|
{{- if and .Values.users (not (hasKey .Values.users "postgres")) }}
|
|
psql -v ON_ERROR_STOP=1 <<\EOT
|
|
{{- range $user, $u := .Values.users }}
|
|
SELECT 'CREATE ROLE "{{ $user }}" LOGIN INHERIT;'
|
|
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{{ $user }}')\gexec
|
|
ALTER ROLE "{{ $user }}" WITH PASSWORD '{{ index $passwords $user }}' LOGIN INHERIT {{ ternary "REPLICATION" "NOREPLICATION" (default false $u.replication) }};
|
|
COMMENT ON ROLE "{{ $user }}" IS 'user managed by helm';
|
|
{{- end }}
|
|
EOT
|
|
{{- else if and .Values.users (hasKey .Values.users "postgres") }}
|
|
{{- fail "`users.postgres` is forbidden by policy. Use a different username." }}
|
|
{{- end }}
|
|
|
|
echo "== delete users"
|
|
MANAGED_USERS=$(echo '\du+' | psql | awk -F'|' '$4 == " user managed by helm" {print $1}' | awk NF=NF RS= OFS=' ')
|
|
DEFINED_USERS="{{ join " " (keys .Values.users) }}"
|
|
DELETE_USERS=$(for user in $MANAGED_USERS; do case " $DEFINED_USERS " in *" $user "*) :;; *) echo $user;; esac; done)
|
|
|
|
echo "users to delete: $DELETE_USERS"
|
|
for user in $DELETE_USERS; do
|
|
# https://stackoverflow.com/a/51257346/2931267
|
|
psql -v ON_ERROR_STOP=1 --echo-all <<EOT
|
|
REASSIGN OWNED BY $user TO postgres;
|
|
DROP OWNED BY $user;
|
|
DROP USER $user;
|
|
EOT
|
|
done
|
|
|
|
echo "== delete databases"
|
|
MANAGED_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database d JOIN pg_shdescription s ON d.oid = s.objoid WHERE s.description = 'database managed by helm'")
|
|
DEFINED_DBS="{{ join " " (keys .Values.databases | sortAlpha) }}"
|
|
DELETE_DBS=$(for db in $MANAGED_DBS; do case " $DEFINED_DBS " in *" $db "*) :;; *) echo $db;; esac; done)
|
|
|
|
echo "databases to delete: $DELETE_DBS"
|
|
for db in $DELETE_DBS; do
|
|
psql -v ON_ERROR_STOP=1 --echo-all -c "DROP DATABASE IF EXISTS \"$db\" WITH (FORCE);"
|
|
done
|
|
|
|
echo "== delete orphaned managed roles"
|
|
MANAGED_ROLES=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT rolname FROM pg_roles r JOIN pg_shdescription s ON r.oid = s.objoid WHERE s.description = 'role managed by helm'")
|
|
DEFINED_ROLES="{{ range $database, $d := .Values.databases }}{{ $database }}_admin {{ $database }}_readonly {{ end }}"
|
|
DELETE_ROLES=$(for role in $MANAGED_ROLES; do case " $DEFINED_ROLES " in *" $role "*) :;; *) echo $role;; esac; done)
|
|
|
|
echo "roles to delete: $DELETE_ROLES"
|
|
for role in $DELETE_ROLES; do
|
|
psql -v ON_ERROR_STOP=1 --echo-all <<EOT
|
|
DO \$\$
|
|
DECLARE
|
|
member record;
|
|
BEGIN
|
|
FOR member IN SELECT m.rolname FROM pg_auth_members am JOIN pg_roles m ON am.member = m.oid JOIN pg_roles r ON am.roleid = r.oid WHERE r.rolname = '$role' LOOP
|
|
EXECUTE format('REVOKE %I FROM %I', '$role', member.rolname);
|
|
END LOOP;
|
|
END\$\$;
|
|
REASSIGN OWNED BY "$role" TO postgres;
|
|
DROP OWNED BY "$role";
|
|
DROP ROLE IF EXISTS "$role";
|
|
EOT
|
|
done
|
|
|
|
echo "== create databases and roles"
|
|
{{- if .Values.databases }}
|
|
psql -v ON_ERROR_STOP=1 --echo-all <<\EOT
|
|
{{- range $database, $d := .Values.databases }}
|
|
SELECT 'CREATE DATABASE "{{ $database }}"'
|
|
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '{{ $database }}')\gexec
|
|
COMMENT ON DATABASE "{{ $database }}" IS 'database managed by helm';
|
|
SELECT 'CREATE ROLE "{{ $database }}_admin" NOINHERIT;'
|
|
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{{ $database }}_admin')\gexec
|
|
COMMENT ON ROLE "{{ $database }}_admin" IS 'role managed by helm';
|
|
SELECT 'CREATE ROLE "{{ $database }}_readonly" NOINHERIT;'
|
|
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{{ $database }}_readonly')\gexec
|
|
COMMENT ON ROLE "{{ $database }}_readonly" IS 'role managed by helm';
|
|
{{- end }}
|
|
EOT
|
|
{{- end }}
|
|
|
|
echo "== grant privileges on databases to roles"
|
|
{{- range $database, $d := .Values.databases }}
|
|
psql -v ON_ERROR_STOP=1 --echo-all -d "{{ $database }}" <<\EOT
|
|
ALTER DATABASE "{{ $database }}" OWNER TO "{{ $database }}_admin";
|
|
GRANT CONNECT ON DATABASE "{{ $database }}" TO "{{ $database }}_readonly";
|
|
|
|
DO $$
|
|
DECLARE
|
|
schema_record record;
|
|
BEGIN
|
|
-- Loop over all schemas
|
|
FOR schema_record IN SELECT schema_name FROM information_schema.schemata WHERE schema_name NOT IN ('pg_catalog', 'information_schema') LOOP
|
|
-- Changing Schema Ownership
|
|
EXECUTE format('ALTER SCHEMA %I OWNER TO %I', schema_record.schema_name, '{{ $database }}_admin');
|
|
|
|
-- Add rights for the admin role
|
|
EXECUTE format('GRANT ALL ON SCHEMA %I TO %I', schema_record.schema_name, '{{ $database }}_admin');
|
|
EXECUTE format('GRANT ALL ON ALL TABLES IN SCHEMA %I TO %I', schema_record.schema_name, '{{ $database }}_admin');
|
|
EXECUTE format('GRANT ALL ON ALL SEQUENCES IN SCHEMA %I TO %I', schema_record.schema_name, '{{ $database }}_admin');
|
|
EXECUTE format('GRANT ALL ON ALL FUNCTIONS IN SCHEMA %I TO %I', schema_record.schema_name, '{{ $database }}_admin');
|
|
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT ALL ON TABLES TO %I', schema_record.schema_name, '{{ $database }}_admin');
|
|
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT ALL ON SEQUENCES TO %I', schema_record.schema_name, '{{ $database }}_admin');
|
|
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT ALL ON FUNCTIONS TO %I', schema_record.schema_name, '{{ $database }}_admin');
|
|
|
|
-- Add rights for the readonly role
|
|
EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', schema_record.schema_name, '{{ $database }}_readonly');
|
|
EXECUTE format('GRANT SELECT ON ALL TABLES IN SCHEMA %I TO %I', schema_record.schema_name, '{{ $database }}_readonly');
|
|
EXECUTE format('GRANT USAGE ON ALL SEQUENCES IN SCHEMA %I TO %I', schema_record.schema_name, '{{ $database }}_readonly');
|
|
EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA %I TO %I', schema_record.schema_name, '{{ $database }}_readonly');
|
|
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT SELECT ON TABLES TO %I', schema_record.schema_name, '{{ $database }}_readonly');
|
|
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT USAGE ON SEQUENCES TO %I', schema_record.schema_name, '{{ $database }}_readonly');
|
|
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT EXECUTE ON FUNCTIONS TO %I', schema_record.schema_name, '{{ $database }}_readonly');
|
|
END LOOP;
|
|
END$$;
|
|
EOT
|
|
|
|
echo "== setup event trigger for schema creation"
|
|
psql -v ON_ERROR_STOP=1 --echo-all -d "{{ $database }}" <<\EOT
|
|
CREATE OR REPLACE FUNCTION auto_grant_schema_privileges()
|
|
RETURNS event_trigger LANGUAGE plpgsql AS $$
|
|
DECLARE
|
|
obj record;
|
|
BEGIN
|
|
FOR obj IN SELECT * FROM pg_event_trigger_ddl_commands() WHERE command_tag = 'CREATE SCHEMA' LOOP
|
|
EXECUTE format('ALTER SCHEMA %I OWNER TO %I', obj.object_identity, '{{ $database }}_admin');
|
|
EXECUTE format('GRANT ALL ON SCHEMA %I TO %I', obj.object_identity, '{{ $database }}_admin');
|
|
EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', obj.object_identity, '{{ $database }}_readonly');
|
|
EXECUTE format('GRANT SELECT ON ALL TABLES IN SCHEMA %I TO %I', obj.object_identity, '{{ $database }}_readonly');
|
|
EXECUTE format('GRANT USAGE ON ALL SEQUENCES IN SCHEMA %I TO %I', obj.object_identity, '{{ $database }}_readonly');
|
|
EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA %I TO %I', obj.object_identity, '{{ $database }}_readonly');
|
|
|
|
-- Set owner for schema
|
|
EXECUTE format('ALTER SCHEMA %I OWNER TO %I', obj.object_identity, '{{ $database }}_admin');
|
|
|
|
-- Set privileges for admin role
|
|
EXECUTE format('GRANT ALL ON SCHEMA %I TO %I', obj.object_identity, '{{ $database }}_admin');
|
|
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT ALL ON TABLES TO %I', obj.object_identity, '{{ $database }}_admin');
|
|
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT ALL ON SEQUENCES TO %I', obj.object_identity, '{{ $database }}_admin');
|
|
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT ALL ON FUNCTIONS TO %I', obj.object_identity, '{{ $database }}_admin');
|
|
|
|
-- Set privileges for readonly role
|
|
EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', obj.object_identity, '{{ $database }}_readonly');
|
|
EXECUTE format('GRANT SELECT ON ALL TABLES IN SCHEMA %I TO %I', obj.object_identity, '{{ $database }}_readonly');
|
|
EXECUTE format('GRANT USAGE ON ALL SEQUENCES IN SCHEMA %I TO %I', obj.object_identity, '{{ $database }}_readonly');
|
|
EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA %I TO %I', obj.object_identity, '{{ $database }}_readonly');
|
|
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT SELECT ON TABLES TO %I', obj.object_identity, '{{ $database }}_readonly');
|
|
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT USAGE ON SEQUENCES TO %I', obj.object_identity, '{{ $database }}_readonly');
|
|
EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT EXECUTE ON FUNCTIONS TO %I', obj.object_identity, '{{ $database }}_readonly');
|
|
END LOOP;
|
|
END;
|
|
$$;
|
|
|
|
DROP EVENT TRIGGER IF EXISTS trigger_auto_grant;
|
|
CREATE EVENT TRIGGER trigger_auto_grant ON ddl_command_end
|
|
WHEN TAG IN ('CREATE SCHEMA')
|
|
EXECUTE PROCEDURE auto_grant_schema_privileges();
|
|
EOT
|
|
{{- end }}
|
|
|
|
echo "== assign roles to users"
|
|
psql -v ON_ERROR_STOP=1 --echo-all <<\EOT
|
|
{{- range $database, $d := .Values.databases }}
|
|
{{- range $user, $u := $.Values.users }}
|
|
{{- if has $user $d.roles.admin }}
|
|
GRANT "{{ $database }}_admin" TO "{{ $user }}";
|
|
{{- else }}
|
|
REVOKE "{{ $database }}_admin" FROM "{{ $user }}";
|
|
{{- end }}
|
|
{{- if has $user $d.roles.readonly }}
|
|
GRANT "{{ $database }}_readonly" TO "{{ $user }}";
|
|
{{- else }}
|
|
REVOKE "{{ $database }}_readonly" FROM "{{ $user }}";
|
|
{{- end }}
|
|
{{- end }}
|
|
{{- end }}
|
|
EOT
|
|
|
|
echo "== create extensions"
|
|
{{- range $database, $d := .Values.databases }}
|
|
{{- if $d.extensions }}
|
|
psql -v ON_ERROR_STOP=1 --echo-all -d "{{ $database }}" <<\EOT
|
|
{{- range $extension := $d.extensions }}
|
|
CREATE EXTENSION IF NOT EXISTS {{ $extension }};
|
|
{{- end }}
|
|
EOT
|
|
{{- end }}
|
|
{{- end }}
|
|
repair.sh: |
|
|
#!/bin/bash
|
|
set -e
|
|
{{- /*
|
|
An operand image built on another Debian release ships another glibc and
|
|
ICU, and an index ordered by a collation of either library is then
|
|
ordered by rules the server no longer applies: lookups miss rows and a
|
|
unique index stops seeing duplicates. PostgreSQL records the library
|
|
version each collation was created with, so a collation whose recorded
|
|
version differs from the one the server reports marks the indexes to
|
|
rebuild. The C and POSIX collations carry no version and never qualify,
|
|
which is every index of a database this chart created with its defaults.
|
|
|
|
PostgreSQL records a collation for an index only where it orders a key.
|
|
A collation can also decide what an index holds without ordering it, in
|
|
a predicate or inside an expression, and for those the catalog names
|
|
the columns the index reads and nothing else. The collations of those
|
|
columns therefore count as well. That rebuilds an index or two that did
|
|
not need it, and still misses a collation that an expression applies to
|
|
a column of another one.
|
|
|
|
This pass runs in a Job of its own, which a post-upgrade hook starts
|
|
once the init-job has managed roles and databases, and which Helm does
|
|
not wait for. The hook runs as soon as the Cluster is patched, while
|
|
CNPG is still rolling the instances, the primary last, and an instance
|
|
whose clients keep their sessions open waits out smartShutdownTimeout
|
|
before it restarts: the rollout alone can take longer than Helm gives a
|
|
hook, and the rebuild of a large index as long again, so inside the
|
|
hook either one failed the upgrade. Here a rebuild that fails costs
|
|
nothing else, and the next upgrade starts the Job again.
|
|
|
|
The primary may therefore answer from the previous image for minutes.
|
|
The Job runs the image the Cluster is moving to, so
|
|
the server is on it once both report the same PostgreSQL version and
|
|
the same Debian release. The rebuild counter that follows them is left
|
|
out: a tag is rebuilt in place, so the Job and an instance can run
|
|
different rebuilds of one release for good. The pass waits for that
|
|
whenever the image changes, even when no index depends on a collation
|
|
yet: a plan made on the previous image misses an index created in the
|
|
meantime, which the release recorded at the end would then claim as
|
|
repaired. The wait ends 120 seconds before the Job's deadline, which is
|
|
what a first run keeps for rebuilding.
|
|
|
|
Rebuilds survive a retry: REINDEX CONCURRENTLY gives the index a new
|
|
OID, so the highest OID seen when the repair began separates the
|
|
indexes still to rebuild from the ones already done. That mark is kept
|
|
as a setting of the database, next to a fingerprint of the stale
|
|
collations and their new versions, so another library change starts a
|
|
new repair. An exclusion constraint's index cannot be rebuilt
|
|
concurrently: its table is neither read nor written while it is rebuilt
|
|
in place, and it keeps its OID. The same setting therefore records each
|
|
attempt at one together with the index's storage file: a file that has
|
|
changed since means the index was rebuilt, by a run or by hand, and two
|
|
attempts on the same file mean two runs did not finish, after which the
|
|
index is left to an operator. The rebuild is given what is left of the
|
|
Job and no more, so that the table is not kept locked by a backend the
|
|
Job no longer waits for.
|
|
|
|
A transaction that stays open on the table makes a rebuild wait for a
|
|
lock. That wait is bounded by what is left of the Job as well, so that
|
|
no backend is left waiting for a lock after the Job is gone. A
|
|
concurrent rebuild that is already running is not cut short: it blocks
|
|
nobody, and the index it finishes counts as done. Both bounds keep a
|
|
minute in reserve: the deadline counts from the start of the Job,
|
|
$SECONDS from the start of this script.
|
|
|
|
Such a rebuild outlives the run that started it: its backend does not
|
|
notice that the Job is gone until the rebuild ends. REINDEX finds an
|
|
index by name, and once it has waited behind that rebuild the name
|
|
belongs to the index the rebuild put in place, which would then be
|
|
rebuilt a second time. An index is therefore skipped, and reported like
|
|
a failed rebuild, while another session builds an index of its table;
|
|
the next run finds the new index above the mark. That check comes
|
|
first in the session, before the index is looked up: a rebuild that
|
|
ended before it has removed the index the session looks for, and an
|
|
orphaned one cannot start another after it.
|
|
|
|
One index must be rebuilt within one run of the Job, and a retry would
|
|
otherwise start a rebuild that cannot finish over and over. An
|
|
interrupted or failed REINDEX CONCURRENTLY leaves an invalid index with
|
|
a _ccnew suffix on the table, so two of those mean two runs already
|
|
failed there: the pass then leaves the table's stale indexes alone
|
|
until an operator has dropped the leftovers. A rebuild that succeeds
|
|
drops them itself. A failed or
|
|
skipped rebuild does not stop the others: the pass reports them, and
|
|
the Job exits non-zero at its end, with the recorded versions of that
|
|
database left as they are.
|
|
|
|
A collation that a range partition key depends on is never refreshed:
|
|
rebuilding an index does not move a row to the partition the new
|
|
ordering assigns it, and the version mismatch PostgreSQL keeps logging
|
|
is the only lasting sign of that. Its indexes are still rebuilt, and
|
|
again only when another collation of the database goes stale.
|
|
Before PostgreSQL 15 the server records no version for a database's
|
|
default collation. The version recorded for the libc collation of the
|
|
same locale stands in for it there, and is refreshed in its place; the
|
|
two are matched as glibc matches them, without regard to the case of
|
|
the codeset or a hyphen in it. A locale with no such collation cannot
|
|
be checked, which a run that saw the image change says in a warning.
|
|
|
|
PostgreSQL records no version for a libc locale named C.<codeset>
|
|
either, yet the one Debian patched into the glibc of bullseye and the
|
|
one glibc ships since 2.35 order some characters differently. Such a
|
|
collation, and a database whose default collation is such a locale,
|
|
therefore take the Debian release of the server's build as their
|
|
version. The release a database was last repaired for is another
|
|
setting of it, written once a run repairs the database without a
|
|
failure. A database without that setting gets the release of the
|
|
server the pass first finds it on: that is the previous image whenever
|
|
the pass sees the image change, since it looks before it waits for the
|
|
rollout, so a retry after the primary has restarted still rebuilds
|
|
those indexes. A database that already runs on a new glibc by then is
|
|
recognised by a libc collation, or a libc database default, whose
|
|
recorded version differs from the server's, and is taken as repaired
|
|
for no release. Anything else, a new cluster included, is taken as
|
|
repaired for the release it runs. That includes a database a pass
|
|
without this rule already repaired on the new glibc: it refreshed the
|
|
libc versions and left no sign of the move behind, so its indexes on a
|
|
C.<codeset> collation have to be rebuilt by hand with REINDEX.
|
|
With no version for PostgreSQL to complain about, a range partition key
|
|
of such a collation is reported only by the run that rebuilds its
|
|
indexes.
|
|
|
|
Every session of the pass pins search_path to pg_catalog: the Job
|
|
connects as the superuser, and a function or operator a tenant defined
|
|
in public would otherwise be picked wherever its argument types match
|
|
a call more exactly than the built-in does.
|
|
*/}}
|
|
|
|
echo "== refresh collation versions"
|
|
collation_sql() {
|
|
cat <<\EOT
|
|
SET client_min_messages = error;
|
|
SET search_path = pg_catalog, pg_temp;
|
|
SELECT current_setting('server_version_num')::int >= 150000 AS tracks_database \gset
|
|
\if :tracks_database
|
|
SELECT datcollversion IS NOT NULL AS db_versioned, coalesce(pg_database_collation_actual_version(oid), '') AS db_actual, datcollversion IS NOT NULL AND datcollversion IS DISTINCT FROM pg_database_collation_actual_version(oid) AS db_stale, false AS db_unmatched, datlocprovider = 'c' AND datcollate ~* '^C\.' AS db_c, datlocprovider = 'c' AND datcollversion IS NOT NULL AND datcollversion IS DISTINCT FROM pg_database_collation_actual_version(oid) AS db_libc_stale FROM pg_database WHERE datname = current_database() \gset
|
|
\else
|
|
SELECT d.datcollate NOT IN ('C', 'POSIX') AND d.datcollate !~* '^C\.' AS db_versioned,
|
|
coalesce(max(pg_collation_actual_version(c.oid)), '') AS db_actual,
|
|
coalesce(bool_or(c.collversion IS DISTINCT FROM pg_collation_actual_version(c.oid)), false) AS db_stale,
|
|
d.datcollate NOT IN ('C', 'POSIX') AND d.datcollate !~* '^C\.' AND count(c.oid) = 0 AS db_unmatched,
|
|
d.datcollate ~* '^C\.' AS db_c,
|
|
false AS db_libc_stale
|
|
FROM pg_database d
|
|
LEFT JOIN pg_collation c ON c.collprovider = 'c' AND lower(replace(c.collcollate, '-', '')) = lower(replace(d.datcollate, '-', '')) AND c.collversion IS NOT NULL AND c.collencoding IN (-1, d.encoding)
|
|
WHERE d.datname = current_database()
|
|
GROUP BY d.datcollate \gset
|
|
\endif
|
|
SELECT coalesce(substring(current_setting('server_version') from 'pgdg[0-9]+'), '') AS release, coalesce(current_setting('cozystack.collation_release', true), '') AS repaired \gset
|
|
SELECT :'repaired' = '' AND :'release' <> '' AS unrecorded \gset
|
|
\if :unrecorded
|
|
SELECT CASE WHEN :'db_libc_stale'::boolean OR EXISTS (SELECT FROM pg_collation c WHERE c.collprovider = 'c' AND c.collversion IS NOT NULL AND c.collversion IS DISTINCT FROM pg_collation_actual_version(c.oid)) THEN 'unknown' ELSE :'release' END AS repaired \gset
|
|
SELECT format('ALTER DATABASE %I SET cozystack.collation_release = %L', current_database(), :'repaired') \gexec
|
|
\endif
|
|
CREATE TEMP TABLE cozystack_collation AS
|
|
SELECT v.oid, v.actual, v.stale,
|
|
EXISTS (SELECT FROM pg_partitioned_table p WHERE p.partstrat = 'r' AND v.oid = ANY (p.partcollation::oid[])) AS held
|
|
FROM (
|
|
SELECT c.oid, coalesce(pg_collation_actual_version(c.oid), '') AS actual, c.collversion IS DISTINCT FROM pg_collation_actual_version(c.oid) AS stale
|
|
FROM pg_collation c
|
|
WHERE c.collversion IS NOT NULL
|
|
AND c.collencoding IN (-1, (SELECT encoding FROM pg_database WHERE datname = current_database()))
|
|
UNION ALL
|
|
SELECT 100, :'db_actual', :'db_stale'::boolean WHERE :'db_versioned'::boolean
|
|
) v
|
|
UNION ALL
|
|
SELECT c.oid, :'release', :'repaired' <> :'release', false
|
|
FROM pg_collation c
|
|
WHERE :'release' <> '' AND c.collprovider = 'c' AND c.collversion IS NULL AND c.collcollate ~* '^C\.'
|
|
AND c.collencoding IN (-1, (SELECT encoding FROM pg_database WHERE datname = current_database()))
|
|
UNION ALL
|
|
SELECT 100, :'release', :'repaired' <> :'release', false WHERE :'release' <> '' AND :'db_c'::boolean;
|
|
CREATE TEMP TABLE cozystack_collation_index AS
|
|
SELECT i.indexrelid AS index, bool_or(c.stale) AS stale
|
|
FROM (
|
|
SELECT x.indexrelid, k.used FROM pg_index x, unnest(x.indcollation::oid[]) AS k(used)
|
|
UNION
|
|
SELECT d.objid, d.refobjid FROM pg_depend d WHERE d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_collation'::regclass
|
|
UNION
|
|
SELECT d.objid, a.attcollation FROM pg_depend d JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid
|
|
WHERE d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_class'::regclass AND d.refobjsubid > 0 AND a.attcollation <> 0
|
|
) u
|
|
JOIN cozystack_collation c ON c.oid = u.used
|
|
JOIN pg_index i ON i.indexrelid = u.indexrelid
|
|
JOIN pg_class r ON r.oid = i.indexrelid
|
|
WHERE r.relkind = 'i' AND r.relpersistence <> 't' AND i.indisvalid
|
|
GROUP BY 1;
|
|
EOT
|
|
}
|
|
collation_run() {
|
|
{ collation_sql; cat; } | psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$1" -v moved="$IMAGE_MOVED"
|
|
}
|
|
IMAGE_MOVED=false
|
|
pg_release() {
|
|
sed -E 's/^([0-9.]+) \(Debian [^)]*(pgdg[0-9]+)\+[0-9]+\)$/\1 \2/'
|
|
}
|
|
server_release() {
|
|
psql -t -A -c 'SHOW server_version' 2>/dev/null | pg_release
|
|
}
|
|
JOB_RELEASE=$(psql -V | sed 's/^psql (PostgreSQL) //' | pg_release)
|
|
COLLATION_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate")
|
|
if [ "$(server_release)" != "$JOB_RELEASE" ]; then
|
|
IMAGE_MOVED=true
|
|
for db in $COLLATION_DBS; do
|
|
collation_run "$db" </dev/null >/dev/null
|
|
done
|
|
echo "waiting for the server to run PostgreSQL $JOB_RELEASE"
|
|
until [ "$(server_release)" = "$JOB_RELEASE" ]; do
|
|
if [ "$SECONDS" -ge $((JOB_DEADLINE - 120)) ]; then
|
|
echo "the server did not move to PostgreSQL $JOB_RELEASE in time (check the rollout of the cnpg.io/Cluster); no index is rebuilt yet - failing the collation repair Job, the next upgrade of the release starts it again" >&2
|
|
exit 1
|
|
fi
|
|
sleep 5
|
|
done
|
|
fi
|
|
COLLATION_FAILED=""
|
|
for db in $COLLATION_DBS; do
|
|
PLAN=$(collation_run "$db" <<\EOT
|
|
SELECT coalesce(md5(string_agg(oid || '=' || actual, ',' ORDER BY oid)), '') AS fingerprint FROM cozystack_collation WHERE stale \gset
|
|
SELECT coalesce(current_setting('cozystack.collation_repair', true), '') AS recorded \gset
|
|
SELECT :'fingerprint' <> '' AND split_part(:'recorded', ':', 1) = :'fingerprint' AS resumed \gset
|
|
\if :resumed
|
|
SELECT split_part(:'recorded', ':', 2) AS mark, split_part(:'recorded', ':', 3) AS inplace \gset
|
|
\else
|
|
SELECT max(oid)::bigint AS mark, '' AS inplace FROM pg_class \gset
|
|
SELECT format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), :'fingerprint' || ':' || :'mark') WHERE :'fingerprint' <> '' \gexec
|
|
\endif
|
|
SELECT index::bigint FROM cozystack_collation_index WHERE stale AND index::bigint <= :'mark'::bigint AND NOT EXISTS (SELECT FROM unnest(string_to_array(:'inplace', ',')) AS e JOIN pg_class r ON r.oid = index WHERE split_part(e, '/', 1) = index::text AND split_part(e, '/', 2) <> r.relfilenode::text) ORDER BY pg_relation_size(index);
|
|
EOT
|
|
)
|
|
DB_FAILED=""
|
|
for index in $PLAN; do
|
|
LEFT=$((JOB_DEADLINE - SECONDS - 60))
|
|
if [ "$LEFT" -lt 10 ]; then
|
|
echo "index $index in database $db was not rebuilt: the collation repair Job is out of time, the next upgrade of the release starts it again" >&2
|
|
DB_FAILED=yes
|
|
continue
|
|
fi
|
|
if ! psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -v index="$index" -v lock_wait="${LEFT}s" <<\EOT
|
|
SET client_min_messages = error;
|
|
SET search_path = pg_catalog, pg_temp;
|
|
SET lock_timeout = :'lock_wait';
|
|
SELECT EXISTS (SELECT FROM pg_index i JOIN pg_stat_progress_create_index p ON p.relid = i.indrelid JOIN pg_database d ON d.oid = p.datid WHERE i.indexrelid = :'index'::oid AND d.datname = current_database() AND p.pid <> pg_backend_pid()) AS building \gset
|
|
\if :building
|
|
SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was skipped: another session is building an index of its table, as a rebuild left by an earlier repair does; the next upgrade of the release starts the repair again', :'index'::oid::regclass, current_database()))) \gexec
|
|
\endif
|
|
SELECT count(*) = 1 AS present FROM pg_index WHERE indexrelid = :'index'::oid \gset
|
|
\if :present
|
|
SELECT coalesce(current_setting('cozystack.collation_repair', true), '') AS recorded \gset
|
|
SELECT i.indrelid AS relation, i.indisexclusion AS exclusion, i.indexrelid::regclass AS name, :'index' || '/' || r.relfilenode AS attempt,
|
|
(SELECT count(*) FROM pg_index l JOIN pg_class n ON n.oid = l.indexrelid WHERE l.indrelid = i.indrelid AND NOT l.indisvalid AND n.relname ~ '_ccnew[0-9]*$') >= 2 AS abandoned,
|
|
(SELECT count(*) FROM unnest(string_to_array(split_part(:'recorded', ':', 3), ',')) AS e WHERE e = :'index' || '/' || r.relfilenode) >= 2 AS abandoned_in_place
|
|
FROM pg_index i JOIN pg_class r ON r.oid = i.indexrelid WHERE i.indexrelid = :'index'::oid \gset
|
|
\if :abandoned
|
|
SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was left alone: two earlier runs failed to rebuild an index of its table, and each left an invalid _ccnew index there. Fix what made them fail, then drop those _ccnew indexes; the repair started by the next upgrade of the release rebuilds this one', :'name', current_database()))) \gexec
|
|
\endif
|
|
\if :exclusion
|
|
\if :abandoned_in_place
|
|
SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('index %s in database %s was left alone: two earlier runs began rebuilding it in place and did not finish. Rebuild it by hand with REINDEX INDEX, which blocks its table meanwhile; the repair started by the next upgrade of the release sees that it was rebuilt', :'name', current_database()))) \gexec
|
|
\endif
|
|
SELECT format('rebuilding index %s in database %s in place: its collation changed version', :'name', current_database());
|
|
SELECT format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), split_part(:'recorded', ':', 1) || ':' || split_part(:'recorded', ':', 2) || ':' || concat_ws(',', nullif(split_part(:'recorded', ':', 3), ''), :'attempt')) WHERE :'recorded' <> '' \gexec
|
|
SET statement_timeout = :'lock_wait';
|
|
SELECT format('REINDEX INDEX %s', :'name') \gexec
|
|
RESET statement_timeout;
|
|
\else
|
|
SELECT format('rebuilding index %s in database %s: its collation changed version', :'name', current_database());
|
|
SELECT format('REINDEX INDEX CONCURRENTLY %s', :'name') \gexec
|
|
\endif
|
|
SELECT format('DROP INDEX CONCURRENTLY IF EXISTS %s', l.indexrelid::regclass) FROM pg_index l JOIN pg_class n ON n.oid = l.indexrelid WHERE l.indrelid = :'relation'::oid AND NOT l.indisvalid AND n.relname ~ '_ccnew[0-9]*$' \gexec
|
|
\endif
|
|
EOT
|
|
then
|
|
[ "${PIPESTATUS[0]}" != 2 ] || COLLATION_LOST=yes
|
|
DB_FAILED=yes
|
|
fi
|
|
done
|
|
if [ -n "$DB_FAILED" ]; then
|
|
COLLATION_FAILED="$COLLATION_FAILED $db"
|
|
else
|
|
collation_run "$db" <<\EOT
|
|
SELECT format('WARNING: database %s uses the locale %s, for which this PostgreSQL major records no collation version and the catalog has no collation to stand in; the indexes on its default collation were not checked. If this upgrade moved the image to another Debian release, rebuild them with REINDEX DATABASE', datname, datcollate) FROM pg_database WHERE datname = current_database() AND :'db_unmatched'::boolean AND :'moved'::boolean;
|
|
SELECT format('WARNING: %s in database %s is range-partitioned on a key whose collation changed version; rows stored before the change may now belong to another partition, %s', p.partrelid::regclass, current_database(), CASE WHEN bool_or(c.held) THEN 'and the collation version is left as recorded until that is checked' ELSE 'and no later run says so again: PostgreSQL records no version for that collation' END) FROM pg_partitioned_table p JOIN cozystack_collation c ON c.stale AND c.oid = ANY (p.partcollation::oid[]) WHERE p.partstrat = 'r' GROUP BY p.partrelid;
|
|
DO $$
|
|
DECLARE
|
|
entry record;
|
|
BEGIN
|
|
FOR entry IN SELECT c.oid::regcollation AS name FROM cozystack_collation c WHERE c.stale AND NOT c.held AND c.oid <> 100
|
|
AND NOT (current_setting('server_version_num')::int < 150000
|
|
AND EXISTS (SELECT FROM cozystack_collation d WHERE d.oid = 100 AND d.held)
|
|
AND c.oid IN (SELECT n.oid FROM pg_collation n JOIN pg_database d ON d.datname = current_database() WHERE n.collprovider = 'c' AND lower(replace(n.collcollate, '-', '')) = lower(replace(d.datcollate, '-', '')))) LOOP
|
|
EXECUTE format('ALTER COLLATION %s REFRESH VERSION', entry.name);
|
|
END LOOP;
|
|
END$$;
|
|
SELECT format('ALTER DATABASE %I REFRESH COLLATION VERSION', current_database()) FROM cozystack_collation WHERE oid = 100 AND stale AND NOT held AND current_setting('server_version_num')::int >= 150000 \gexec
|
|
SELECT format('ALTER DATABASE %I SET cozystack.collation_release = %L', current_database(), :'release') WHERE :'release' NOT IN ('', :'repaired') \gexec
|
|
SELECT coalesce(md5(string_agg(oid || '=' || actual, ',' ORDER BY oid)), '') AS remaining FROM cozystack_collation WHERE stale AND held \gset
|
|
SELECT CASE WHEN :'remaining' = '' THEN '' ELSE :'remaining' || ':0' END AS settled \gset
|
|
SELECT CASE WHEN :'settled' = '' THEN format('ALTER DATABASE %I RESET cozystack.collation_repair', current_database()) ELSE format('ALTER DATABASE %I SET cozystack.collation_repair = %L', current_database(), :'settled') END WHERE coalesce(current_setting('cozystack.collation_repair', true), '') <> :'settled' \gexec
|
|
EOT
|
|
fi
|
|
done
|
|
if [ -n "$COLLATION_LOST" ]; then
|
|
echo "lost the connection to the server during index rebuilds in:$COLLATION_FAILED" >&2
|
|
exit 2
|
|
fi
|
|
if [ -n "$COLLATION_FAILED" ]; then
|
|
echo "index rebuilds failed in:$COLLATION_FAILED (the errors are above); the other indexes were rebuilt. A unique index cannot be rebuilt over rows that the previous ordering kept apart and the new one treats as equal, so remove such duplicates. The next upgrade of the release starts the repair again, except for an index an error above reports as left alone" >&2
|
|
fi
|
|
[ -z "$COLLATION_FAILED" ] || exit 1
|
|
{{- end }}
|
|
{{- if hasKey (.Values.users | default dict) "app" }}
|
|
---
|
|
{{- /* The bootstrap secret db.yaml gives CNPG for its "app" owner; see there. */}}
|
|
apiVersion: v1
|
|
kind: Secret
|
|
metadata:
|
|
name: {{ .Release.Name }}-app-owner
|
|
type: kubernetes.io/basic-auth
|
|
stringData:
|
|
username: app
|
|
password: {{ quote (index $passwords "app") }}
|
|
{{- end }}
|