Files
cozystack/packages/apps/postgres/templates/init-script.yaml
T
a67fa94fdb feat(postgres)!: issue user passwords through the credentials API
The chart generated every user's password at render time into
<release>-credentials, which tenants could read again at any time and
which Helm history kept for MaxHistory revisions, so a deployment whose
policy requires a credential shown once could not run PostgreSQL here.

The chart now renders a CredentialTemplate per user, and the users move
under CloudNativePG's managed roles, each pointing at its account
Secret, so the operator creates the role with the SCRAM verifier the
Secret holds, applies a changed Secret live, and reverts a password set
inside PostgreSQL. Every role is rendered as the init-script created it,
because the operator reverts an attribute that differs, revokes a parent
role missing from inRoles and clears a comment the spec leaves unset.
The init-script stops creating, passwording and altering accounts, where
it would be a second writer, and keeps the two things the operator has
no field for: the marker membership and the reset of the
createrole_self_grant an earlier chart set. Its marking pass waits a
bounded time for CloudNativePG to create the declared roles before it
marks them. users.app adopts the owner CloudNativePG bootstraps, whose
password the instance manager applies again from the bootstrap secret
on every pod start, so that secret is the app user's account Secret
and both writers apply the one stored verifier. A users.<name>.password
left in values draws an admission warning that points at a mint on the
user's Credential.

createRole is refused on every render path. A role a CREATEROLE user
creates makes that user a member of it, CloudNativePG revokes every
membership a managed role is not declared to hold, and the revoke fails
on the dependent self-grant, so the user would sit in cannotReconcile on
ordinary use; there is no per-role switch to leave memberships alone.
The account-name checks render with the managed roles too, so a restore
cannot bypass them: a user CloudNativePG or PostgreSQL reserves, a
database whose derived <name>_admin or <name>_readonly role starts with
pg_ or cnpg_ (which makes the CloudNativePG webhook reject the whole
Cluster), and a user whose account name is no valid object name are
refused. The chart's account naming is pinned to the API's on one table
of names.

A pre-upgrade hook refuses to let CloudNativePG adopt a role the chart
did not mark, because the operator adopts a managed role within seconds
of the spec reaching it, before any post-upgrade job could look. It
reads the live Cluster first and connects to the database only when the
upgrade adds a name CloudNativePG does not manage yet, so a database
that is down does not block the resize that might fix it. For each
absent declared database role it creates and marks the role as the
superuser before the Cluster applies, so no tenant can plant it in the
adoption window. The refusal and the create run in one psql session,
keyed on a snapshot of the role's existence taken at the top, so a role
planted in between collides with the CREATE and stops the hook; the
statements are built with format() and \gexec, since psql does not
substitute :'role' inside a DO $$ block. Verified on postgres:18: a
fresh role is created NOINHERIT, commented and marked, a role planted
after the snapshot fails the hook, and an existing unmarked role is
refused. The hook reads the Cluster at run time with a ServiceAccount
that may get only that Cluster, rather than through a template lookup,
which nothing re-renders when the object changes. The flag an earlier
chart set when a user held createRole is still read and never set, so
such a release keeps refusing to adopt a role it did not mark.

The EndpointAttachment e2e suite read testuser's password from that
Secret to probe the attached addresses. It now mints one per probe and
waits until the application's own Service accepts it, so the attached
address is still queried exactly once.

BREAKING CHANGE: PostgreSQL passwords are no longer readable from
<release>-credentials. A password is issued once, by a mint on the
account's Credential in core.cozystack.io, and replaced by the next
mint. users.<name>.createRole is refused; a release that sets it keeps
its previous chart version and passwords until it is false. Deleting a
Postgres application whose release is suspended is refused. The
conversion needs a platform variant with migrations enabled.

Co-authored-by: IvanHunters <xorokhotnikov@gmail.com>
Co-authored-by: Andrei Kvapil <kvapss@gmail.com>
Assisted-by: LLM
Signed-off-by: Timofei Larkin <lllamnyp@gmail.com>
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>
2026-11-30 18:21:27 +01:00

935 lines
63 KiB
YAML

