diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index bdc3c2f5be..b99a90684d 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -526e8ad937cc09cdbd36f06434e2a0cee9e575bb +71f59f5c66584f7c8c8200a0945fdac9cac0b084 \ No newline at end of file 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 b30ac1f9a5..8df1176ee0 100644 --- a/backend/windmill-api-workspaces/src/datatable_clone.rs +++ b/backend/windmill-api-workspaces/src/datatable_clone.rs @@ -28,9 +28,7 @@ use windmill_common::workspaces::{ use windmill_common::{PgDatabase, DB}; use crate::datatable_acl::connect_with_notices; -use crate::datatable_extensions::{ - read_extension_plan, ExtensionCreator, ExtensionPlan, PlannedDump, -}; +use crate::datatable_extensions::{read_extension_plan, ExtensionPlan, PlannedDump}; use crate::datatable_migrations::{ lock_migration_runs_on, read_applied_migrations, write_applied_migrations, AppliedMigrations, }; @@ -477,6 +475,9 @@ async fn make_copy( 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( @@ -484,6 +485,7 @@ async fn make_copy( request.dbname, "datatable", Some(parent_w_id), + &extensions.database_extensions(), ) .await? } @@ -495,6 +497,7 @@ async fn make_copy( request.dbname, "datatable", Some(parent_w_id), + &extensions.database_extensions(), ) .await?; tx.commit().await?; @@ -515,8 +518,6 @@ async fn make_copy( &target, dump, &extensions, - // Created above, on the source's own server. - ExtensionCreator::for_new_copy_of(source_database.resource_type), applied.as_ref(), ) .await; @@ -559,10 +560,9 @@ async fn fill( target: &PgDatabase, dump: PlannedDump, extensions: &ExtensionPlan, - creator: ExtensionCreator, applied: Option<&AppliedMigrations>, ) -> Result { - extensions.restore(db, dump, target, creator).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 index f517e9d0b2..e71ae33288 100644 --- a/backend/windmill-api-workspaces/src/datatable_extensions.rs +++ b/backend/windmill-api-workspaces/src/datatable_extensions.rs @@ -10,14 +10,18 @@ //! //! 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 before the -//! replay by an [`ExtensionCreator`]. +//! 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`]). //! //! TimescaleDB keeps a hypertable's rows in chunk tables and bookkeeping of its own, which a replay //! can neither write nor reproduce. The chunks are left out of the dump and each hypertable is made -//! one again in the copy. Its rows are streamed from the source between the dump's data and its -//! post-data section, where pg_dump would load them: before the triggers that would fire on them -//! and the materialized views refreshed from them, and in the dump's own snapshot. +//! one again in the copy. Its rows are streamed from the source between the dump's pre-data and +//! data sections, where pg_dump would load them: before the triggers that would fire on them and +//! the materialized views refreshed from them, and in the dump's own snapshot. use std::collections::BTreeSet; use std::io::Write; @@ -25,11 +29,10 @@ use std::io::Write; use futures::{SinkExt, StreamExt}; use tokio_postgres::types::ToSql; use windmill_common::error::{pg_error_message, Error, Result}; -use windmill_common::workspaces::DataTableCatalogResourceType; -use windmill_common::{PgDatabase, DB}; +use windmill_common::{DatabaseExtension, PgDatabase, DB}; use crate::workspaces::{ - pg_dump_database, pg_import_dump, pg_restore_section, DumpFile, PgDumpOptions, + pg_dump_database, pg_import_dump, pg_restore_list, pg_restore_script, DumpFile, PgDumpOptions, }; const TIMESCALEDB: &str = "timescaledb"; @@ -40,10 +43,12 @@ const TIMESCALEDB_INTERNAL: &str = "_timescaledb_internal"; #[derive(Default)] pub(crate) struct ExtensionPlan { /// In creation order, so an extension comes after those it requires. - extensions: Vec, + extensions: Vec, /// Schemas holding an extension that the dump creates too. The copy needs them before its - /// extensions, so they are made first and the dump's `CREATE SCHEMA` is commented out. + /// extensions, so they are made first and the dump's `CREATE SCHEMA` is not replayed. extension_schemas: Vec, + /// The source objects whose archive entries are not replayed, as `(catalog oid, object oid)`. + skipped_entries: BTreeSet<(u32, u32)>, hypertables: Vec, /// Every chunk of every hypertable, `"schema"."table"` as pg_dump patterns read them. chunks: Vec, @@ -52,11 +57,6 @@ pub(crate) struct ExtensionPlan { snapshot: Option<(SnapshotSession, String)>, } -struct SourceExtension { - name: String, - schema: String, -} - struct Hypertable { schema: String, name: String, @@ -103,7 +103,7 @@ pub(crate) async fn read_extension_plan( let join_handle = tokio::spawn(async move { connection.await }); let read = async { let plan = read_plan(&client, &source.dbname, schema_only).await?; - let hypertables: Vec = if plan.extensions.iter().any(|e| e.name == TIMESCALEDB) { + let hypertables: Vec = if plan.uses_timescaledb() { client .query( "SELECT format('%I.%I', hypertable_schema, hypertable_name) @@ -126,7 +126,7 @@ pub(crate) async fn read_extension_plan( let (mut plan, hypertables) = read?; // The chunks to leave out are read in the snapshot the dump is then taken in: a chunk made in // between would otherwise be dumped as a table of its own, inheriting from its hypertable. - if plan.extensions.iter().any(|e| e.name == TIMESCALEDB) { + if plan.uses_timescaledb() { let (snapshot, snapshot_id) = SnapshotSession::open(db, source, &hypertables).await?; let read = async { read_hypertables(&snapshot.client, &source.dbname, &mut plan).await?; @@ -175,7 +175,8 @@ async fn read_plan( 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') + AND d.deptype = 'e'), + 'pg_namespace'::regclass::oid, n.oid FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace WHERE e.extname <> 'plpgsql' ORDER BY e.oid", @@ -188,9 +189,10 @@ async fn read_plan( for row in rows { if row.get::<_, bool>(2) { extension_schemas.insert(row.get::<_, String>(1)); + plan.skipped_entries.insert((row.get(3), row.get(4))); } plan.extensions - .push(SourceExtension { name: row.get(0), schema: row.get(1) }); + .push(DatabaseExtension { name: row.get(0), schema: row.get(1) }); } plan.extension_schemas = extension_schemas.into_iter().collect(); @@ -342,38 +344,30 @@ async fn read_hypertables( .map(|row| row.get(0)) .collect(); } + + // `ts_insert_blocker`, the trigger older TimescaleDB versions put on a hypertable, is made by + // `create_hypertable` again: the dump's would already exist. + let blockers = client + .query( + "SELECT 'pg_trigger'::regclass::oid, t.oid FROM pg_trigger t + WHERE t.tgname = 'ts_insert_blocker' AND NOT t.tgisinternal + AND t.tgrelid IN ( + SELECT format('%I.%I', hypertable_schema, hypertable_name)::regclass + FROM timescaledb_information.hypertables)", + &[], + ) + .await + .map_err(source_err(dbname))?; + plan.skipped_entries + .extend(blockers.iter().map(|row| (row.get(0), row.get(1)))); Ok(()) } -/// Who creates the extensions a copy lacks. -#[derive(Clone, Copy)] -pub(crate) enum ExtensionCreator { - /// The target's own connection role, which may create only trusted extensions. - TargetRole, - /// The administrator of the cluster Windmill manages the target on. - ClusterAdmin(DataTableCatalogResourceType), -} - -impl ExtensionCreator { - /// For a copy of a database of `kind` into a database the caller has just created on the same - /// server, before anyone could have written to it. The source names the extensions created, - /// so the administrator creates them only there: a source elsewhere could name an untrusted - /// extension, and a database its role could already write to may hold objects that an - /// extension script running as the administrator would pick up. - pub(crate) fn for_new_copy_of(kind: DataTableCatalogResourceType) -> Self { - if kind.is_windmill_managed() { - Self::ClusterAdmin(kind) - } else { - Self::TargetRole - } - } -} - /// A dump of a source, made by [`ExtensionPlan::dump`] and replayed by /// [`ExtensionPlan::restore`]. pub(crate) enum PlannedDump { - Script(DumpFile), - /// A copy with data of hypertables, whose rows load between `data` and `post_data` through + Whole(DumpFile), + /// A copy with data of hypertables, whose rows load between `pre_data` and `data` through /// `snapshot`, the session whose snapshot the dump was taken in. Sections { pre_data: DumpFile, @@ -447,15 +441,26 @@ impl SnapshotSession { } impl ExtensionPlan { + fn uses_timescaledb(&self) -> bool { + self.extensions.iter().any(|e| e.name == TIMESCALEDB) + } + + /// 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() + } + /// The `--filter` lines leaving out what the copy gets otherwise: every extension, and every - /// relation TimescaleDB makes for itself. + /// relation TimescaleDB makes for itself. Dependents go with them, which leaving their archive + /// entries out of the replay would not do. fn filter_lines(&self) -> Vec { let mut lines: Vec = self .extensions .iter() .map(|e| format!("exclude extension {}", quote_ident(&e.name))) .collect(); - if self.extensions.iter().any(|e| e.name == TIMESCALEDB) { + if self.uses_timescaledb() { lines.push(format!( "exclude schema {}", quote_ident(TIMESCALEDB_INTERNAL) @@ -478,61 +483,50 @@ impl ExtensionPlan { schema_only: bool, no_acl: bool, ) -> Result { - let lines = self.filter_lines(); - let filter = if lines.is_empty() { - None - } else { - 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 dump filter: {e}")))?; - Some(file) - }; - let filter_path = filter.as_ref().map(|f| f.path.as_path()); - + let filter = write_lines(&self.filter_lines())?; let (snapshot, snapshot_id) = match self.snapshot.take() { Some((session, id)) => (Some(session), Some(id)), None => (None, None), }; - if schema_only || self.hypertables.is_empty() { - let dump = pg_dump_database( - source, - PgDumpOptions { - schema_only, - no_owner: true, - no_acl, - filter: filter_path, - snapshot: snapshot_id.as_deref(), - ..Default::default() - }, - ) - .await; - if let Some(snapshot) = snapshot { - snapshot.close().await; + let archive = pg_dump_database( + source, + PgDumpOptions { + schema_only, + archive: true, + filter: filter.as_ref().map(|f| f.path.as_path()), + snapshot: snapshot_id.as_deref(), + ..Default::default() + }, + ) + .await; + let sectioned = !schema_only && !self.hypertables.is_empty(); + let snapshot = match (snapshot, sectioned) { + (Some(snapshot), true) => snapshot, + (snapshot, _) => { + if let Some(snapshot) = snapshot { + snapshot.close().await; + } + if sectioned { + return Err(Error::internal_err( + "the hypertables of a copy were read outside a snapshot", + )); + } + let archive = archive?; + let list = self.restore_list(&archive).await?; + let list = list.as_ref().map(|l| l.path.as_path()); + return Ok(PlannedDump::Whole( + pg_restore_script(&archive, None, list, true, no_acl).await?, + )); } - return Ok(PlannedDump::Script(dump?)); - } - - let (Some(snapshot), Some(snapshot_id)) = (snapshot, snapshot_id) else { - return Err(Error::internal_err( - "the hypertables of a copy were read outside a snapshot", - )); }; let sections = async { - let archive = pg_dump_database( - source, - PgDumpOptions { - archive: true, - filter: filter_path, - snapshot: Some(&snapshot_id), - ..Default::default() - }, - ) - .await?; + let archive = archive?; + let list = self.restore_list(&archive).await?; + let list = list.as_ref().map(|l| l.path.as_path()); Ok::<_, Error>(( - pg_restore_section(&archive, "pre-data", true, no_acl).await?, - pg_restore_section(&archive, "data", true, no_acl).await?, - pg_restore_section(&archive, "post-data", true, no_acl).await?, + pg_restore_script(&archive, Some("pre-data"), list, true, no_acl).await?, + pg_restore_script(&archive, Some("data"), list, true, no_acl).await?, + pg_restore_script(&archive, Some("post-data"), list, true, no_acl).await?, )) } .await; @@ -547,36 +541,42 @@ impl ExtensionPlan { } } - /// Replay `dump` into `target`: its extensions first, created by `creator`, then the dump, - /// with each hypertable made one again and, in a copy with data, its rows loaded where pg_dump - /// would load them. A copy with data of hypertables replays in several transactions, so one - /// that fails part way leaves `target` partly filled. + /// 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() { + return Ok(None); + } + let listing = pg_restore_list(archive).await?; + let kept = skip_entries(&listing, &self.skipped_entries); + write_lines(&[kept]) + } + + /// Replay `dump` into `target`: its extensions first, which its role creates when it lacks + /// one, then the dump, with each hypertable made one again and, in a copy with data, its rows + /// loaded where pg_dump would load them. A copy with data of hypertables replays in several + /// transactions, so one that fails part way leaves `target` partly filled. /// - /// Authorization: none. Callers MUST have authorized writing to `target`, and pick `creator` - /// as [`ExtensionCreator::for_new_copy_of`] says. + /// Authorization: none. Callers MUST have authorized writing to `target`. pub(crate) async fn restore( &self, db: &DB, dump: PlannedDump, target: &PgDatabase, - creator: ExtensionCreator, ) -> Result<()> { match dump { - PlannedDump::Script(script) => { - self.prepare_target(db, target, creator, &script).await?; - // Replayed before the hypertables are made again, so `ONLY` still applies. - self.patch_for_hypertables(&script, false).await?; + PlannedDump::Whole(script) => { + self.prepare_target(db, target).await?; pg_import_dump(target, &script).await?; self.make_hypertables(db, target, None).await } PlannedDump::Sections { pre_data, data, post_data, snapshot } => { let restored = async { - self.prepare_target(db, target, creator, &pre_data).await?; + self.prepare_target(db, target).await?; pg_import_dump(target, &pre_data).await?; self.make_hypertables(db, target, Some(&snapshot.client)) .await?; pg_import_dump(target, &data).await?; - self.patch_for_hypertables(&post_data, true).await?; + self.drop_only_on_hypertables(&post_data).await?; pg_import_dump(target, &post_data).await } .await; @@ -586,19 +586,13 @@ impl ExtensionPlan { } } - /// Make `script`'s statements on the source's hypertables replayable on the copy's: - /// - `ts_insert_blocker`, the trigger older TimescaleDB versions put on a hypertable, is made - /// by `create_hypertable` too, so the script's would already exist; - /// - with `drop_only`, for a script replayed once they are hypertables: TimescaleDB refuses - /// `ALTER TABLE ONLY` on one, which pg_dump adds constraints with. Without `ONLY` the - /// constraint goes on the hypertable, and TimescaleDB gives each chunk its own. - async fn patch_for_hypertables(&self, script: &DumpFile, drop_only: bool) -> Result<()> { - if self.hypertables.is_empty() { - return Ok(()); - } + /// TimescaleDB refuses `ALTER TABLE ONLY` on a hypertable, which the post-data section, replayed + /// once they are hypertables, adds constraints with. Without `ONLY` the constraint goes on the + /// hypertable, and TimescaleDB gives each chunk its own. + async fn drop_only_on_hypertables(&self, post_data: &DumpFile) -> Result<()> { let io_err = |e: std::io::Error| Error::internal_err(format!("Failed to patch dump file: {e}")); - let text = tokio::fs::read_to_string(&script.path) + let text = tokio::fs::read_to_string(&post_data.path) .await .map_err(io_err)?; let hypertables: BTreeSet<(&str, &str)> = self @@ -608,56 +602,37 @@ impl ExtensionPlan { .collect(); let mut patched = String::with_capacity(text.len()); for line in text.split_inclusive('\n') { - if line.starts_with("CREATE TRIGGER ts_insert_blocker ") { - patched.push_str("-- "); - patched.push_str(line); - continue; - } - let only_on_hypertable = drop_only - && line - .trim_end() - .strip_prefix("ALTER TABLE ONLY ") - .and_then(parse_qualified) - .is_some_and(|(schema, name)| hypertables.contains(&(&schema, &name))); + let only_on_hypertable = line + .trim_end() + .strip_prefix("ALTER TABLE ONLY ") + .and_then(parse_qualified) + .is_some_and(|(schema, name)| hypertables.contains(&(&schema, &name))); if only_on_hypertable { patched.push_str(&line.replacen("ALTER TABLE ONLY ", "ALTER TABLE ", 1)); } else { patched.push_str(line); } } - tokio::fs::write(&script.path, patched) + tokio::fs::write(&post_data.path, patched) .await .map_err(io_err) } - /// Give `target` the source's extensions before `script` is replayed into it. - async fn prepare_target( - &self, - db: &DB, - target: &PgDatabase, - creator: ExtensionCreator, - script: &DumpFile, - ) -> Result<()> { + /// 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 missing = self.create_schemas_and_list_missing(&client, target).await; + let prepared = self.prepare_on(&client, target).await; drop(client); windmill_common::shutdown_pg_connection(join_handle).await?; - for extension in missing? { - create_extension(db, target, creator, extension).await?; - } - comment_out_schema_creations(script, &self.extension_schemas).await + prepared } - /// Made by the target's own role, so what the replay puts in them is its own. - async fn create_schemas_and_list_missing( - &self, - client: &tokio_postgres::Client, - target: &PgDatabase, - ) -> Result> { + 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: {}", @@ -674,8 +649,7 @@ impl ExtensionPlan { .await .map_err(target_err)?; } - // A database made from a template carrying extensions already has them, and creating one - // it has would still need the rights to. + // Creating an extension the database has would still need the rights to. let present: BTreeSet = client .query("SELECT extname::text FROM pg_extension", &[]) .await @@ -683,11 +657,31 @@ impl ExtensionPlan { .iter() .map(|row| row.get(0)) .collect(); - Ok(self + for extension in self .extensions .iter() .filter(|e| !present.contains(&e.name)) - .collect()) + { + 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(()) } /// Make each hypertable of the source one again in `target`, streaming its rows from `rows` @@ -843,69 +837,34 @@ async fn copy_rows( Ok(()) } -async fn create_extension( - db: &DB, - target: &PgDatabase, - creator: ExtensionCreator, - extension: &SourceExtension, -) -> Result<()> { - let sql = format!( - "CREATE EXTENSION IF NOT EXISTS {} WITH SCHEMA {} CASCADE", - quote_ident(&extension.name), - quote_ident(&extension.schema) - ); - let name = &extension.name; - match creator { - ExtensionCreator::ClusterAdmin(DataTableCatalogResourceType::ExternalInstance) => { - windmill_common::external_instance_pg::execute_as_external_instance_admin_unchecked( - db, - &target.dbname, - &sql, - ) - .await - .map_err(|e| { - Error::BadRequest(format!( - "Could not create extension '{name}' in the copy as the external instance \ - cluster's admin login: {e}" - )) - }) - } - ExtensionCreator::ClusterAdmin(DataTableCatalogResourceType::Instance) => { - let windmill = - PgDatabase::parse_uri(&windmill_common::get_database_url().await?.as_str().await)?; - let admin = PgDatabase { dbname: target.dbname.clone(), ..windmill }; - execute(db, &admin, &sql).await.map_err(|e| { - Error::BadRequest(format!( - "Could not create extension '{name}' in the copy as Windmill's database user: \ - {e}" - )) - }) - } - ExtensionCreator::ClusterAdmin(DataTableCatalogResourceType::Postgresql) - | ExtensionCreator::TargetRole => execute(db, target, &sql).await.map_err(|e| { - Error::BadRequest(format!( - "The copy needs extension '{name}', which its new 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.", - target.login_name(), - e.trim_end_matches('.') - )) - }), +/// `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)) } -async fn execute(db: &DB, pg: &PgDatabase, sql: &str) -> std::result::Result<(), String> { - let (client, connection) = pg.connect(Some(db)).await.map_err(|e| e.to_string())?; - let join_handle = tokio::spawn(async move { connection.await }); - let result = client - .batch_execute(sql) - .await - .map_err(|e| pg_error_message(&e)); - drop(client); - if let Err(e) = windmill_common::shutdown_pg_connection(join_handle).await { - tracing::warn!("Closing the connection to '{}': {e}", pg.dbname); - } - result +/// `listing`, as `pg_restore --list` prints it, with the entries for `skipped` objects commented +/// out. An entry reads `; ...`. +fn skip_entries(listing: &str, skipped: &BTreeSet<(u32, u32)>) -> String { + let object = |line: &str| -> Option<(u32, u32)> { + let (_, entry) = line.split_once("; ")?; + let mut oids = entry.split_whitespace(); + Some((oids.next()?.parse().ok()?, oids.next()?.parse().ok()?)) + }; + listing + .lines() + .map(|line| match object(line) { + Some(object) if skipped.contains(&object) => format!(";{line}"), + _ => line.to_string(), + }) + .collect::>() + .join("\n") } /// A `schema.name` as pg_dump writes it, each part double-quoted only when it has to be, unquoted. @@ -938,68 +897,9 @@ fn parse_ident(s: &str) -> Option<(String, &str)> { } } -/// The schema a `CREATE SCHEMA ;` line of a dump creates, unquoted. -fn created_schema(line: &str) -> Option { - let name = line - .strip_prefix("CREATE SCHEMA ")? - .trim_end() - .strip_suffix(';')?; - match name.strip_prefix('"').and_then(|n| n.strip_suffix('"')) { - Some(quoted) => Some(quoted.replace("\"\"", "\"")), - None => Some(name.to_string()), - } -} - -/// Comment out the script's `CREATE SCHEMA` of each of `schemas`, which the copy already has, in -/// place and three bytes each so the rest of the script stays where it is. pg_dump writes every -/// schema before any other object, so the scan stops at the first other `CREATE` or `COPY`. -async fn comment_out_schema_creations(script: &DumpFile, schemas: &[String]) -> Result<()> { - use tokio::io::{AsyncBufReadExt, AsyncSeekExt, AsyncWriteExt}; - - if schemas.is_empty() { - return Ok(()); - } - let io_err = |e: std::io::Error| Error::internal_err(format!("Failed to patch dump file: {e}")); - let file = tokio::fs::File::open(&script.path).await.map_err(io_err)?; - let mut reader = tokio::io::BufReader::new(file); - let mut offsets = vec![]; - let mut offset = 0u64; - let mut line = String::new(); - loop { - line.clear(); - let read = reader.read_line(&mut line).await.map_err(io_err)?; - if read == 0 { - break; - } - if let Some(schema) = created_schema(&line) { - if schemas.contains(&schema) { - offsets.push(offset); - } - } else if line.starts_with("CREATE ") || line.starts_with("COPY ") { - break; - } - offset += read as u64; - } - if offsets.is_empty() { - return Ok(()); - } - let mut file = tokio::fs::OpenOptions::new() - .write(true) - .open(&script.path) - .await - .map_err(io_err)?; - for offset in offsets { - file.seek(std::io::SeekFrom::Start(offset)) - .await - .map_err(io_err)?; - file.write_all(b"-- ").await.map_err(io_err)?; - } - file.flush().await.map_err(io_err) -} - #[cfg(test)] mod tests { - use super::{created_schema, parse_qualified}; + use super::{parse_qualified, skip_entries}; #[test] fn parse_qualified_unquotes_what_pg_dump_quotes() { @@ -1014,15 +914,21 @@ mod tests { } #[test] - fn created_schema_unquotes_what_pg_dump_quotes() { + 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 ts_insert_blocker postgres\n\ + 3712; 2620 17843 TRIGGER public m audit postgres"; + let kept = skip_entries(listing, &[(2620, 17842)].into_iter().collect()); assert_eq!( - created_schema("CREATE SCHEMA extensions;\n").as_deref(), - Some("extensions") + kept.lines().collect::>(), + [ + ";", + "; Archive created at 2026-11-28", + "278; 1259 17838 TABLE public m postgres", + ";3711; 2620 17842 TRIGGER public m ts_insert_blocker postgres", + "3712; 2620 17843 TRIGGER public m audit postgres", + ] ); - assert_eq!( - created_schema("CREATE SCHEMA \"My \"\"Ext\"\"\";").as_deref(), - Some("My \"Ext\"") - ); - assert_eq!(created_schema("CREATE TABLE public.t ("), None); } } diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 9a8b1a7de9..3e4144c247 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -3514,7 +3514,7 @@ pub(crate) struct PgDumpOptions<'a> { /// Dump as of a snapshot another session exported, rather than one of its own. pub(crate) snapshot: Option<&'a str>, /// Write an archive for `pg_restore` rather than a `psql` script. `no_owner` and `no_acl` then - /// apply when restoring it ([`pg_restore_section`]). + /// apply when restoring it ([`pg_restore_script`]). pub(crate) archive: bool, /// Leave out `ALTER ... OWNER TO`. pub(crate) no_owner: bool, @@ -3643,19 +3643,45 @@ pub(crate) async fn pg_dump_database( Ok(dump_file) } -/// One section of a [`PgDumpOptions::archive`] dump (`pre-data`, `data` or `post-data`), as a -/// script [`pg_import_dump`] replays. -pub(crate) async fn pg_restore_section( +/// 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: one `section` +/// (`pre-data`, `data` or `post-data`) or all of it, restricted to the entries `list` keeps +/// ([`pg_restore_list`]'s format) when given. +pub(crate) async fn pg_restore_script( archive: &DumpFile, - section: &str, + section: Option<&str>, + 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(format!("--section={section}")) - .arg("--file") - .arg(&script.path); + cmd.arg("--file").arg(&script.path); + if let Some(section) = section { + cmd.arg(format!("--section={section}")); + } + if let Some(list) = list { + cmd.arg("--use-list").arg(list); + } if no_owner { cmd.arg("--no-owner"); } @@ -4194,6 +4220,7 @@ async fn create_pg_database( &req.target_dbname, "datatable", Some(&w_id), + &[], ) .await?; } else { @@ -4202,6 +4229,7 @@ async fn create_pg_database( &req.target_dbname, "datatable", Some(&w_id), + &[], ) .await?; } @@ -4441,15 +4469,10 @@ async fn import_pg_database( Some(client) => Some(crate::datatable_migrations::read_applied_migrations(&client).await?), None => None, }; - extensions - .restore( - &db, - dump, - &target_pg, - // The target was created by an earlier request and may have been written to since. - crate::datatable_extensions::ExtensionCreator::TargetRole, - ) - .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 6877b13226..855bde31c2 100644 --- a/backend/windmill-common/src/external_instance_pg.rs +++ b/backend/windmill-common/src/external_instance_pg.rs @@ -261,31 +261,8 @@ pub async fn external_instance_connection_unchecked( .await } -/// Run `sql` on `dbname` as the external cluster's admin login, for what `custom_instance_user` -/// may not do there itself, such as creating an extension only a superuser may create. -/// -/// Authorization: checks nothing. Callers MUST have authorized administering `dbname`: superadmin, -/// or making a fork copy they may fill. -pub async fn execute_as_external_instance_admin_unchecked( - db: &DB, - dbname: &str, - sql: &str, -) -> Result<()> { - crate::external_instance_pg_oss::with_external_instance_admin_unchecked( - db, - Some(dbname), - async |client| { - client - .batch_execute(sql) - .await - .map_err(|e| Error::BadRequest(crate::error::pg_error_message(&e))) - }, - ) - .await -} - /// 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. @@ -298,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, @@ -305,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 a343cd495b..f1683e13dd 100644 --- a/backend/windmill-common/src/external_instance_pg_oss.rs +++ b/backend/windmill-common/src/external_instance_pg_oss.rs @@ -21,7 +21,7 @@ pub fn external_instance_pg_unavailable() -> Error { pub(crate) use crate::external_instance_pg_ee::{ create_external_instance_database_unchecked, drop_external_instance_database_unchecked, external_instance_connection_unchecked, setup_external_instance_pg_unchecked, - validate_external_instance_pg_setting, with_external_instance_admin_unchecked, + validate_external_instance_pg_setting, }; #[cfg(all(feature = "private", feature = "enterprise"))] @@ -68,18 +68,11 @@ mod ce { _dbname: &str, _tag: &str, _for_workspace: Option<&str>, + _extensions: &[crate::DatabaseExtension], ) -> Result<()> { Err(unavailable()) } - pub(crate) async fn with_external_instance_admin_unchecked( - _db: &DB, - _dbname: Option<&str>, - _f: impl AsyncFnOnce(&tokio_postgres::Client) -> Result, - ) -> Result { - Err(unavailable()) - } - pub(crate) async fn drop_external_instance_database_unchecked( _tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, _dbname: &str, diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 84a509a5df..495bb5a9bd 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -2168,6 +2168,117 @@ 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, +} + +/// 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 an +/// extension goes in 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(); + let schemas: std::collections::BTreeSet<&str> = extensions + .iter() + .map(|e| e.schema.as_str()) + .filter(|s| *s != "public") + .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))?; + 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 +2298,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 +2334,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 +2377,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 +2385,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.",