From 2a53334b3ffe7de5a22d57e951a9eb7487d47f8f Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sun, 29 Nov 2026 12:56:13 +0000 Subject: [PATCH] fix: copy data tables whose database uses extensions (#12716) * feat: copy data tables that use extensions such as timescaledb and postgis Co-Authored-By: Claude Opus 5.5 * fix: create copied extensions as the cluster admin only for same-cluster copies Co-Authored-By: Claude Opus 5.5 * fix: load hypertable rows in the dump's snapshot before post-data Co-Authored-By: Claude Opus 5.5 * fix: read hypertables in the dump's snapshot and copy their rows as text Co-Authored-By: Claude Opus 5.5 * fix: lock hypertables until their rows are copied Co-Authored-By: Claude Opus 5.5 * fix: lock every chunk the dump's snapshot sees Co-Authored-By: Claude Opus 5.5 * refactor: create managed copies' extensions with the database, restore from an archive Co-Authored-By: Claude Opus 5.5 * fix: hand over only the extension schemas provisioning creates, replay roles without chunks Co-Authored-By: Claude Opus 5.5 * fix: carry extension schemas' comments through the copy's setup Co-Authored-By: Claude Opus 5.5 * style: wrap a comment Co-Authored-By: Claude Opus 5.5 * fix: have the server quote copied schema comments, keep a copy whose inherited schema it cannot comment Co-Authored-By: Claude Opus 5.5 * refactor: refuse TimescaleDB hypertables in data table copies Co-Authored-By: Claude Opus 5.5 * fix: check a copy's source for hypertables again once it is dumped Co-Authored-By: Claude Opus 5.5 * chore: update ee-repo-ref to ae92a820922f76ad60427dec257cc57fc8ce1a36 This commit updates the EE repository reference after PR #1023 was merged in windmill-ee-private. Previous ee-repo-ref: 5a35e6f2a01650b4cc846eba8997837bb307bf71 New ee-repo-ref: ae92a820922f76ad60427dec257cc57fc8ce1a36 Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: windmill-internal-app[bot] --- backend/ee-repo-ref.txt | 2 +- backend/windmill-api-settings/src/lib.rs | 7 +- .../src/datatable_clone.rs | 20 +- .../src/datatable_extensions.rs | 456 ++++++++++++++++++ .../src/datatable_migrations.rs | 1 + backend/windmill-api-workspaces/src/lib.rs | 1 + .../windmill-api-workspaces/src/workspaces.rs | 113 ++++- .../src/external_instance_pg.rs | 4 +- .../src/external_instance_pg_oss.rs | 1 + backend/windmill-common/src/lib.rs | 170 ++++++- 10 files changed, 755 insertions(+), 20 deletions(-) create mode 100644 backend/windmill-api-workspaces/src/datatable_extensions.rs diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 6d0e7b18fc..23275013ec 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -23291f201b34b6f3d8e08b11783413a22a43a15f +ae92a820922f76ad60427dec257cc57fc8ce1a36 diff --git a/backend/windmill-api-settings/src/lib.rs b/backend/windmill-api-settings/src/lib.rs index d6e6672080..3634b38d0f 100644 --- a/backend/windmill-api-settings/src/lib.rs +++ b/backend/windmill-api-settings/src/lib.rs @@ -2101,7 +2101,12 @@ async fn create_external_instance_pg_database( let tag = body.tag.as_deref().unwrap_or("datatable"); let mut tx = db.begin().await?; windmill_common::external_instance_pg::create_external_instance_database_unchecked( - &db, &mut tx, &dbname, tag, None, + &db, + &mut tx, + &dbname, + tag, + None, + &[], ) .await?; tx.commit().await?; diff --git a/backend/windmill-api-workspaces/src/datatable_clone.rs b/backend/windmill-api-workspaces/src/datatable_clone.rs index 398766b19e..28e352eadb 100644 --- a/backend/windmill-api-workspaces/src/datatable_clone.rs +++ b/backend/windmill-api-workspaces/src/datatable_clone.rs @@ -28,13 +28,13 @@ use windmill_common::workspaces::{ use windmill_common::{PgDatabase, DB}; use crate::datatable_acl::connect_with_notices; +use crate::datatable_extensions::{read_extension_plan, ExtensionPlan}; use crate::datatable_migrations::{ lock_migration_runs_on, read_applied_migrations, write_applied_migrations, AppliedMigrations, }; use crate::datatable_permissions::ensure_reaches_governing_datatable; use crate::workspaces::{ - copy_database_settings, create_database_on_server, ensure_datatable_is_clonable, - pg_dump_database, pg_import_dump, DumpFile, PgDumpOptions, + copy_database_settings, create_database_on_server, ensure_datatable_is_clonable, DumpFile, }; /// A database this request created and filled for the data tables of the fork on one source @@ -468,16 +468,16 @@ async fn make_copy( // Ownership never carries over: the restore runs as the target's connection user. Grants do, // except on a cluster Windmill manages, which plants its own and where the replay below is what // reproduces the roles'. - let dump = pg_dump_database( - &server, - PgDumpOptions { schema_only, no_owner: true, no_acl: managed, ..Default::default() }, - ) - .await?; + let extensions = read_extension_plan(db, &server, schema_only).await?; + let dump = extensions.dump(db, &server, schema_only, managed).await?; let applied = match migrations_lock { Some(client) => Some(read_applied_migrations(&client).await?), None => None, }; + // On a cluster Windmill manages, its administrator creates the copy's extensions with the + // database, before the copy's role may write to it. On a server of the workspace's own, the + // role creates them itself when the dump is restored. match source_database.resource_type { DataTableCatalogResourceType::Instance => { windmill_common::create_custom_instance_database( @@ -485,6 +485,7 @@ async fn make_copy( request.dbname, "datatable", Some(parent_w_id), + &extensions.database_extensions(), ) .await? } @@ -496,6 +497,7 @@ async fn make_copy( request.dbname, "datatable", Some(parent_w_id), + &extensions.database_extensions(), ) .await?; tx.commit().await?; @@ -515,6 +517,7 @@ async fn make_copy( &server, &target, &dump, + &extensions, applied.as_ref(), ) .await; @@ -556,9 +559,10 @@ async fn fill( source: &PgDatabase, target: &PgDatabase, dump: &DumpFile, + extensions: &ExtensionPlan, applied: Option<&AppliedMigrations>, ) -> Result { - pg_import_dump(target, dump).await?; + extensions.restore(db, dump, target).await?; if let Some(applied) = applied { write_applied_migrations(db, target, applied).await?; } diff --git a/backend/windmill-api-workspaces/src/datatable_extensions.rs b/backend/windmill-api-workspaces/src/datatable_extensions.rs new file mode 100644 index 0000000000..11b606349e --- /dev/null +++ b/backend/windmill-api-workspaces/src/datatable_extensions.rs @@ -0,0 +1,456 @@ +/* + * Author: Ruben Fiszel + * Copyright: Windmill Labs, Inc 2022 + * This file and its contents are licensed under the AGPLv3 License. + * Please see the included NOTICE for copyright information and + * LICENSE-AGPL for a copy of the license. + */ + +//! Copying a database that uses extensions. +//! +//! A copy is replayed as the target's own connection role, which can neither create an extension +//! only a superuser may create nor comment on one it does not own, and `pg_dump` writes both for +//! every extension. So the dump leaves extensions out, and the copy is given them first: by its +//! cluster's administrator when Windmill manages it, as it creates the database +//! ([`ExtensionPlan::database_extensions`]), by the target's role otherwise. +//! +//! The dump is an archive, and what of it is replayed is chosen entry by entry, by the source +//! object each entry is for ([`ExtensionPlan::skipped_entries`]). + +use std::collections::BTreeSet; +use std::io::Write; + +use windmill_common::error::{pg_error_message, Error, Result}; +use windmill_common::{DatabaseExtension, PgDatabase, DB}; + +use crate::workspaces::{ + pg_dump_database, pg_import_dump, pg_restore_list, pg_restore_script, DumpFile, PgDumpOptions, +}; + +const TIMESCALEDB: &str = "timescaledb"; + +/// What a copy of one database needs done about the extensions it uses. +#[derive(Default)] +pub(crate) struct ExtensionPlan { + /// In creation order, so an extension comes after those it requires. + extensions: Vec, + /// Schemas holding an extension that the dump creates too. The copy needs them before its + /// extensions, so they are made first, with their comments, and the dump's `CREATE SCHEMA` and + /// `COMMENT ON SCHEMA` are not replayed: the copy's role may not own one it did not make. + extension_schemas: Vec, + /// The source objects whose archive entries are not replayed, as `(catalog oid, object oid)`. + skipped_entries: BTreeSet<(u32, u32)>, +} + +fn quote_ident(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) +} + +fn source_err(dbname: &str) -> impl FnOnce(tokio_postgres::Error) -> Error + '_ { + move |e| { + Error::internal_err(format!( + "Failed to read the extensions of database '{dbname}': {}", + pg_error_message(&e) + )) + } +} + +/// Read what copying `source` takes: its extensions. Refuses, before anything is created, what a +/// copy cannot carry. +pub(crate) async fn read_extension_plan( + db: &DB, + source: &PgDatabase, + schema_only: bool, +) -> Result { + let (client, connection) = source.connect(Some(db)).await?; + let join_handle = tokio::spawn(async move { connection.await }); + let plan = read_plan(&client, &source.dbname, schema_only).await; + drop(client); + windmill_common::shutdown_pg_connection(join_handle).await?; + plan +} + +async fn read_plan( + client: &tokio_postgres::Client, + dbname: &str, + schema_only: bool, +) -> Result { + // An extension's schema is dumped unless it is Postgres's own, `public`, which every database + // already has, or one an extension created as part of itself. + let rows = client + .query( + "SELECT e.extname::text, n.nspname::text, + n.nspname NOT IN ('public', 'pg_catalog') AND NOT EXISTS ( + SELECT 1 FROM pg_depend d + WHERE d.classid = 'pg_namespace'::regclass AND d.objid = n.oid + AND d.deptype = 'e'), + 'pg_namespace'::regclass::oid, n.oid, obj_description(n.oid, 'pg_namespace') + FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace + WHERE e.extname <> 'plpgsql' + ORDER BY e.oid", + &[], + ) + .await + .map_err(source_err(dbname))?; + let mut plan = ExtensionPlan::default(); + let mut extension_schemas = BTreeSet::new(); + for row in rows { + let dumped_schema = row.get::<_, bool>(2); + if dumped_schema { + extension_schemas.insert(row.get::<_, String>(1)); + plan.skipped_entries.insert((row.get(3), row.get(4))); + } + plan.extensions.push(DatabaseExtension { + name: row.get(0), + schema: row.get(1), + schema_comment: if dumped_schema { row.get(5) } else { None }, + }); + } + plan.extension_schemas = extension_schemas.into_iter().collect(); + + if plan.extensions.iter().any(|e| e.name == TIMESCALEDB) { + refuse_hypertables(client, dbname).await?; + } + if !schema_only { + refuse_extension_rows(client, dbname).await?; + } + Ok(plan) +} + +/// Refuse a copy with data of a database whose extensions' configuration tables hold rows of its +/// users, such as PostGIS's custom spatial references: leaving the extensions out of the dump +/// leaves those rows out too, and the copy's role could not write them anyway. TimescaleDB's always +/// hold bookkeeping its copy in the new database writes again, and its hypertables are refused on +/// their own. +async fn refuse_extension_rows(client: &tokio_postgres::Client, dbname: &str) -> Result<()> { + // `extcondition` is the filter pg_dump applies to pick the rows that are the user's. + let tables = client + .query( + "SELECT e.extname::text, c.oid::regclass::text, COALESCE(e.extcondition[i], '') + FROM pg_extension e + CROSS JOIN LATERAL generate_subscripts(e.extconfig, 1) AS i + JOIN pg_class c ON c.oid = e.extconfig[i] + WHERE c.relkind = 'r' AND e.extname <> $1 + ORDER BY 1, 2", + &[&TIMESCALEDB], + ) + .await + .map_err(source_err(dbname))?; + let mut holding = vec![]; + for table in tables { + let (extension, relation, condition): (String, String, String) = + (table.get(0), table.get(1), table.get(2)); + let has_rows: bool = client + .query_one( + &format!("SELECT EXISTS (SELECT 1 FROM {relation} {condition})"), + &[], + ) + .await + .map_err(source_err(dbname))? + .get(0); + if has_rows { + holding.push(format!("{relation} of {extension}")); + } + } + if !holding.is_empty() { + return Err(Error::BadRequest(format!( + "Database '{dbname}' has rows of its own in tables of its extensions ({}), which a \ + copy with data cannot carry: copy its schema only", + holding.join(", ") + ))); + } + Ok(()) +} + +/// Refuse a database with TimescaleDB hypertables: their rows live in chunk tables and catalog +/// rows of TimescaleDB's, which a replay as the copy's role can neither write nor reproduce. +async fn refuse_hypertables(client: &tokio_postgres::Client, dbname: &str) -> Result<()> { + let hypertables: Vec = client + .query( + "SELECT format('%I.%I', hypertable_schema, hypertable_name) + FROM timescaledb_information.hypertables ORDER BY 1", + &[], + ) + .await + .map_err(source_err(dbname))? + .iter() + .map(|row| row.get(0)) + .collect(); + if !hypertables.is_empty() { + return Err(Error::BadRequest(format!( + "Database '{dbname}' has TimescaleDB hypertables ({}), which a copy cannot carry yet", + hypertables.join(", ") + ))); + } + Ok(()) +} + +impl ExtensionPlan { + /// The extensions a database made to be this copy is created with, on a cluster Windmill + /// manages, by its administrator. + pub(crate) fn database_extensions(&self) -> Vec { + self.extensions.clone() + } + + /// Dump `source`, the database this plan was read from, as the script [`Self::restore`] + /// replays. Extensions are left out, their dependents with them, which leaving their archive + /// entries out of the replay would not do. `no_acl` as in [`PgDumpOptions`]; ownership never + /// carries over, as the restore runs as the target's connection user. + pub(crate) async fn dump( + &self, + db: &DB, + source: &PgDatabase, + schema_only: bool, + no_acl: bool, + ) -> Result { + let filter = write_lines( + &self + .extensions + .iter() + .map(|e| format!("exclude extension {}", quote_ident(&e.name))) + .collect::>(), + )?; + let archive = pg_dump_database( + source, + PgDumpOptions { + schema_only, + archive: true, + filter: filter.as_ref().map(|f| f.path.as_path()), + ..Default::default() + }, + ) + .await?; + // A hypertable made since the plan was read would be dumped as a plain table without its + // chunks. One made after the dump's snapshot is not in the dump at all. + if self.extensions.iter().any(|e| e.name == TIMESCALEDB) { + let (client, connection) = source.connect(Some(db)).await?; + let join_handle = tokio::spawn(async move { connection.await }); + let refused = refuse_hypertables(&client, &source.dbname).await; + drop(client); + windmill_common::shutdown_pg_connection(join_handle).await?; + refused?; + } + let list = self.restore_list(&archive).await?; + pg_restore_script( + &archive, + list.as_ref().map(|l| l.path.as_path()), + true, + no_acl, + ) + .await + } + + /// The `--use-list` file replaying every entry of `archive` but the skipped ones, when any is. + async fn restore_list(&self, archive: &DumpFile) -> Result> { + if self.skipped_entries.is_empty() && self.extension_schemas.is_empty() { + return Ok(None); + } + let listing = pg_restore_list(archive).await?; + let kept = skip_entries(&listing, &self.skipped_entries, &self.extension_schemas); + write_lines(&[kept]) + } + + /// Replay `dump` into `target`: its extensions first, which its role creates when it lacks + /// one, then the dump. + /// + /// Authorization: none. Callers MUST have authorized writing to `target`. + pub(crate) async fn restore( + &self, + db: &DB, + dump: &DumpFile, + target: &PgDatabase, + ) -> Result<()> { + self.prepare_target(db, target).await?; + pg_import_dump(target, dump).await + } + + /// Give `target`, as its own role, the schemas extensions live in and the extensions it lacks. + /// A database made from a template, or by a cluster administrator, may have them already. + async fn prepare_target(&self, db: &DB, target: &PgDatabase) -> Result<()> { + if self.extensions.is_empty() { + return Ok(()); + } + let (client, connection) = target.connect(Some(db)).await?; + let join_handle = tokio::spawn(async move { connection.await }); + let prepared = self.prepare_on(&client, target).await; + drop(client); + windmill_common::shutdown_pg_connection(join_handle).await?; + prepared + } + + async fn prepare_on(&self, client: &tokio_postgres::Client, target: &PgDatabase) -> Result<()> { + let target_err = |e: tokio_postgres::Error| { + Error::internal_err(format!( + "Failed to prepare database '{}' for a copy: {}", + target.dbname, + pg_error_message(&e) + )) + }; + for schema in &self.extension_schemas { + client + .batch_execute(&format!( + "CREATE SCHEMA IF NOT EXISTS {}", + quote_ident(schema) + )) + .await + .map_err(target_err)?; + } + // The replay leaves these to the copy, as a cluster administrator may have set them. The + // server quotes the comment, so no `standard_conforming_strings` lets it end the literal. + for extension in &self.extensions { + let Some(comment) = &extension.schema_comment else { + continue; + }; + let statement: Option = client + .query_opt( + "SELECT format('COMMENT ON SCHEMA %I IS %L', $1::text, $2::text) + FROM pg_namespace + WHERE nspname = $1::text + AND obj_description(oid, 'pg_namespace') IS DISTINCT FROM $2::text", + &[&extension.schema, comment], + ) + .await + .map_err(target_err)? + .map(|row| row.get(0)); + let Some(statement) = statement else { + continue; + }; + // A schema the database already had can be another role's: the copy goes without the + // comment rather than not at all. + if let Err(e) = client.batch_execute(&statement).await { + tracing::warn!( + "Not copying the comment on schema '{}' to '{}': {}", + extension.schema, + target.dbname, + pg_error_message(&e) + ); + } + } + // Creating an extension the database has would still need the rights to. + let present: BTreeSet = client + .query("SELECT extname::text FROM pg_extension", &[]) + .await + .map_err(target_err)? + .iter() + .map(|row| row.get(0)) + .collect(); + for extension in self + .extensions + .iter() + .filter(|e| !present.contains(&e.name)) + { + client + .batch_execute(&format!( + "CREATE EXTENSION IF NOT EXISTS {} WITH SCHEMA {} CASCADE", + quote_ident(&extension.name), + quote_ident(&extension.schema) + )) + .await + .map_err(|e| { + Error::BadRequest(format!( + "The copy needs extension '{}', which its database does not have and \ + role '{}' may not create: {}. Install the extension in the server's \ + template1 database, which new databases are made from, or let the role \ + create it.", + extension.name, + target.login_name(), + pg_error_message(&e).trim_end_matches('.') + )) + })?; + } + Ok(()) + } +} + +/// `lines` in a file of their own, or none when there are no lines. +fn write_lines(lines: &[String]) -> Result> { + if lines.is_empty() { + return Ok(None); + } + let file = DumpFile::new()?; + std::fs::File::create(&file.path) + .and_then(|mut f| f.write_all(lines.join("\n").as_bytes())) + .map_err(|e| Error::internal_err(format!("Failed to write a dump's file: {e}")))?; + Ok(Some(file)) +} + +/// `listing`, as `pg_restore --list` prints it, with the entries for `skipped` objects and the +/// comments on `uncommented_schemas` commented out. An entry reads `; +/// `. A comment's entry carries no oids, and names the +/// schema it is on as pg_dump writes it, quoted only when it has to be. +fn skip_entries( + listing: &str, + skipped: &BTreeSet<(u32, u32)>, + uncommented_schemas: &[String], +) -> String { + let skip = |line: &str| -> bool { + let Some((_, entry)) = line.split_once("; ") else { + return false; + }; + let mut oids = entry.split_whitespace(); + let object = ( + oids.next().and_then(|o| o.parse().ok()), + oids.next().and_then(|o| o.parse().ok()), + ); + if let (Some(catalog), Some(oid)) = object { + if skipped.contains(&(catalog, oid)) { + return true; + } + } + let Some(commented) = entry.strip_prefix("0 0 COMMENT - SCHEMA ") else { + return false; + }; + uncommented_schemas.iter().any(|schema| { + [schema.clone(), quote_ident(schema)] + .iter() + .any(|name| commented == name || commented.starts_with(&format!("{name} "))) + }) + }; + listing + .lines() + .map(|line| { + if skip(line) { + format!(";{line}") + } else { + line.to_string() + } + }) + .collect::>() + .join("\n") +} + +#[cfg(test)] +mod tests { + use super::skip_entries; + + #[test] + fn skip_entries_comments_out_only_the_skipped_objects() { + let listing = ";\n; Archive created at 2026-11-28\n\ + 278; 1259 17838 TABLE public m postgres\n\ + 3711; 2620 17842 TRIGGER public m retired postgres\n\ + 3712; 2620 17843 TRIGGER public m audit postgres\n\ + 6459; 0 0 COMMENT - SCHEMA \"My Ext\" postgres\n\ + 6461; 0 0 COMMENT - SCHEMA extensions postgres\n\ + 6462; 0 0 COMMENT - SCHEMA extensions_old postgres\n\ + 6463; 0 0 COMMENT - EXTENSION extensions "; + let kept = skip_entries( + listing, + &[(2620, 17842)].into_iter().collect(), + &["My Ext".to_string(), "extensions".to_string()], + ); + assert_eq!( + kept.lines().collect::>(), + [ + ";", + "; Archive created at 2026-11-28", + "278; 1259 17838 TABLE public m postgres", + ";3711; 2620 17842 TRIGGER public m retired postgres", + "3712; 2620 17843 TRIGGER public m audit postgres", + ";6459; 0 0 COMMENT - SCHEMA \"My Ext\" postgres", + ";6461; 0 0 COMMENT - SCHEMA extensions postgres", + "6462; 0 0 COMMENT - SCHEMA extensions_old postgres", + "6463; 0 0 COMMENT - EXTENSION extensions ", + ] + ); + } +} diff --git a/backend/windmill-api-workspaces/src/datatable_migrations.rs b/backend/windmill-api-workspaces/src/datatable_migrations.rs index 35ea6210dd..0ea6b10621 100644 --- a/backend/windmill-api-workspaces/src/datatable_migrations.rs +++ b/backend/windmill-api-workspaces/src/datatable_migrations.rs @@ -1946,6 +1946,7 @@ async fn generate_initial_datatable_migration( exclude_tables: &["_wm_migrations"], no_owner: true, no_acl, + ..Default::default() }, ) .await?; diff --git a/backend/windmill-api-workspaces/src/lib.rs b/backend/windmill-api-workspaces/src/lib.rs index cc5a7b9ab0..4f95f5089e 100644 --- a/backend/windmill-api-workspaces/src/lib.rs +++ b/backend/windmill-api-workspaces/src/lib.rs @@ -4,6 +4,7 @@ pub mod data_metrics; pub mod datatable_acl; pub mod datatable_acl_oss; pub mod datatable_clone; +pub mod datatable_extensions; pub mod datatable_migration_scope; pub mod datatable_migrations; pub mod datatable_permissions; diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 576e4c33e6..f753bb069e 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -3464,7 +3464,7 @@ pub(crate) struct DumpFile { } impl DumpFile { - fn new() -> Result { + pub(crate) fn new() -> Result { let dir = std::path::Path::new("/tmp/windmill"); std::fs::create_dir_all(dir) .map_err(|e| Error::internal_err(format!("Failed to create /tmp/windmill: {}", e)))?; @@ -3509,6 +3509,11 @@ impl Drop for DumpFile { pub(crate) struct PgDumpOptions<'a> { pub(crate) schema_only: bool, pub(crate) exclude_tables: &'a [&'a str], + /// A `--filter` file of what else to leave out (pg_dump 17+). + pub(crate) filter: Option<&'a std::path::Path>, + /// Write an archive for `pg_restore` rather than a `psql` script. `no_owner` and `no_acl` then + /// apply when restoring it ([`pg_restore_script`]). + pub(crate) archive: bool, /// Leave out `ALTER ... OWNER TO`. pub(crate) no_owner: bool, /// Leave out `GRANT`, `REVOKE` and `ALTER DEFAULT PRIVILEGES`. @@ -3542,7 +3547,16 @@ fn pg_dump_command( let user = pg_db.login_name(); let mut cmd = tokio::process::Command::new("pg_dump"); - cmd.arg("--format=plain").arg("--file").arg(dump_path); + cmd.arg(if opts.archive { + "--format=custom" + } else { + "--format=plain" + }) + .arg("--file") + .arg(dump_path); + if let Some(filter) = opts.filter { + cmd.arg("--filter").arg(filter); + } if opts.schema_only { cmd.arg("--schema-only"); } @@ -3576,12 +3590,37 @@ fn pg_dump_command( Ok((cmd, root_cert)) } +/// `--filter` is pg_dump 17's: an older client would refuse it as an unknown option. +async fn ensure_pg_dump_filters() -> Result<()> { + let output = tokio::process::Command::new("pg_dump") + .arg("--version") + .output() + .await + .map_err(|e| Error::internal_err(format!("Failed to execute pg_dump: {}", e)))?; + let version = String::from_utf8_lossy(&output.stdout); + let major = version.split_whitespace().find_map(|word| { + let digits: String = word.chars().take_while(char::is_ascii_digit).collect(); + digits.parse::().ok() + }); + match major { + Some(major) if major >= 17 => Ok(()), + _ => Err(Error::BadRequest(format!( + "Copying a database that uses extensions needs pg_dump 17 or later on the Windmill \ + server, which has {}", + version.trim() + ))), + } +} + /// Run pg_dump against a PgDatabase, writing output to a temp file on disk. /// Returns a DumpFile handle; the file is deleted when the handle is dropped. pub(crate) async fn pg_dump_database( pg_db: &PgDatabase, opts: PgDumpOptions<'_>, ) -> Result { + if opts.filter.is_some() { + ensure_pg_dump_filters().await?; + } let dump_file = DumpFile::new()?; let (mut cmd, _root_cert) = pg_dump_command(pg_db, opts, &dump_file.path)?; @@ -3599,6 +3638,61 @@ pub(crate) async fn pg_dump_database( Ok(dump_file) } +/// What a [`PgDumpOptions::archive`] dump holds, one entry a line as `pg_restore --list` prints +/// it: `; `, `;` starting a comment. +pub(crate) async fn pg_restore_list(archive: &DumpFile) -> Result { + let output = tokio::process::Command::new("pg_restore") + .arg("--list") + .arg(&archive.path) + .output() + .await + .map_err(|e| Error::internal_err(format!("Failed to execute pg_restore: {}", e)))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(Error::internal_err(format!( + "pg_restore failed: {}", + stderr + ))); + } + String::from_utf8(output.stdout) + .map_err(|e| Error::internal_err(format!("pg_restore listed a non-UTF-8 entry: {e}"))) +} + +/// A [`PgDumpOptions::archive`] dump as a script [`pg_import_dump`] replays, restricted to the +/// entries `list` keeps ([`pg_restore_list`]'s format) when given. +pub(crate) async fn pg_restore_script( + archive: &DumpFile, + list: Option<&std::path::Path>, + no_owner: bool, + no_acl: bool, +) -> Result { + let script = DumpFile::new()?; + let mut cmd = tokio::process::Command::new("pg_restore"); + cmd.arg("--file").arg(&script.path); + if let Some(list) = list { + cmd.arg("--use-list").arg(list); + } + if no_owner { + cmd.arg("--no-owner"); + } + if no_acl { + cmd.arg("--no-privileges"); + } + let output = cmd + .arg(&archive.path) + .output() + .await + .map_err(|e| Error::internal_err(format!("Failed to execute pg_restore: {}", e)))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(Error::internal_err(format!( + "pg_restore failed: {}", + stderr + ))); + } + Ok(script) +} + /// Whether `line` still belongs to the preamble pg_dump emits before the first /// dumped object: comments, blank lines, psql meta-commands and the session `SET`s. fn is_dump_preamble_line(line: &[u8]) -> bool { @@ -4116,6 +4210,7 @@ async fn create_pg_database( &req.target_dbname, "datatable", Some(&w_id), + &[], ) .await?; } else { @@ -4124,6 +4219,7 @@ async fn create_pg_database( &req.target_dbname, "datatable", Some(&w_id), + &[], ) .await?; } @@ -4356,16 +4452,17 @@ async fn import_pg_database( } else { None }; - let dump_file = pg_dump_database( - &source_pg, - PgDumpOptions { schema_only, no_owner: true, no_acl, ..Default::default() }, - ) - .await?; + let extensions = + crate::datatable_extensions::read_extension_plan(&db, &source_pg, schema_only).await?; + let dump = extensions.dump(&db, &source_pg, schema_only, no_acl).await?; let applied = match migrations_lock { Some(client) => Some(crate::datatable_migrations::read_applied_migrations(&client).await?), None => None, }; - pg_import_dump(&target_pg, &dump_file).await?; + // The target's role creates any extension it lacks. A cluster administrator creates them only + // with a database, before anyone may write to it, and this target was created by an earlier + // request. + extensions.restore(&db, &dump, &target_pg).await?; if let Some(applied) = applied { crate::datatable_migrations::write_applied_migrations(&db, &target_pg, &applied).await?; } diff --git a/backend/windmill-common/src/external_instance_pg.rs b/backend/windmill-common/src/external_instance_pg.rs index 72920a1874..855bde31c2 100644 --- a/backend/windmill-common/src/external_instance_pg.rs +++ b/backend/windmill-common/src/external_instance_pg.rs @@ -262,7 +262,7 @@ pub async fn external_instance_connection_unchecked( } /// Create `dbname` on the external cluster and register it. Refuses a name already taken there, -/// whoever took it. +/// whoever took it. `extensions` are created in it first, as [`crate::provision_extensions`] does. /// /// Runs on `tx`, which it takes [`lock_external_instance_pg_state`] on: the registration lands when /// the caller commits. Take that lock before any database governance lock, as saves do. @@ -275,6 +275,7 @@ pub async fn create_external_instance_database_unchecked( dbname: &str, tag: &str, for_workspace: Option<&str>, + extensions: &[crate::DatabaseExtension], ) -> Result<()> { crate::external_instance_pg_oss::create_external_instance_database_unchecked( db, @@ -282,6 +283,7 @@ pub async fn create_external_instance_database_unchecked( dbname, tag, for_workspace, + extensions, ) .await } diff --git a/backend/windmill-common/src/external_instance_pg_oss.rs b/backend/windmill-common/src/external_instance_pg_oss.rs index 93b6fc63dd..f1683e13dd 100644 --- a/backend/windmill-common/src/external_instance_pg_oss.rs +++ b/backend/windmill-common/src/external_instance_pg_oss.rs @@ -68,6 +68,7 @@ mod ce { _dbname: &str, _tag: &str, _for_workspace: Option<&str>, + _extensions: &[crate::DatabaseExtension], ) -> Result<()> { Err(unavailable()) } diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index b462b9987d..186a93cbc0 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -2168,6 +2168,162 @@ pub(crate) fn instance_db_grants(dbname: &str) -> String { ) } +/// An extension a managed database is created with, in `schema`. +#[derive(Clone, Debug, PartialEq)] +pub struct DatabaseExtension { + pub name: String, + pub schema: String, + /// The schema's comment, which the copy's own replay may not be allowed to set. + pub schema_comment: Option, +} + +/// Create `extensions` in database `dbname`, just created, on `client`, the cluster +/// administrator's connection to it, before `custom_instance_user` holds anything there. +/// +/// An extension's script runs as the administrator and resolves names through the schemas it is +/// created in, so an object another role planted there first would run with the administrator's +/// rights. So `PUBLIC` loses `CREATE` on `public` (which Postgres before 15 grants), the database +/// must hold nothing that a role other than a superuser or the administrator owns, and a schema +/// made for an extension is the administrator's until the extension is in it, then +/// `custom_instance_user`'s, or failing that open to it, as in the database it was copied from. +pub(crate) async fn provision_extensions( + client: &tokio_postgres::Client, + dbname: &str, + extensions: &[DatabaseExtension], +) -> error::Result<()> { + if extensions.is_empty() { + return Ok(()); + } + let err = |context: &str, e: tokio_postgres::Error| { + error::Error::BadRequest(format!( + "{context} database '{dbname}': {}", + crate::error::pg_error_message(&e) + )) + }; + // Committed before the check, so nothing can be added to `public` behind it. + client + .batch_execute("REVOKE CREATE ON SCHEMA public FROM PUBLIC") + .await + .map_err(|e| err("Preparing", e))?; + let foreign: Vec = client + .query( + "SELECT DISTINCT pg_get_userbyid(o.owner)::text FROM ( + SELECT relowner AS owner FROM pg_class UNION ALL + SELECT proowner FROM pg_proc UNION ALL + SELECT typowner FROM pg_type UNION ALL + SELECT oprowner FROM pg_operator UNION ALL + SELECT opcowner FROM pg_opclass UNION ALL + SELECT opfowner FROM pg_opfamily UNION ALL + SELECT collowner FROM pg_collation UNION ALL + SELECT conowner FROM pg_conversion UNION ALL + SELECT cfgowner FROM pg_ts_config UNION ALL + SELECT dictowner FROM pg_ts_dict UNION ALL + SELECT nspowner FROM pg_namespace UNION ALL + SELECT stxowner FROM pg_statistic_ext UNION ALL + SELECT extowner FROM pg_extension + ) o JOIN pg_roles r ON r.oid = o.owner + WHERE NOT r.rolsuper AND o.owner <> current_user::regrole + AND r.rolname <> 'pg_database_owner'", + &[], + ) + .await + .map_err(|e| err("Checking", e))? + .iter() + .map(|row| row.get(0)) + .collect(); + if !foreign.is_empty() { + return Err(error::Error::BadRequest(format!( + "Database '{dbname}' already holds objects of {}, so its extensions cannot be created \ + in it safely", + foreign.join(", ") + ))); + } + let mut setup = String::new(); + // Only a schema made here is handed over: one the database already has, `public` and + // `pg_catalog` among them, keeps its owner. + let existing: std::collections::BTreeSet = client + .query("SELECT nspname::text FROM pg_namespace", &[]) + .await + .map_err(|e| err("Checking", e))? + .iter() + .map(|row| row.get(0)) + .collect(); + let schemas: std::collections::BTreeSet<&str> = extensions + .iter() + .map(|e| e.schema.as_str()) + .filter(|s| !existing.contains(*s)) + .collect(); + for schema in &schemas { + setup.push_str(&format!( + "CREATE SCHEMA IF NOT EXISTS {};\n", + datatable_roles::quote_ident(schema) + )); + } + for extension in extensions { + setup.push_str(&format!( + "CREATE EXTENSION IF NOT EXISTS {} WITH SCHEMA {} CASCADE;\n", + datatable_roles::quote_ident(&extension.name), + datatable_roles::quote_ident(&extension.schema) + )); + } + client + .batch_execute(&format!("BEGIN;\n{setup}COMMIT;")) + .await + .map_err(|e| err("Creating the extensions of", e))?; + // While the administrator still owns the schemas it made: the copy's role may own neither one + // the database already had nor one the handover below falls back from, and only an owner may + // comment on a schema. The server quotes the comment, the source's text, so no setting of + // `standard_conforming_strings` lets it end the literal. + for extension in extensions { + let Some(comment) = &extension.schema_comment else { + continue; + }; + let statement: Option = client + .query_opt( + "SELECT format('COMMENT ON SCHEMA %I IS %L', $1::text, $2::text) + FROM pg_namespace + WHERE nspname = $1::text + AND obj_description(oid, 'pg_namespace') IS DISTINCT FROM $2::text", + &[&extension.schema, comment], + ) + .await + .map_err(|e| err("Checking", e))? + .map(|row| row.get(0)); + let Some(statement) = statement else { + continue; + }; + match client.batch_execute(&statement).await { + Ok(()) => {} + // A schema the database already had can be another superuser's: the copy goes without + // the comment rather than not at all. + Err(e) if !schemas.contains(extension.schema.as_str()) => tracing::warn!( + "Not copying the comment on schema '{}' to '{dbname}': {}", + extension.schema, + crate::error::pg_error_message(&e) + ), + Err(e) => return Err(err("Commenting the extension schemas of", e)), + } + } + for schema in schemas { + let schema = datatable_roles::quote_ident(schema); + let handed = client + .batch_execute(&format!( + "ALTER SCHEMA {schema} OWNER TO custom_instance_user" + )) + .await; + if handed.is_err() { + client + .batch_execute(&format!( + "GRANT USAGE, CREATE ON SCHEMA {schema} TO custom_instance_user \ + WITH GRANT OPTION" + )) + .await + .map_err(|e| err("Granting access to the extension schemas of", e))?; + } + } + Ok(()) +} + /// Re-apply [`instance_db_grants`] to a managed database provisioned before data table roles /// existed, whose grants carry no grant option. Connects as the cluster's administrator — the /// database and `public` schema owner — since only it can hand out an option it holds. @@ -2187,11 +2343,13 @@ pub async fn ensure_instance_db_grant_options_unchecked( /// Create a custom instance database: CREATE DATABASE, grant permissions, register in global_settings. /// The `tag` is stored in global_settings metadata (e.g. "datatable" or "ducklake"). `for_workspace` /// is the workspace a member creates a fork copy for; see [`ensure_fork_database_available_to`]. +/// `extensions` are created first, as [`provision_extensions`] does. pub async fn create_custom_instance_database( db: &DB, dbname: &str, tag: &str, for_workspace: Option<&str>, + extensions: &[DatabaseExtension], ) -> error::Result<()> { let dbname = dbname.trim(); validate_dbname(dbname)?; @@ -2221,7 +2379,9 @@ pub async fn create_custom_instance_database( // Nothing names a database that failed past this point, and its name blocks the retry: drop it // rather than leave it behind. - if let Err(e) = finish_custom_instance_database(db, dbname, tag, for_workspace).await { + if let Err(e) = + finish_custom_instance_database(db, dbname, tag, for_workspace, extensions).await + { match drop_unused_instance_database(db, dbname).await { Ok(Cleanup::InUse(users)) => tracing::warn!( "Kept '{dbname}' after failing to set it up: workspaces {} use it", @@ -2262,6 +2422,7 @@ async fn finish_custom_instance_database( dbname: &str, tag: &str, for_workspace: Option<&str>, + extensions: &[DatabaseExtension], ) -> error::Result<()> { // Grant permissions to custom_instance_user let wmill_pg_creds = PgDatabase::parse_uri(&get_database_url().await?.as_str().await)?; @@ -2269,6 +2430,13 @@ async fn finish_custom_instance_database( let (client, connection) = new_pg_creds.connect(Some(db)).await?; let join_handle = tokio::spawn(async move { connection.await }); + // Before the grants, as `provision_extensions` requires. + if let Err(e) = provision_extensions(&client, dbname, extensions).await { + drop(client); + let _ = shutdown_pg_connection(join_handle).await; + return Err(e); + } + if let Err(e) = client.batch_execute(&instance_db_grants(dbname)).await { tracing::warn!( "Failed to grant permissions on '{}': {}. Continuing.",