{{/*
Reject a username outside the charset before it is interpolated into the role
SQL and the Cluster's managed roles. The charset mirrors k8s IsConfigMapKey
(rejecting ".", any name starting with "..", and the metacharacters that would
reach the shell). The length cap is 63: the username is a PostgreSQL role name,
and an identifier over NAMEDATALEN-1 (63 bytes) is silently TRUNCATED by CREATE
ROLE with a NOTICE, not an error, so the role exists under its 63-byte prefix,
two long names sharing that prefix become one role, and the stored name is not
the one the tenant declared. The account name the API derives from it is a DNS
label with the same cap, so the API refuses such a user before the chart sees
it. The charset is ASCII-only, so len (bytes) equals characters.
*/}}
{{- range $user, $u := .Values.users }}
{{- if or (not (regexMatch "^[-._a-zA-Z0-9]+$" $user)) (eq $user ".") (hasPrefix ".." $user) (gt (len $user) 63) }}
{{- fail (printf "invalid username %q: a username may contain only letters, digits and the characters -._ , must not be \".\" or start with \"..\", and must be at most 63 characters (it is a PostgreSQL role name, which CREATE ROLE silently truncates past 63 bytes, and the account name derived from it is a Kubernetes object name)" $user) }}
{{- end }}
{{- end }}
{{/*
A database name is interpolated into SQL identifiers (CREATE DATABASE "<db>", the
"<db>_admin"/"<db>_readonly" role names), into a single-quoted SQL string literal
in the superuser DO block ('<db>_admin' as a format() argument), and into a
space-separated shell list (DEFINED_ROLES). Reject any name outside the same safe
charset the username guard enforces so none of those contexts can be broken out
of: a "'" would escape the DO-block literal into arbitrary superuser SQL, a "\""
the CREATE DATABASE identifier, a space or ";" the shell list. The charset is the
injection guard, so it holds on install and upgrade alike: a database added on
upgrade is still a new name. It does not reject "." or a ".." prefix the way the
username guard does, because a database name is not a Secret key. The length cap
is 54 because the name also seeds the "<db>_admin" and "<db>_readonly" roles;
"_readonly" is 9 bytes, so past 54 bytes a role truncates past NAMEDATALEN (63).
The next init-job run then orphan-drops the truncated role, DROP OWNED only
reaches the database it runs in, and DROP ROLE fails on the grants inside the
long-named database, so such a release cannot survive a second run anyway. The
cap therefore holds on upgrade too: failing the render names
the problem instead of crash-looping the init-job. Extension names are
PostgreSQL identifiers too, capped at 63.
*/}}
{{- range $database, $d := .Values.databases }}
{{- if has $database (list "postgres" "template0" "template1") }}
{{- fail (printf "databases.%s is refused: %q is a PostgreSQL system database. Managing it would hand it, its public schema and the auto-grant event trigger to the \"%s_admin\" role (template1 then passes all of that on to every database created afterwards), and removing the entry later could not drop it. Remove the entry and declare an application database instead; the next upgrade releases a system database a previous version took over, without dropping it" $database $database $database) }}
{{- end }}
{{- if or (not (regexMatch "^[-._a-zA-Z0-9]+$" $database)) (gt (len $database) 54) }}
{{- fail (printf "invalid database name %q: a database name may contain only letters, digits and the characters -._ and must be at most 54 characters (it is interpolated into superuser SQL and the init-script shell, and it seeds the \"<db>_admin\" and \"<db>_readonly\" PostgreSQL roles, which CREATE ROLE silently truncates past 63 bytes; the next init-job run then cannot drop the truncated role and fails). Changing only its key in values makes the init-job drop the database; to keep the data, a platform administrator first renames it as the CNPG superuser (ALTER DATABASE, and ALTER ROLE for its <db>_admin and <db>_readonly roles), then the key is changed" $database) }}
{{- end }}
{{- range $extension := ($d.extensions | default (list)) }}
{{- $name := include "postgres.extensionName" $extension }}
{{- if or (not (regexMatch "^[-._a-zA-Z0-9]+$" $name)) (eq $name ".") (hasPrefix ".." $name) (gt (len $name) 63) }}
{{- fail (printf "invalid extension name %q for database %q: an extension name may contain only letters, digits and the characters -._ , must not be \".\" or start with \"..\", and must be at most 63 characters (it is a PostgreSQL identifier interpolated into CREATE EXTENSION in a superuser session; real names carry \"-\", e.g. uuid-ossp, so it is quoted at the call site). A clause after the name, such as CASCADE or SCHEMA, is not accepted: remove it from the value, which leaves an extension that is already installed as it is, and list the extensions it depends on before it, e.g. [cube, earthdistance]" $extension $database) }}
{{- end }}
{{- end }}
{{- end }}
{{/*
`postgres` is the CNPG-managed cluster superuser and must never be redefined as
an app role. Reject it here, before the bootstrap gate, not only in the
create-users block below: that block is skipped while bootstrap.enabled is true,
so a restore target carrying users.postgres would install, and the restore
controller's automatic bootstrap clear (disablePostgresAppBootstrap) would then
wedge the very next reconcile against a fail it never had to see at install while
the RestoreJob records Succeeded. Failing regardless of bootstrap keeps the
controller from converging a release into an unrenderable state.
*/}}
{{- if and .Values.users (hasKey .Values.users "postgres") }}
{{- fail "`users.postgres` is forbidden by policy. Use a different username." }}
{{- 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
{{- /*
Bounded readiness wait: this script runs as a post-install,post-upgrade Helm
hook Helm blocks on, so an unbounded `until pg_isready` would hang the hook
forever. The bound is wall-clock elapsed ($SECONDS), not an attempt count: an
attempt count ignores the time pg_isready itself takes, so a loop sized in
attempts can outlive the Job deadline, and the Job is then killed before this
diagnostic prints or the work after readiness gets any time. Each bound sits
below the Job's
activeDeadlineSeconds so the tail is reserved for create-users and the
per-schema grant pass. On UPGRADE the Cluster is already up, so give up after
250s of the 540s deadline and a purged target surfaces THIS diagnostic, leaving
290s for grants on a large database. On INSTALL the Cluster is still
provisioning (PVC, image pull, initdb), so allow 480s of the 570s deadline for
a cold-but-healthy first boot; the fresh databases need little of the 90s left.
Those tails are upper bounds: activeDeadlineSeconds counts from the Job's
start, while $SECONDS starts at 0 when this script does, so the pod's
scheduling, image pull and volume mounts come out of the tail first. A slow
start eats into the install tail, which is why a cold node can still hit the
Job deadline; the upgrade tail is wide enough not to notice. A
deleted-superuser-Secret mount never lets this loop run at all - the Job
deadline covers that.
*/}}
until pg_isready ; do
if [ "$SECONDS" -ge {{ if .Release.IsInstall }}480{{ else }}250{{ end }} ]; then
echo "postgres did not become ready in time; on a fresh install the Cluster may still be provisioning (check the cnpg.io/Cluster), on an upgrade the restore target may have been purged by a concurrent restore - failing the init-job rather than blocking the Helm hook" >&2
exit 1
fi
sleep 5
done
{{- /*
Role comments cannot tell which roles this chart manages: on PostgreSQL 16 a
CREATEROLE holder may COMMENT ON ROLE every role it created, and it may drop
the intermediate role that created one, leaving no pg_auth_members trace of
who did. Membership in "cozystack:managed" can only be granted by a holder of
ADMIN on it, which no role but the superuser ever gets, so the delete passes
and the adoption checks below trust that instead. The name sits outside the
username and database charsets, so values can never declare it. Its first run
marks every role the chart had commented before the marker existed; no role
could have held CREATEROLE through the chart by then. On PostgreSQL 16 and
later the membership carries neither INHERIT nor SET, so it is a record and
nothing else; the role holds no privileges on older majors either.
*/}}
{{- $pgMajor := atoi (trimPrefix "v" .Values.version) }}
{{- $markOptions := ternary " WITH INHERIT FALSE, SET FALSE" "" (ge $pgMajor 16) }}
echo "== mark managed roles"
psql -v ON_ERROR_STOP=1 --echo-all <<\EOT
DO $$
DECLARE
managed record;
BEGIN
IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'cozystack:managed') THEN
CREATE ROLE "cozystack:managed" NOLOGIN;
FOR managed IN SELECT r.rolname FROM pg_roles r JOIN pg_shdescription s ON s.objoid = r.oid AND s.classoid = 'pg_authid'::regclass WHERE s.description IN ('user managed by helm', 'role managed by helm') LOOP
EXECUTE format('GRANT %I TO %I{{ $markOptions }}', 'cozystack:managed', managed.rolname);
END LOOP;
END IF;
END$$;
EOT
echo "== mark users"
{{- if .Values.users }}
{{- /*
CNPG creates, passwords and alters each account from the Cluster's
managed roles; a second writer here would fight it. Two things it has no
field for stay: the marker membership, which CNPG grants with the default
options and this re-grant narrows to a record, leaving the options of an
existing membership alone; and the reset of createrole_self_grant, which
an earlier chart set for a createRole user. Both need the role, which
CNPG creates within seconds of the spec but possibly after this hook
starts, so the pass waits for it a bounded time; a role still missing
then keeps CNPG's defaults until the next run.
*/}}
{{- $declared := list }}
{{- range $user, $u := .Values.users }}{{ $declared = append $declared (printf "'%s'" $user) }}{{ end }}
roles_from=$SECONDS
until [ "$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT count(*) FROM pg_catalog.pg_roles WHERE rolname IN ({{ join ", " $declared }})")" = "{{ len $declared }}" ]; do
if [ "$SECONDS" -ge $((roles_from + 60)) ]; then
echo "not every declared role exists yet; marking those that do, the next run marks the rest" >&2
break
fi
sleep 2
done
psql -v ON_ERROR_STOP=1 --echo-all <<\EOT
{{- range $user, $u := .Values.users }}
SELECT 'GRANT "cozystack:managed" TO "{{ $user }}"{{ $markOptions }};'
WHERE EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{{ $user }}')\gexec
SELECT 'ALTER ROLE "{{ $user }}" RESET createrole_self_grant;'
WHERE EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{{ $user }}')\gexec
{{- end }}
EOT
{{- end }}
echo "== delete users"
{{- /*
Read the managed users from the catalog rather than by parsing `\du+`: its
column layout differs across PostgreSQL versions (16 dropped "Member of"), and
matching the wrong column finds nothing, so a user removed from values would
keep its LOGIN and password. Compare against the declared names truncated to
63 bytes, the form CREATE ROLE stores, or a long name kept on upgrade would
count as undeclared and be dropped on every run. REASSIGN OWNED and DROP OWNED
act only on the database they run in, so run them in every connectable
database: an object the user owns elsewhere would otherwise fail DROP USER
and wedge every later run. The objects go to "cozystack:orphaned", a role
that cannot log in and that the chart grants nothing: what a tenant role
created must not become superuser-owned. Every dropped role's objects share
that one owner, so its memberships are revoked and, after both drop passes,
functions it owns are switched to SECURITY INVOKER and, from PostgreSQL 15,
its views to security_invoker. A materialized view, a rule, and a view on
an older server have no such switch and keep reading as that owner. Grants
and memberships of the dropped role do not carry over, so a view or function
it owned can lose access it had through them. The ":" is outside the
username and database charsets, so no declared user or <db>_admin role can
take the name. In the user and role drop passes, names read from the
catalog reach SQL only as psql variables.
*/}}
MANAGED_USERS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT r.rolname FROM pg_roles r JOIN pg_shdescription s ON s.objoid = r.oid AND s.classoid = 'pg_authid'::regclass WHERE s.description = 'user managed by helm' AND r.oid IN (SELECT m.member FROM pg_auth_members m JOIN pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed')")
DEFINED_USERS="{{ $defined := list }}{{ range $user, $u := .Values.users }}{{ $defined = append $defined (trunc 63 $user) }}{{ end }}{{ join " " $defined }}"
DELETE_USERS=$(for user in $MANAGED_USERS; do case " $DEFINED_USERS " in *" $user "*) :;; *) echo $user;; esac; done)
ALL_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate")
psql -v ON_ERROR_STOP=1 --echo-all <<\EOT
SELECT 'CREATE ROLE "cozystack:orphaned" NOLOGIN NOINHERIT'
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'cozystack:orphaned')\gexec
SELECT format('REVOKE %I FROM %I', r.rolname, 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 'cozystack:orphaned' IN (r.rolname, m.rolname)\gexec
ALTER ROLE "cozystack:orphaned" NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;
EOT
echo "users to delete: $DELETE_USERS"
for user in $DELETE_USERS; do
for db in $ALL_DBS; do
psql -v ON_ERROR_STOP=1 --echo-queries --dbname "$db" -v user="$user" <<\EOT
REASSIGN OWNED BY :"user" TO "cozystack:orphaned";
DROP OWNED BY :"user";
EOT
done
psql -v ON_ERROR_STOP=1 --echo-queries -v user="$user" <<\EOT
DROP USER :"user";
EOT
done
echo "== release system databases"
{{- /*
Versions that did not refuse postgres, template0 and template1 in
databases took them over like any other entry. DROP DATABASE on them can
only fail (template databases cannot be dropped, and this session is
connected to postgres), which wedged every later upgrade, so they are
handed back instead: the auto-grant trigger goes, since it names a role
about to be dropped and would make every CREATE SCHEMA fail; what the
<db>_admin and <db>_readonly roles own there goes to cozystack:orphaned,
as in the orphaned-roles pass and for the same reason (a tenant's
SECURITY DEFINER function must not end up owned by the superuser), and is
made SECURITY INVOKER (only a role marked "cozystack:managed" is touched:
a role that merely carries one of those names was not created by this
chart and keeps what it owns); the database itself returns to the superuser,
public to pg_database_owner (to the superuser before PostgreSQL 15), each
only when one of those marked roles owns it and before the reassignment
would move it (or when cozystack:orphaned does, after a run that stopped
in between); an owner the chart did not mark keeps what it owns, and
the comment is cleared. The orphaned-roles pass below then drops the
roles; it does not visit template1, hence the per-database pass here.
template0 accepts no connection, and the Job that commented it never got
further, so only the comment is cleared. A database created from
template1 while it was taken over inherited its trigger, naming
template1_admin, and its public schema owned by that role; the trigger
goes, public returns to its default owner if a marked template1_admin
still owns it, and a declared database gets
its trigger back from the grant pass further down.
*/}}
SYSTEM_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' AND d.datname IN ('postgres', 'template0', 'template1')")
echo "system databases to release: $SYSTEM_DBS"
for db in $SYSTEM_DBS; do
if [ "$db" != template0 ]; then
psql -v ON_ERROR_STOP=1 --echo-all --dbname "$db" -v db="$db" <<\EOT
DROP EVENT TRIGGER IF EXISTS trigger_auto_grant;
DROP FUNCTION IF EXISTS auto_grant_schema_privileges();
SELECT format('ALTER SCHEMA public OWNER TO %s', CASE WHEN current_setting('server_version_num')::int >= 150000 THEN 'pg_database_owner' ELSE 'CURRENT_USER' END) FROM pg_namespace n JOIN pg_roles o ON o.oid = n.nspowner WHERE n.nspname = 'public' AND (o.rolname = 'cozystack:orphaned' OR o.rolname IN (:'db' || '_admin', :'db' || '_readonly') AND EXISTS (SELECT FROM pg_auth_members m JOIN pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = o.oid))\gexec
SELECT format('ALTER DATABASE %I OWNER TO CURRENT_USER', d.datname) FROM pg_database d JOIN pg_roles o ON o.oid = d.datdba WHERE d.datname = :'db' AND (o.rolname = 'cozystack:orphaned' OR o.rolname IN (:'db' || '_admin', :'db' || '_readonly') AND EXISTS (SELECT FROM pg_auth_members m JOIN pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = o.oid))\gexec
SELECT format('REASSIGN OWNED BY %I TO "cozystack:orphaned"', r), format('DROP OWNED BY %I', r) FROM unnest(ARRAY[:'db' || '_admin', :'db' || '_readonly']) AS r WHERE EXISTS (SELECT FROM pg_auth_members m JOIN pg_roles g ON g.oid = m.roleid JOIN pg_roles u ON u.oid = m.member WHERE g.rolname = 'cozystack:managed' AND u.rolname = r)\gexec
SELECT format('ALTER %s %s SECURITY INVOKER', CASE p.prokind WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END, p.oid::regprocedure) FROM pg_proc p WHERE p.proowner = '"cozystack:orphaned"'::regrole AND p.prosecdef\gexec
SELECT format('ALTER VIEW %s SET (security_invoker = true)', c.oid::regclass) FROM pg_class c WHERE c.relowner = '"cozystack:orphaned"'::regrole AND c.relkind = 'v' AND current_setting('server_version_num')::int >= 150000 AND NOT coalesce('security_invoker=true' = ANY (c.reloptions), false)\gexec
EOT
fi
if [ "$db" = template1 ]; then
{{- /*
An assignment of its own, so that set -e stops the pass when the lookup
fails: inside the for list its status is discarded, the comment below is
cleared without a clone visited, and no later run selects template1 again.
*/}}
CLONE_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate")
for other in $CLONE_DBS; do
psql -v ON_ERROR_STOP=1 --echo-queries --dbname "$other" <<\EOT
SELECT 'DROP EVENT TRIGGER IF EXISTS trigger_auto_grant', 'DROP FUNCTION auto_grant_schema_privileges()' WHERE position('''template1_admin''' IN coalesce((SELECT prosrc FROM pg_proc WHERE oid = to_regprocedure('auto_grant_schema_privileges()')), '')) > 0\gexec
SELECT format('ALTER SCHEMA public OWNER TO %s', CASE WHEN current_setting('server_version_num')::int >= 150000 THEN 'pg_database_owner' ELSE 'CURRENT_USER' END) FROM pg_namespace n JOIN pg_roles o ON o.oid = n.nspowner WHERE n.nspname = 'public' AND o.rolname = 'template1_admin' AND EXISTS (SELECT FROM pg_auth_members m JOIN pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = o.oid)\gexec
EOT
done
fi
psql -v ON_ERROR_STOP=1 --echo-all -v db="$db" <<\EOT
COMMENT ON DATABASE :"db" IS NULL;
EOT
done
echo "== delete databases"
{{- /*
A restore replaces spec.databases with the Backup's snapshot, but recovery
replays WAL past it, so a database created after the Backup comes back still
commented 'database managed by helm' and would be dropped here. The first run
after a restore is told apart by bootstrap.newServerName, which the restore
driver sets to a value unique to each RestoreJob; the last pass records it as
a setting of the postgres database, which the recovery replaces with the
source's along with the rest of the catalog. Until then an undeclared managed database is released
instead: its comment and its roles' comments are cleared, which keeps the
orphaned-roles pass below off roles that still hold grants inside it. The
value is free text in values, so it arrives base64-encoded and reaches SQL
only as a psql variable.
*/}}
RESTORE_MARK={{ with .Values.bootstrap.newServerName }}$(echo {{ b64enc . }} | base64 -d){{ end }}
ADOPTED_MARK=$(psql -v ON_ERROR_STOP=1 -t -A --dbname postgres -c "SELECT current_setting('cozystack.adopted_restore', true)")
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 " postgres template0 template1 $DEFINED_DBS " in *" $db "*) :;; *) echo $db;; esac; done)
if [ -n "$RESTORE_MARK" ] && [ "$ADOPTED_MARK" != "$RESTORE_MARK" ]; then
echo "databases the restore brought back that values do not declare, released from management: $DELETE_DBS"
for db in $DELETE_DBS; do
psql -v ON_ERROR_STOP=1 --echo-all -v db="$db" <<\EOT
COMMENT ON DATABASE :"db" IS NULL;
SELECT format('COMMENT ON ROLE %I IS NULL', r) FROM unnest(ARRAY[:'db' || '_admin', :'db' || '_readonly']) AS r WHERE EXISTS (SELECT FROM pg_roles WHERE rolname = r)\gexec
EOT
done
else
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
fi
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' AND r.oid IN (SELECT m.member FROM pg_auth_members m JOIN pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed')")
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)
{{- /*
Same per-database REASSIGN/DROP OWNED as the user pass, for the same reason.
The database list is read again because the pass above may have dropped
some of the databases the first read returned.
*/}}
ALL_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate")
echo "roles to delete: $DELETE_ROLES"
for role in $DELETE_ROLES; do
psql -v ON_ERROR_STOP=1 --echo-queries -v role="$role" <<\EOT
SELECT format('REVOKE %I FROM %I', r.rolname, 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'\gexec
EOT
for db in $ALL_DBS; do
psql -v ON_ERROR_STOP=1 --echo-queries --dbname "$db" -v role="$role" <<\EOT
REASSIGN OWNED BY :"role" TO "cozystack:orphaned";
DROP OWNED BY :"role";
EOT
done
psql -v ON_ERROR_STOP=1 --echo-queries -v role="$role" <<\EOT
DROP ROLE IF EXISTS :"role";
EOT
done
for db in $ALL_DBS; do
psql -v ON_ERROR_STOP=1 --echo-queries --dbname "$db" <<\EOT
SELECT format('ALTER %s %s SECURITY INVOKER', CASE p.prokind WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END, p.oid::regprocedure) FROM pg_proc p WHERE p.proowner = '"cozystack:orphaned"'::regrole AND p.prosecdef\gexec
SELECT format('ALTER VIEW %s SET (security_invoker = true)', c.oid::regclass) FROM pg_class c WHERE c.relowner = '"cozystack:orphaned"'::regrole AND c.relkind = 'v' AND current_setting('server_version_num')::int >= 150000 AND NOT coalesce('security_invoker=true' = ANY (c.reloptions), false)\gexec
EOT
done
echo "== create databases and roles"
{{- if .Values.databases }}
{{- /*
The database roles are declared in the Cluster's managed roles as well,
but ALTER DATABASE ... OWNER below needs them in this run, so they are
still created here, idempotently, and CNPG then finds them as its spec
says. The refusal to adopt an unmarked role runs in the pre-upgrade hook.
*/}}
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';
GRANT "cozystack:managed" TO "{{ $database }}_admin"{{ $markOptions }};
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';
GRANT "cozystack:managed" TO "{{ $database }}_readonly"{{ $markOptions }};
{{- 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 "== 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 "{{ include "postgres.extensionName" $extension }}";
{{- end }}
EOT
{{- end }}
{{- end }}
{{- if .Values.bootstrap.newServerName }}
echo "== record the adopted restore"
psql -v ON_ERROR_STOP=1 --echo-all -v mark="$RESTORE_MARK" <<\EOT
ALTER DATABASE postgres SET cozystack.adopted_restore = :'mark';
EOT
{{- 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 PostGIS
update, which waits for the same rollout, follows this pass in the
same Job.
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, nor the PostGIS update: 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
{{- if eq .Values.flavor "postgis" }}
{{- /*
A new PostGIS library leaves the SQL objects of every database on the
release they were installed with until ALTER EXTENSION ... UPDATE runs
there, and postgis_full_version() reports them as needing an upgrade
meanwhile. The extensions were created in the init-job's superuser session,
so only the superuser owns them and can update them; a tenant gets
"must be owner of extension". This pass updates them in every database
where they are installed, including ones values no longer list.
The target is the version the server offers, never one rendered here,
so a database only moves to what the running library implements, and
a database already on it is left alone. While CNPG is still rolling the
instances the server offers the previous release and there is nothing
to update yet, so the pass first waits for the server to offer the
PostGIS release the Job's own image ships, until 120 seconds before
the Job's deadline. A rollout that takes longer fails the Job, and the
next upgrade of the release starts it again.
postgis_extensions_upgrade() is not used: it leaves out
address_standardizer, and it updates every installed extension to ANY
and back on each call, even when nothing changed. Each extension is
updated on its own instead, postgis before the ones that require it,
in sessions that pin search_path as the collation pass does. A version
the image ships no update path from is reported and left as it is: the
address_standardizer of PostGIS 3.7 has none from earlier releases.
ALTER EXTENSION is transactional, so an update that fails leaves its
extension as it was. A tenant transaction can hold a lock an update
needs, and one update can wait for several of them in turn, so each
update, its lock waits included, runs no longer than what is left of
the Job, with the same minute in reserve as the collation pass, and a
database reached with no time left counts as failed. The pass carries
on with the other databases and then fails the Job, whose log names
them; the next upgrade of the release starts it again.
The update scripts run as the superuser and write to tables a tenant's
admin role may attach triggers to (spatial_ref_sys among them), and a
trigger runs with the privileges of the session that fires it. The
update session therefore runs with session_replication_role = replica,
under which triggers enabled the default way do not fire; only a
table's owner, the superuser, can enable one ALWAYS or REPLICA, and a
database where such a trigger sits on a table of these extensions is
not updated.
*/}}
echo "== update postgis extensions"
POSTGIS_SHIPPED=$(sed -n "s/^default_version *= *'\([^']*\)'.*/\1/p" "$(pg_config --sharedir)/extension/postgis.control")
postgis_offered() {
timeout 10 psql -t -A -c "SELECT default_version FROM pg_catalog.pg_available_extensions WHERE name = 'postgis'" 2>/dev/null
}
ALL_DBS=$(psql -v ON_ERROR_STOP=1 -t -A -c "SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate")
POSTGIS_DBS=""
POSTGIS_FAILED=""
POSTGIS_LOST=""
for db in $ALL_DBS; do
status=0
installed=$(psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -c "SET search_path = pg_catalog, pg_temp" -c "SELECT count(*) FROM pg_extension WHERE extname IN ('postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us')") || status=$?
if [ "$status" != 0 ]; then
[ "$status" != 2 ] || POSTGIS_LOST=yes
echo "the PostGIS extensions in database $db were not checked (the error is above); the next upgrade of the release starts the repair again" >&2
POSTGIS_FAILED="$POSTGIS_FAILED $db"
continue
fi
if [ "$installed" != 0 ]; then
POSTGIS_DBS="$POSTGIS_DBS $db"
fi
done
if [ -n "$POSTGIS_DBS" ] && [ -n "$POSTGIS_SHIPPED" ] && [ "$(postgis_offered)" != "$POSTGIS_SHIPPED" ]; then
echo "waiting for the server to offer PostGIS $POSTGIS_SHIPPED"
until [ "$(postgis_offered)" = "$POSTGIS_SHIPPED" ]; do
if [ "$SECONDS" -ge $((JOB_DEADLINE - 120)) ]; then
echo "the server did not move to PostGIS $POSTGIS_SHIPPED in time (check the rollout of the cnpg.io/Cluster); the PostGIS extensions are not updated yet - failing the collation repair Job, the next upgrade of the release starts it again" >&2
exit 1
fi
sleep 5
done
fi
for db in $POSTGIS_DBS; do
LEFT=$((JOB_DEADLINE - SECONDS - 60))
if [ "$LEFT" -lt 10 ]; then
echo "the PostGIS extensions in database $db were not updated: the collation repair Job is out of time, the next upgrade of the release starts it again" >&2
POSTGIS_FAILED="$POSTGIS_FAILED $db"
continue
fi
if ! psql -v ON_ERROR_STOP=1 -q -t -A --dbname "$db" -v lock_wait="${LEFT}s" <<\EOT
SET client_min_messages = warning;
SET search_path = pg_catalog, pg_temp;
SET lock_timeout = :'lock_wait';
SET session_replication_role = replica;
SELECT EXISTS (SELECT FROM pg_trigger t JOIN pg_depend d ON d.classid = 'pg_class'::regclass AND d.objid = t.tgrelid AND d.deptype = 'e' JOIN pg_extension x ON x.oid = d.refobjid WHERE NOT t.tgisinternal AND t.tgenabled IN ('A', 'R') AND x.extname IN ('postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us')) AS armed \gset
\if :armed
SELECT format('DO %L', format('BEGIN RAISE EXCEPTION %L, %L; END', '%', format('the PostGIS extensions in database %s were not updated: a table of theirs carries a trigger enabled ALWAYS or REPLICA, which would run inside the superuser update; drop that trigger, and the next upgrade of the release starts the repair again', current_database()))) \gexec
\endif
SELECT clock_timestamp() + :'lock_wait'::interval AS deadline_at \gset
CREATE TEMP TABLE cozystack_postgis AS
SELECT e.extname, e.extversion, a.default_version, f.position,
EXISTS (SELECT FROM pg_extension_update_paths(e.extname) p WHERE p.source = e.extversion AND p.target = a.default_version AND p.path IS NOT NULL) AS reachable
FROM unnest(ARRAY['postgis', 'postgis_raster', 'postgis_topology', 'postgis_sfcgal', 'postgis_tiger_geocoder', 'address_standardizer', 'address_standardizer_data_us']::name[]) WITH ORDINALITY AS f(name, position)
JOIN pg_extension e ON e.extname = f.name
JOIN pg_available_extensions a ON a.name = e.extname
WHERE e.extversion <> a.default_version;
SELECT format('WARNING: extension %s in database %s stays at version %s: the image ships no update path from it to %s', extname, current_database(), extversion, default_version) FROM cozystack_postgis WHERE NOT reachable ORDER BY position;
SELECT format('updating extension %s in database %s from %s to %s', extname, current_database(), extversion, default_version) FROM cozystack_postgis WHERE reachable ORDER BY position;
SELECT format('DO %L', format('BEGIN PERFORM set_config(%L, greatest(1, floor(extract(epoch FROM %L::timestamptz - clock_timestamp()) * 1000))::bigint::text, false); PERFORM set_config(%L, current_setting(%L), false); END', 'statement_timeout', :'deadline_at', 'lock_timeout', 'statement_timeout')),
format('ALTER EXTENSION %I UPDATE TO %L', extname, default_version)
FROM cozystack_postgis WHERE reachable ORDER BY position \gexec
EOT
then
[ "${PIPESTATUS[0]}" != 2 ] || POSTGIS_LOST=yes
POSTGIS_FAILED="$POSTGIS_FAILED $db"
fi
done
if [ -n "$POSTGIS_LOST" ]; then
echo "lost the connection to the server during the PostGIS update in:$POSTGIS_FAILED" >&2
exit 2
fi
if [ -n "$POSTGIS_FAILED" ]; then
echo "PostGIS extension updates failed in:$POSTGIS_FAILED (the errors are above); the extensions there stay at their previous version. The next upgrade of the release starts the repair again" >&2
exit 1
fi
{{- end }}
[ -z "$COLLATION_FAILED" ] || exit 1
{{- end }}