{{- $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 }} {{/* Reject a username outside the Secret-key charset before it is interpolated into the credentials Secret key, the init-script shell (pw=$(cat "/credentials/")) and the role SQL. The charset mirrors k8s IsConfigMapKey (rejecting ".", any name starting with "..", and the metacharacters that would reach the shell). The length cap is 63, NOT the 253-char Secret-key limit: the username is also 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 ON_ERROR_STOP never sees it: 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. Cap at 63 so a too-long name is named here instead. A release that installed before the cap still carries such a user's key in the credentials Secret read above and its role under the truncated name; failing its upgrade would wedge the whole release, so on upgrade the cap applies only to a user that Secret does not already carry, i.e. a new one. The charset holds on both paths: a name outside it is not a valid Secret key, so it never installed. The charset is ASCII-only, so len (bytes) equals characters. */}} {{- range $user, $u := .Values.users }} {{- $tooLong := and (gt (len $user) 63) (or $.Release.IsInstall (not (hasKey $passwords $user))) }} {{- if or (not (regexMatch "^[-._a-zA-Z0-9]+$" $user)) (eq $user ".") (hasPrefix ".." $user) $tooLong }} {{- 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 it becomes a Kubernetes Secret key)" $user) }} {{- end }} {{- end }} {{/* A database name is interpolated into SQL identifiers (CREATE DATABASE "", the "_admin"/"_readonly" role names), into a single-quoted SQL string literal in the superuser DO block ('_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 "_admin" and "_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 \"_admin\" and \"_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 _admin and _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 }} {{/* Unlike MariaDB (secret.yaml carries the same lookup with a guard), postgres does NOT reject an upgrade whose credentials lookup came back empty. The credentials Secret here is gated on .Values.users, so a release installed with the default `users: {}` has no Secret at all; adding its FIRST user is an upgrade whose lookup is legitimately empty, and a guard on `IsUpgrade and not $existingSecret` cannot tell that apart from a deleted Secret (both are empty). Postgres also has no equivalent of MariaDB's bootstrap-only root: every role's password is applied by the post-upgrade init-job (ALTER ROLE), so a re-mint on a genuinely deleted Secret self-heals on the next reconcile rather than desyncing forever. So mint on an empty lookup, and let the common first-user-on-upgrade path through. */}} {{/* Passwords are always chart-generated and preserved across reconciles via the lookup above: a user keeps whatever password is already stored in the Secret, and only a user without one yet gets a freshly generated value. */}} {{- range $user, $u := .Values.users }} {{- if not (index $passwords $user) }} {{- $_ := set $passwords $user (randAlphaNum 16) }} {{- end }} {{- end }} {{- if .Values.users }} apiVersion: v1 kind: Secret metadata: name: {{ .Release.Name }}-credentials {{- if .Values.bootstrap.enabled }} annotations: # During a restore the roles recovered from the backup keep their original # password hashes, but this Secret holds freshly generated passwords and the # init-job that would apply them (ALTER ROLE) is skipped while bootstrap is # on. So the values below do NOT authenticate yet; they converge once the app # leaves bootstrap and the init-job runs. Flag it so a reader (dashboard, # tenant) does not treat the advertised password as usable mid-restore. postgres.cozystack.io/credentials-pending: "true" {{- end }} 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: 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 "== create users" {{- if .Values.users }} {{- /* A CREATEROLE holder can create a role under a name values will declare later, plant objects owned by it, role settings and default privileges, then drop the intermediate role it did this through, so the squatted role shows no member at all by the time it is declared. No catalog check can tell that apart from a role a platform administrator created, so once any user has held createRole the chart refuses to adopt a role it did not mark. Before that, adopting is safe, and it is what a declared users.app does on install with the role CNPG bootstraps. The flag is read at the start of this session and set only after it, so the run that first grants createRole still adopts, and every user is created and marked before any of them holds CREATEROLE. */}} {{- $grantsCreateRole := false }} psql -v ON_ERROR_STOP=1 --echo-all <<\EOT {{- range $user, $u := .Values.users }} {{- if and (default false $u.createRole) (lt $pgMajor 16) }} {{- fail (printf "SECURITY: users.%s.createRole requires PostgreSQL 16 or newer. On PostgreSQL 15 and older, a role holding CREATEROLE can grant itself any non-superuser role, including pg_execute_server_program, which escalates to command execution on the instance." $user) }} {{- end }} {{- if default false $u.createRole }} {{- $grantsCreateRole = true }} {{- end }} SELECT format('DO $$BEGIN RAISE EXCEPTION %L; END$$', 'role "{{ $user }}" already exists and this chart did not create it; a user of this instance has held createRole, so the role may be controlled by that user and users.{{ $user }} will not adopt it. A platform administrator must inspect the role and drop it as the superuser, or declare the user under another name') FROM pg_catalog.pg_roles r WHERE r.rolname = '{{ $user }}' AND current_setting('cozystack.createrole_granted', true) = 'on' AND NOT EXISTS (SELECT FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = r.oid)\gexec SELECT 'CREATE ROLE "{{ $user }}" LOGIN INHERIT;' WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{{ $user }}')\gexec GRANT "cozystack:managed" TO "{{ $user }}"{{ $markOptions }}; {{- end }} EOT {{- if $grantsCreateRole }} psql -v ON_ERROR_STOP=1 --echo-all -c "ALTER DATABASE postgres SET cozystack.createrole_granted = 'on';" {{- end }} {{- /* Each password is read from the mounted -credentials Secret at run time rather than rendered into this script: the init-script Secret is stored verbatim in the Helm release manifest and kept for MaxHistory revisions, so a literal password here would linger in cleartext history a tenant cannot scrub. psql's :'pw' quotes and escapes the value, so it applies safely whatever characters it holds. The password does reach psql through -v, i.e. its argv, readable via /proc//cmdline to a process sharing this container's PID namespace -- but this init container runs alone, and any code with that reach can already read the mounted /credentials/* files directly, so the argv path widens no exposure. This rationale is a template comment so it ships ONCE, not once per user, into the rendered init.sh. */}} {{- range $user, $u := .Values.users }} pw=$(cat "/credentials/{{ $user }}") psql -v ON_ERROR_STOP=1 -v pw="$pw" <<\EOT ALTER ROLE "{{ $user }}" WITH PASSWORD :'pw' LOGIN INHERIT {{ ternary "REPLICATION" "NOREPLICATION" (default false $u.replication) }} {{ ternary "CREATEROLE" "NOCREATEROLE" (default false $u.createRole) }} {{ ternary "BYPASSRLS" "NOBYPASSRLS" (default false $u.bypassRls) }}; {{- /* PostgreSQL 16 grants a CREATEROLE holder only ADMIN OPTION on the roles it creates, governed by createrole_self_grant, whose default is empty. ADMIN OPTION alone allows granting the role onward but not SET ROLE to it, and creating an object owned by another role requires SET. Without this the attribute looks functional — CREATE ROLE succeeds — yet the very next statement a tenant writes, CREATE SCHEMA ... AUTHORIZATION , fails with "must be able to SET ROLE". Set as a role-level default so it applies to every session, and reset when the attribute is withdrawn. */}} {{- if default false $u.createRole }} ALTER ROLE "{{ $user }}" SET createrole_self_grant = 'set, inherit'; {{- else }} ALTER ROLE "{{ $user }}" RESET createrole_self_grant; {{- end }} COMMENT ON ROLE "{{ $user }}" IS 'user managed by helm'; EOT {{- end }} {{- 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 _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 _admin and _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 same adoption check as for users. This session starts after the create users pass has recorded createRole, so the run that first grants it already refuses: its CREATEROLE holders exist from that pass on. */}} psql -v ON_ERROR_STOP=1 --echo-all <<\EOT {{- range $database, $d := .Values.databases }} SELECT format('DO $$BEGIN RAISE EXCEPTION %L; END$$', format('role "%s" already exists and this chart did not create it; a user of this instance has held createRole, so the role may be controlled by that user and databases.{{ $database }} will not adopt it. A platform administrator must inspect the role and drop it as the superuser, or declare the database under another name', r.rolname)) FROM pg_catalog.pg_roles r WHERE r.rolname IN ('{{ $database }}_admin', '{{ $database }}_readonly') AND current_setting('cozystack.createrole_granted', true) = 'on' AND NOT EXISTS (SELECT FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles g ON g.oid = m.roleid WHERE g.rolname = 'cozystack:managed' AND m.member = r.oid)\gexec 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 "== assign roles to users" psql -v ON_ERROR_STOP=1 --echo-all <<\EOT {{- range $database, $d := .Values.databases }} {{- $roles := $d.roles | default dict }} {{- range $user, $u := $.Values.users }} {{- if has $user $roles.admin }} GRANT "{{ $database }}_admin" TO "{{ $user }}"; {{- else }} REVOKE "{{ $database }}_admin" FROM "{{ $user }}"; {{- end }} {{- if has $user $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 "{{ include "postgres.extensionName" $extension }}"; {{- end }} EOT {{- end }} {{- end }} {{- /* 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 comes after the ones that manage roles and databases, so that a rebuild that fails, or does not finish before the Job deadline, costs none of them. Only the PostGIS update and the record of an adopted restore follow it: that record must not be written by a run that failed. Helm runs this hook as soon as the Cluster is patched, while CNPG is still rolling the instances, so the primary may 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. Waiting is only worth its time when an index depends on a versioned collation. 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 exits non-zero at the 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. 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 FROM pg_database WHERE datname = current_database() \gset \else SELECT d.datcollate NOT IN ('C', 'POSIX') 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 count(c.oid) = 0 AS db_unmatched 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 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; 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 DEPENDENT="" for db in $COLLATION_DBS; do DEPENDENT="$DEPENDENT$(collation_run "$db" <<\EOT SELECT index FROM cozystack_collation_index; EOT )" done if [ -n "$DEPENDENT" ]; then echo "indexes depend on a versioned collation; 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); indexes that depend on a versioned collation are not rebuilt yet - failing the init-job, the next run of it rebuilds them" >&2 exit 1 fi sleep 5 done fi 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 init-job is out of time, the next run of it carries on" >&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 run of the init-job does; the next run of the init-job carries on', :'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 next run of the init-job 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 next run of the init-job 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 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, and the collation version is left as recorded until that is checked', p.partrelid::regclass, current_database()) FROM pg_partitioned_table p WHERE p.partstrat = 'r' AND EXISTS (SELECT FROM cozystack_collation c WHERE c.stale AND c.oid = ANY (p.partcollation::oid[])); 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 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_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 run of the init-job tries again, except for an index an error above reports as left alone" >&2 exit 1 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 this 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: this Job is a hook, so a run that ended well would not come again before the next change of the release, while a failed one makes the release retry. 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, so that the release is retried and reported as failed instead of the error staying in the log of a Job that is deleted an hour later. 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="" for db in $ALL_DBS; do if ! 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')"); then echo "the PostGIS extensions in database $db were not checked (the error is above); the next run of the init-job carries on" >&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 init-job, the next run of it updates them" >&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 init-job is out of time, the next run of it carries on" >&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 run of the init-job updates them', 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 POSTGIS_FAILED="$POSTGIS_FAILED $db" fi done 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 run of the init-job tries again" >&2 exit 1 fi {{- 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 }} {{- 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 }}