diff --git a/backup/backup.go b/backup/backup.go index ddbcc197..2ab84bb1 100644 --- a/backup/backup.go +++ b/backup/backup.go @@ -49,27 +49,22 @@ func DoSetup() { utils.CheckGpexpandRunning(utils.BackupPreventedByGpexpandMessage) timestamp := history.CurrentTimestamp() createBackupLockFile(timestamp) - // Heap file hashes must be read before initializeConnectionPool takes the - // backup snapshot, and verified after it; see CollectHeapFileHashes. + // Collect heap hashes before the snapshot and verify them after it. var hashedHeapTables []heapTable if MustGetFlagBool(options.HEAP_FILE_HASH) && collectsIncrementalMetadata() { gplog.Info("Collecting heap table file hashes") hashedHeapTables, heapFileHashes = CollectHeapFileHashes(MustGetFlagString(options.DBNAME)) } initializeConnectionPool(timestamp) - if heapFileHashes != nil { - heapFileHashes = VerifyHeapFileHashes(MustGetFlagString(options.DBNAME), hashedHeapTables, heapFileHashes) - } gplog.Info("Apache Cloudberry Version = %s", connectionPool.Version.VersionString) gplog.Info("Starting backup of database %s", MustGetFlagString(options.DBNAME)) opts, err := options.NewOptions(cmdFlags) gplog.FatalOnError(err) - ValidateAndProcessFilterLists(opts) - includeOids := GetOidsFromRelationList(IncludedRelationFqns) - err = ExpandIncludesForPartitions(connectionPool, opts, includeOids, cmdFlags) - gplog.FatalOnError(err) + if connectionPool.Version.IsCBDB() && MustGetFlagString(options.PLUGIN_CONFIG) != "" { + ValidateAndProcessFilterLists(opts) + } clusterConfigConn := dbconn.NewDBConnFromEnvironment(MustGetFlagString(options.DBNAME)) clusterConfigConn.MustConnect(1) @@ -92,11 +87,29 @@ func DoSetup() { globalTOC = &toc.TOC{} globalTOC.InitializeMetadataEntryMap() utils.InitializePipeThroughParameters(!MustGetFlagBool(options.NO_COMPRESSION), MustGetFlagString(options.COMPRESSION_TYPE), MustGetFlagInt(options.COMPRESSION_LEVEL)) + // Signal cleanup needs globalFPInfo.Timestamp to cancel blocked sessions. + if connectionPool.Version.IsCBDB() { + setupBackupReportAndPlugin(timestamp, *opts) + gplog.FatalOnError(PrepareBackupSnapshot(opts)) + } else { + ValidateAndProcessFilterLists(opts) + includeOids := GetOidsFromRelationList(IncludedRelationFqns) + gplog.FatalOnError(ExpandIncludesForPartitions(connectionPool, opts, includeOids, cmdFlags)) + } + if heapFileHashes != nil { + heapFileHashes = VerifyHeapFileHashes(MustGetFlagString(options.DBNAME), hashedHeapTables, heapFileHashes) + } getQuotedRoleNames(connectionPool) + if !connectionPool.Version.IsCBDB() { + setupBackupReportAndPlugin(timestamp, *opts) + } +} +func setupBackupReportAndPlugin(timestamp string, opts options.Options) { pluginConfigFlag := MustGetFlagString(options.PLUGIN_CONFIG) if pluginConfigFlag != "" { + var err error pluginConfig, err = utils.ReadPluginConfig(pluginConfigFlag) gplog.FatalOnError(err) configFilename := path.Base(pluginConfig.ConfigPath) @@ -106,7 +119,7 @@ func DoSetup() { gplog.Debug("Plugin config path: %s", pluginConfig.ConfigPath) } - initializeBackupReport(*opts) + initializeBackupReport(opts) if pluginConfigFlag != "" { backupReport.PluginVersion = pluginConfig.CheckPluginExistsOnAllHosts(globalCluster) @@ -523,7 +536,7 @@ func DoCleanup(backupFailed bool) { // panics, there should be no way for gpbackup to exit that leaves the entry in the initial status. historyUpdated := false - if !MustGetFlagBool(options.NO_HISTORY) { + if backupReport != nil && !MustGetFlagBool(options.NO_HISTORY) { var statusString string if backupFailed { statusString = history.BackupStatusFailed diff --git a/backup/data.go b/backup/data.go index 4ffb5172..e6323588 100644 --- a/backup/data.go +++ b/backup/data.go @@ -94,7 +94,16 @@ func CopyTableOut(connectionPool *dbconn.DBConn, table Table, destinationToWrite if gplog.GetVerbosity() >= gplog.LOGVERBOSE { workerInfo = fmt.Sprintf("Worker %d: ", connNum) } - query := fmt.Sprintf("COPY %s%s TO %s WITH CSV DELIMITER '%s' ON SEGMENT IGNORE EXTERNAL PARTITIONS;", table.FQN(), columnNames, copyCommand, tableDelim) + source := table.FQN() + columnNames + if table.snapshotLeafOIDs != "" { + columns := "*" + if columnNames != "" { + columns = columnNames[1 : len(columnNames)-1] + } + // Keep the root's access checks and row policies while excluding later attachments. + source = fmt.Sprintf("(SELECT %s FROM %s WHERE tableoid = ANY ('%s'::pg_catalog.oid[]))", columns, table.FQN(), table.snapshotLeafOIDs) + } + query := fmt.Sprintf("COPY %s TO %s WITH CSV DELIMITER '%s' ON SEGMENT IGNORE EXTERNAL PARTITIONS;", source, copyCommand, tableDelim) if (connectionPool.Version.IsGPDB() && connectionPool.Version.AtLeast("7")) || connectionPool.Version.IsCBDB() { utils.LogProgress(`%sExecuting "%s" on coordinator`, workerInfo, query) } else { diff --git a/backup/queries_incremental.go b/backup/queries_incremental.go index a484bb1a..e4708cf1 100644 --- a/backup/queries_incremental.go +++ b/backup/queries_incremental.go @@ -400,7 +400,7 @@ BEGIN IF v_segno = 0 THEN v_path := v_base; ELSE - v_path := v_base || '.' || v_segno; + v_path := v_base || '.' || v_segno::text; END IF; BEGIN @@ -412,7 +412,7 @@ BEGIN IF v_mod >= v_now THEN RETURN ''; END IF; - v_result := v_result || ';' || v_segno || ':' || v_mod::text || '|' || v_size; + v_result := v_result || ';' || v_segno::text || ':' || v_mod::text || '|' || v_size::text; v_segno := v_segno + 1; END LOOP; @@ -649,11 +649,11 @@ func getHeapColumnHashes(connectionPool *dbconn.DBConn) (map[uint32]string, erro FROM column_types ct JOIN type_deps d ON d.typid = ct.typid ), type_defs(typid, def) AS ( - SELECT enumtypid, 'e' || enumtypid::text || ':' || enumsortorder || ':' || enumlabel + SELECT enumtypid, 'e' || enumtypid::text || ':' || enumsortorder::text || ':' || enumlabel::text FROM pg_enum UNION ALL - SELECT t.oid, 'c' || t.oid::text || ':' || ta.attnum || ':' || ta.attname || ':' || ta.atttypid - || ':' || ta.atttypmod || ':' || ta.attisdropped + SELECT t.oid, 'c' || t.oid::text || ':' || ta.attnum::text || ':' || ta.attname::text || ':' || ta.atttypid::text + || ':' || ta.atttypmod::text || ':' || ta.attisdropped::text FROM pg_type t JOIN pg_attribute ta ON ta.attrelid = t.typrelid WHERE t.typtype = 'c' AND ta.attnum > 0 @@ -675,8 +675,8 @@ func getHeapColumnHashes(connectionPool *dbconn.DBConn) (map[uint32]string, erro FROM column_types ct JOIN type_defs td ON td.typid = ct.typid UNION ALL - SELECT ca.attrelid, 'a' || ca.attnum::text || ':' || ca.attname || ':' || ca.atttypid - || ':' || ca.atttypmod || ':' || ca.attisdropped + SELECT ca.attrelid, 'a' || ca.attnum::text || ':' || ca.attname::text || ':' || ca.atttypid::text + || ':' || ca.atttypmod::text || ':' || ca.attisdropped::text FROM pg_attribute ca WHERE ca.attnum > 0 AND ca.attrelid IN (SELECT relid FROM column_types) diff --git a/backup/queries_relations.go b/backup/queries_relations.go index 6bc297fb..47e3a65f 100644 --- a/backup/queries_relations.go +++ b/backup/queries_relations.go @@ -550,11 +550,12 @@ func GetAllViews(connectionPool *dbconn.DBConn) []View { // dumping part but it also makes the main worker thread (worker 0) the // most resilient for the later data dumping logic. Locks will still be // taken for --data-only calls. -func LockTables(connectionPool *dbconn.DBConn, tables []Relation) { +func LockTables(connectionPool *dbconn.DBConn, tables []Relation) error { gplog.Info("Acquiring ACCESS SHARE locks on tables") progressBar := utils.NewProgressBar(len(tables), "Locks acquired: ", utils.PB_VERBOSE) progressBar.Start() + defer progressBar.Finish() var lockMode string const batchSize = 100 lastBatchSize := len(tables) % batchSize @@ -573,18 +574,13 @@ func LockTables(connectionPool *dbconn.DBConn, tables []Relation) { } else { lockMode = `IN ACCESS SHARE MODE` } - // The LOCK TABLE query could block if someone else is holding an - // AccessExclusiveLock on the table. In the case gpbackup is interrupted, - // cancelBlockedQueries() will cancel these queries during cleanup. for i, currentBatch := range tableBatches { - _, err := connectionPool.Exec(fmt.Sprintf("LOCK TABLE %s %s", currentBatch, lockMode)) - if err != nil { + if _, err := connectionPool.Exec(fmt.Sprintf("LOCK TABLE %s %s", currentBatch, lockMode)); err != nil { if wasTerminated { gplog.Warn("Interrupt received while acquiring ACCESS SHARE locks on tables") - select {} // wait for cleanup thread to exit gpbackup - } else { - gplog.FatalOnError(err) + select {} // Wait for signal cleanup to exit gpbackup. } + return fmt.Errorf("locking tables %s: %w", currentBatch, err) } if i == len(tableBatches)-1 && lastBatchSize > 0 { currentBatchSize = lastBatchSize @@ -592,7 +588,7 @@ func LockTables(connectionPool *dbconn.DBConn, tables []Relation) { progressBar.Add(currentBatchSize) } - progressBar.Finish() + return nil } // GenerateTableBatches batches tables to reduce network congestion and diff --git a/backup/queries_table_defs.go b/backup/queries_table_defs.go index 3cb5d9f9..4ac5d000 100644 --- a/backup/queries_table_defs.go +++ b/backup/queries_table_defs.go @@ -20,6 +20,7 @@ import ( type Table struct { Relation TableDefinition + snapshotLeafOIDs string } func (t Table) SkipDataBackup() bool { @@ -140,7 +141,7 @@ func ConstructDefinitionsForTables(connectionPool *dbconn.DBConn, tableRelations if tableDef.Inherits == nil { tableDef.Inherits = []string{} } - tables = append(tables, Table{tableRel, tableDef}) + tables = append(tables, Table{Relation: tableRel, TableDefinition: tableDef}) } return tables } diff --git a/backup/snapshot.go b/backup/snapshot.go index 145954f7..c3721670 100644 --- a/backup/snapshot.go +++ b/backup/snapshot.go @@ -1,16 +1,179 @@ package backup -/* - * This file contains functions related to use of synchronized database snapshots. - */ - import ( + "errors" "fmt" + "sort" + "strconv" + "strings" + "github.com/apache/cloudberry-backup/options" "github.com/apache/cloudberry-go-libs/dbconn" "github.com/apache/cloudberry-go-libs/gplog" + "github.com/jackc/pgx/v5/pgconn" ) +// CheckSnapshotTableLocks finds relations in the backup snapshot without a +// lock, including descendants read through a parent. +func CheckSnapshotTableLocks(conn *dbconn.DBConn, tables []Relation) ([]string, error) { + if len(tables) == 0 { + return nil, nil + } + conflicts := make(map[string]bool) + const batchSize = 1000 + for start := 0; start < len(tables); start += batchSize { + end := start + batchSize + if end > len(tables) { + end = len(tables) + } + oids := make([]string, end-start) + for i, table := range tables[start:end] { + oids[i] = strconv.FormatUint(uint64(table.Oid), 10) + } + query := fmt.Sprintf(`WITH RECURSIVE relations(oid) AS ( + SELECT oid FROM pg_catalog.pg_class WHERE oid IN (%s) + UNION + SELECT i.inhrelid FROM pg_catalog.pg_inherits i JOIN relations r ON i.inhparent = r.oid + ) + SELECT quote_ident(n.nspname) || '.' || quote_ident(c.relname) AS fqn + FROM relations r JOIN pg_catalog.pg_class c ON c.oid = r.oid + JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE NOT EXISTS ( + SELECT 1 FROM pg_catalog.pg_locks l + WHERE l.locktype = 'relation' AND l.relation = c.oid + AND l.database = (SELECT oid FROM pg_catalog.pg_database WHERE datname = current_database()) + AND l.pid = pg_catalog.pg_backend_pid() + AND l.mode = 'AccessShareLock' AND l.granted + )`, strings.Join(oids, ",")) + var rows []struct{ FQN string } + if err := conn.Select(&rows, query); err != nil { + return nil, fmt.Errorf("checking backup table locks: %w", err) + } + for _, row := range rows { + conflicts[row.FQN] = true + } + } + result := make([]string, 0, len(conflicts)) + for conflict := range conflicts { + result = append(result, conflict) + } + sort.Strings(result) + return result, nil +} + +// collectSnapshotPartitionLeaves reads the partition tree from the backup snapshot. +func collectSnapshotPartitionLeaves(conn *dbconn.DBConn, tables []Table) error { + roots := make(map[uint32]int) + var oids []string + for i, table := range tables { + if table.PartitionLevelInfo.Level == "p" { + roots[table.Oid] = i + oids = append(oids, strconv.FormatUint(uint64(table.Oid), 10)) + } + } + if len(oids) == 0 { + return nil + } + + const query = `WITH RECURSIVE partitions(root, oid, relkind) AS ( + SELECT oid, oid, relkind FROM pg_catalog.pg_class + WHERE oid = ANY($1::oid[]) + UNION ALL + SELECT p.root, c.oid, c.relkind FROM partitions p + JOIN pg_catalog.pg_inherits i ON i.inhparent = p.oid + JOIN pg_catalog.pg_class c ON c.oid = i.inhrelid + WHERE p.relkind = 'p' AND NOT i.inhdetachpending + ) + SELECT root, COALESCE(array_agg(oid ORDER BY oid) FILTER (WHERE relkind <> 'p'), '{}'::oid[])::text AS leaves + FROM partitions GROUP BY root` + var partitions []struct { + Root uint32 + Leaves string + } + if err := conn.SelectWithArgs(&partitions, query, "{"+strings.Join(oids, ",")+"}"); err != nil { + return fmt.Errorf("reading partition leaves from the backup snapshot: %w", err) + } + for _, partition := range partitions { + tables[roots[partition.Root]].snapshotLeafOIDs = partition.Leaves + } + return nil +} + +// PrepareBackupSnapshot locks Cloudberry tables before exporting the shared +// snapshot. The connection pool must have no open transactions on entry. +func PrepareBackupSnapshot(opts *options.Options) error { + maxAttempts := MustGetFlagInt(options.SNAPSHOT_ATTEMPTS) + for attempt := 1; attempt <= maxAttempts; attempt++ { + if err := resolveSnapshotFilters(opts); err != nil { + return err + } + tables := ConvertRelationsOptionsToBackup(GetIncludedUserTableRelations(connectionPool, IncludedRelationFqns)) + // A SELECT before LOCK would establish the transaction snapshot too early. + if err := connectionPool.Begin(0); err != nil { + return err + } + lockErr := LockTables(connectionPool, tables) + var conflicts []string + if lockErr != nil { + var pgErr *pgconn.PgError + if !errors.As(lockErr, &pgErr) || (pgErr.Code != "42P01" && pgErr.Code != "3F000") { + return lockErr + } + conflicts = []string{lockErr.Error()} + } else { + var err error + backupSnapshot, err = GetSynchronizedSnapshot(connectionPool) + if err != nil { + return err + } + if err = resolveSnapshotFilters(opts); err != nil { + return err + } + tables = ConvertRelationsOptionsToBackup(GetIncludedUserTableRelations(connectionPool, IncludedRelationFqns)) + // Locking new tables here would reopen the concurrent TRUNCATE race. + conflicts, err = CheckSnapshotTableLocks(connectionPool, tables) + if err != nil { + return err + } + } + if len(conflicts) == 0 { + for connNum := 1; connNum < connectionPool.NumConns; connNum++ { + if err := SetSynchronizedSnapshot(connectionPool, connNum, backupSnapshot); err != nil { + return err + } + } + return nil + } + if err := connectionPool.Rollback(0); err != nil { + return fmt.Errorf("rolling back backup snapshot preparation: %w", err) + } + backupSnapshot = "" + details := snapshotConflictSummary(conflicts) + if attempt >= maxAttempts { + return fmt.Errorf("could not lock the backup table set before taking a snapshot after %d attempt(s): %s", attempt, details) + } + gplog.Warn("Backup table set changed: %s. Starting snapshot attempt %d of %d", details, attempt+1, maxAttempts) + } + return fmt.Errorf("snapshot preparation requires at least one attempt") +} + +func resolveSnapshotFilters(opts *options.Options) error { + if err := opts.ResetTableFilters(cmdFlags); err != nil { + return err + } + filterRelationClause = "" + ValidateAndProcessFilterLists(opts) + return ExpandIncludesForPartitions(connectionPool, opts, GetOidsFromRelationList(IncludedRelationFqns), cmdFlags) +} + +func snapshotConflictSummary(conflicts []string) string { + const limit = 10 + if len(conflicts) > limit { + return fmt.Sprintf("%s; and %d more", strings.Join(conflicts[:limit], "; "), len(conflicts)-limit) + } + return strings.Join(conflicts, "; ") +} + const ( SNAPSHOT_GPDB_MIN_VERSION = "6.21.0" ) diff --git a/backup/snapshot_internal_test.go b/backup/snapshot_internal_test.go new file mode 100644 index 00000000..7e824dbc --- /dev/null +++ b/backup/snapshot_internal_test.go @@ -0,0 +1,214 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +package backup + +import ( + "errors" + "fmt" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/apache/cloudberry-backup/options" + "github.com/apache/cloudberry-go-libs/dbconn" + "github.com/apache/cloudberry-go-libs/testhelper" + "github.com/jackc/pgx/v5/pgconn" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/spf13/pflag" +) + +var _ = Describe("snapshot preparation", func() { + var mock sqlmock.Sqlmock + var opts *options.Options + table := Relation{Oid: 10, Schema: "public", Name: "t"} + BeforeEach(func() { + connectionPool, mock, _, _, _ = testhelper.SetupTestEnvironment() + connectionPool.Version = dbconn.NewVersion("2.999.0") + connectionPool.Version.Type = dbconn.CBDB + SetCmdFlags(pflag.NewFlagSet("snapshot", pflag.ContinueOnError)) + var err error + opts, err = options.NewOptions(cmdFlags) + Expect(err).NotTo(HaveOccurred()) + filterRelationClause = "" + IncludedRelationFqns = nil + ExcludedRelationFqns = nil + heapFileHashes = nil + backupSnapshot = "" + }) + AfterEach(func() { + Expect(mock.ExpectationsWereMet()).To(Succeed()) + connectionPool.Close() + backupSnapshot = "" + heapFileHashes = nil + }) + + check := func(missing ...string) { + rows := sqlmock.NewRows([]string{"fqn"}) + for _, name := range missing { + rows.AddRow(name) + } + mock.ExpectQuery("WITH RECURSIVE.*").WillReturnRows(rows) + } + It("accepts tables and descendants already locked before the snapshot", func() { + check() + conflicts, err := CheckSnapshotTableLocks(connectionPool, []Relation{table}) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(BeEmpty()) + }) + It("does not query for an empty table set", func() { + conflicts, err := CheckSnapshotTableLocks(connectionPool, nil) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(BeEmpty()) + }) + It("deduplicates missing descendants across bounded OID batches", func() { + tables := make([]Relation, 1001) + for i := range tables { + tables[i] = Relation{Oid: uint32(i + 10)} + } + check("public.leaf", "public.leaf") + check("public.leaf", "public.other") + conflicts, err := CheckSnapshotTableLocks(connectionPool, tables) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(Equal([]string{"public.leaf", "public.other"})) + }) + It("fails closed on a lock validation error", func() { + mock.ExpectQuery("WITH RECURSIVE").WillReturnError(errors.New("catalog failure")) + _, err := CheckSnapshotTableLocks(connectionPool, []Relation{table}) + Expect(err).To(MatchError(ContainSubstring("catalog failure"))) + }) + It("bounds conflict diagnostics", func() { + names := make([]string, 12) + for i := range names { + names[i] = fmt.Sprintf("t%d", i) + } + summary := snapshotConflictSummary(names) + Expect(summary).To(ContainSubstring("t9; and 2 more")) + Expect(summary).NotTo(ContainSubstring("t10")) + }) + + begin := func() { + mock.ExpectBegin() + mock.ExpectExec("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE").WillReturnResult(sqlmock.NewResult(0, 0)) + } + session := func() { + for _, query := range []string{"SET search_path", "SET statement_timeout", "SET DATESTYLE", "SET enable_mergejoin", "SELECT set_config", "SET synchronize_seqscans", "SET INTERVALSTYLE", "SET lock_timeout", "SET idle_in_transaction_session_timeout"} { + mock.ExpectExec(query).WillReturnResult(sqlmock.NewResult(0, 0)) + } + } + tables := func() { + mock.ExpectQuery("SELECT n.oid AS schemaoid").WillReturnRows(sqlmock.NewRows([]string{"schemaoid", "oid", "schema", "name"}).AddRow(1, 10, "public", "t")) + } + lock := func(err error) { + tables() + begin() + expectation := mock.ExpectExec("LOCK TABLE public.t") + if err != nil { + expectation.WillReturnError(err) + } else { + expectation.WillReturnResult(sqlmock.NewResult(0, 0)) + } + } + snapshot := func() { + mock.ExpectQuery("SELECT pg_catalog.pg_export_snapshot").WillReturnRows(sqlmock.NewRows([]string{"snapshot"}).AddRow("new-snapshot")) + tables() + } + twoConnections := func() { + connectionPool.ConnPool[0].SetMaxOpenConns(2) + connectionPool.ConnPool = append(connectionPool.ConnPool, connectionPool.ConnPool[0]) + connectionPool.Tx = append(connectionPool.Tx, nil) + connectionPool.NumConns = 2 + } + It("sets session GUCs before beginning any Cloudberry backup transaction", func() { + twoConnections() + for i := 0; i < 2; i++ { + mock.ExpectExec("SET application_name").WillReturnResult(sqlmock.NewResult(0, 0)) + session() + } + Expect(initializeBackupTransactions("20261124000000")).To(Succeed()) + Expect(connectionPool.Tx[0]).To(BeNil()) + Expect(connectionPool.Tx[1]).To(BeNil()) + Expect(backupSnapshot).To(BeEmpty()) + }) + It("locks before exporting and imports workers only after validating the final table set", func() { + twoConnections() + lock(nil) + snapshot() + check() + begin() + mock.ExpectExec("SET TRANSACTION SNAPSHOT 'new-snapshot'").WillReturnResult(sqlmock.NewResult(0, 0)) + Expect(PrepareBackupSnapshot(opts)).To(Succeed()) + Expect(backupSnapshot).To(Equal("new-snapshot")) + }) + DescribeTable("honors the attempt budget for unprotected tables", func(limit int) { + Expect(cmdFlags.Set(options.SNAPSHOT_ATTEMPTS, fmt.Sprint(limit))).To(Succeed()) + for i := 0; i < limit; i++ { + lock(nil) + snapshot() + check("public.new_leaf") + mock.ExpectRollback() + } + err := PrepareBackupSnapshot(opts) + Expect(err).To(MatchError(ContainSubstring(fmt.Sprintf("after %d attempt(s): public.new_leaf", limit)))) + Expect(backupSnapshot).To(BeEmpty()) + }, Entry("one", 1), Entry("three", 3)) + It("keeps heap hashes until they can be verified against the final snapshot", func() { + heapFileHashes = map[uint32]string{10: "hash"} + lock(nil) + snapshot() + check("public.new_leaf") + mock.ExpectRollback() + lock(nil) + snapshot() + check() + Expect(PrepareBackupSnapshot(opts)).To(Succeed()) + Expect(heapFileHashes).To(Equal(map[uint32]string{10: "hash"})) + }) + DescribeTable("retries missing names", func(code string) { + lock(&pgconn.PgError{Code: code, Message: "disappeared"}) + mock.ExpectRollback() + lock(nil) + snapshot() + check() + Expect(PrepareBackupSnapshot(opts)).To(Succeed()) + }, Entry("table", "42P01"), Entry("schema", "3F000")) + It("does not retry unrelated SQL errors", func() { + lock(&pgconn.PgError{Code: "42501", Message: "permission denied"}) + Expect(PrepareBackupSnapshot(opts)).To(MatchError(ContainSubstring("permission denied"))) + }) + It("does not import workers after a snapshot export failure", func() { + twoConnections() + lock(nil) + mock.ExpectQuery("SELECT pg_catalog.pg_export_snapshot").WillReturnError(errors.New("export failed")) + Expect(PrepareBackupSnapshot(opts)).To(MatchError("export failed")) + Expect(connectionPool.Tx[1]).To(BeNil()) + }) + It("stops on a lock validation query failure", func() { + lock(nil) + snapshot() + mock.ExpectQuery("WITH RECURSIVE").WillReturnError(errors.New("check failed")) + Expect(PrepareBackupSnapshot(opts)).To(MatchError(ContainSubstring("check failed"))) + }) + It("stops on rollback failure", func() { + lock(nil) + snapshot() + check("public.new_leaf") + mock.ExpectRollback().WillReturnError(errors.New("rollback failure")) + Expect(PrepareBackupSnapshot(opts)).To(MatchError(ContainSubstring("rollback failure"))) + }) +}) diff --git a/backup/validate.go b/backup/validate.go index a4f84229..70f5adc4 100644 --- a/backup/validate.go +++ b/backup/validate.go @@ -168,6 +168,9 @@ func validateFlagCombinations(flags *pflag.FlagSet) { } func validateFlagValues() { + if MustGetFlagInt(options.SNAPSHOT_ATTEMPTS) < 1 { + gplog.Fatal(errors.New("--snapshot-attempts must be an integer of at least 1"), "") + } timeoutSeconds := MustGetFlagInt(options.HISTORY_SYNC_STANDBY_TIMEOUT) if timeoutSeconds <= 0 || timeoutSeconds > maxHistorySyncStandbyTimeoutSeconds { gplog.Fatal(errors.Errorf("--%s must be between 1 and %d seconds", options.HISTORY_SYNC_STANDBY_TIMEOUT, maxHistorySyncStandbyTimeoutSeconds), "") diff --git a/backup/validate_test.go b/backup/validate_test.go index 82678257..2e4b0741 100644 --- a/backup/validate_test.go +++ b/backup/validate_test.go @@ -214,6 +214,10 @@ var _ = Describe("backup/validate tests", func() { Fail("Valid flag combination failed validation check") } }, + Entry("snapshot attempts accepts one", "--snapshot-attempts 1", true), + Entry("snapshot attempts accepts larger values", "--snapshot-attempts 5", true), + Entry("snapshot attempts rejects zero", "--snapshot-attempts 0", false), + Entry("snapshot attempts rejects negative values", "--snapshot-attempts -2", false), Entry("--backup-dir combo", "--backup-dir /tmp --plugin-config /tmp/config", false), Entry("standby history sync timeout must be positive", "--history-sync-standby-timeout 0", false), Entry("standby history sync timeout must not be negative", "--history-sync-standby-timeout -1", false), diff --git a/backup/wrappers.go b/backup/wrappers.go index 30e33096..0daa7c44 100644 --- a/backup/wrappers.go +++ b/backup/wrappers.go @@ -45,7 +45,6 @@ func SetLoggerVerbosity() { func initializeConnectionPool(timestamp string) { var numConns int - var err error connectionPool = dbconn.NewDBConnFromEnvironment(MustGetFlagString(options.DBNAME)) /* * The additional connection is used to hold the locks and process any deferred @@ -68,20 +67,36 @@ func initializeConnectionPool(timestamp string) { utils.ValidateGPDBVersionCompatibility(connectionPool) InitializeMetadataParams(connectionPool) - // Begin transactions, initialize the synchronized snapshot, and set session GUCs + gplog.FatalOnError(initializeBackupTransactions(timestamp)) +} + +// Set application_name outside transactions so cleanup can find sessions after rollback. +func initializeBackupTransactions(timestamp string) error { + backupSnapshot = "" for connNum := 0; connNum < connectionPool.NumConns; connNum++ { - connectionPool.MustExec(fmt.Sprintf("SET application_name TO 'gpbackup_%s'", timestamp), connNum) - // Begins transaction in repeatable read - connectionPool.MustBegin(connNum) - if ((connectionPool.Version.IsGPDB() && connectionPool.Version.AtLeast(SNAPSHOT_GPDB_MIN_VERSION)) || connectionPool.Version.IsCBDB()) && backupSnapshot == "" { - backupSnapshot, err = GetSynchronizedSnapshot(connectionPool) - if err != nil { - gplog.FatalOnError(err) + if _, err := connectionPool.Exec(fmt.Sprintf("SET application_name TO 'gpbackup_%s'", timestamp), connNum); err != nil { + return err + } + if connectionPool.Version.IsCBDB() { + // SetSessionGUCs runs a SELECT that would establish the snapshot. + SetSessionGUCs(connNum) + continue + } + if err := connectionPool.Begin(connNum); err != nil { + return err + } + if connectionPool.Version.IsGPDB() && connectionPool.Version.AtLeast(SNAPSHOT_GPDB_MIN_VERSION) { + if connNum == 0 { + var err error + backupSnapshot, err = GetSynchronizedSnapshot(connectionPool) + if err != nil { + return err + } } } - SetSessionGUCs(connNum) } + return nil } func SetSessionGUCs(connNum int) { @@ -204,10 +219,11 @@ func createBackupDirectoriesOnAllHosts() { */ func RetrieveAndProcessTables() ([]Table, []Table) { - includedRelations := GetIncludedUserTableRelations(connectionPool, IncludedRelationFqns) - tableRelations := ConvertRelationsOptionsToBackup(includedRelations) - - LockTables(connectionPool, tableRelations) + tableRelations := ConvertRelationsOptionsToBackup(GetIncludedUserTableRelations(connectionPool, IncludedRelationFqns)) + // PrepareBackupSnapshot already holds these locks on Cloudberry. + if !connectionPool.Version.IsCBDB() { + gplog.FatalOnError(LockTables(connectionPool, tableRelations)) + } if (connectionPool.Version.IsGPDB() && connectionPool.Version.AtLeast("6")) || connectionPool.Version.IsCBDB() { tableRelations = append(tableRelations, GetForeignTableRelations(connectionPool)...) @@ -216,6 +232,9 @@ func RetrieveAndProcessTables() ([]Table, []Table) { tables := ConstructDefinitionsForTables(connectionPool, tableRelations) metadataTables, dataTables := SplitTablesByPartitionType(tables, IncludedRelationFqns) + if connectionPool.Version.IsCBDB() && !MustGetFlagBool(options.METADATA_ONLY) && !MustGetFlagBool(options.LEAF_PARTITION_DATA) { + gplog.FatalOnError(collectSnapshotPartitionLeaves(connectionPool, dataTables)) + } objectCounts["Tables"] = len(metadataTables) return metadataTables, dataTables diff --git a/end_to_end/locks_test.go b/end_to_end/locks_test.go index 046a5730..c80f8d56 100644 --- a/end_to_end/locks_test.go +++ b/end_to_end/locks_test.go @@ -178,7 +178,7 @@ var _ = Describe("Deadlock handling", func() { // Only the main worker thread, worker 0, will run COPY on all the test tables for _, dataTable := range dataTables { - expectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Executing "COPY %s`, dataTable) + expectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Writing data for table %s to file`, dataTable) Expect(stdout).To(ContainSubstring(expectedString)) } @@ -346,7 +346,7 @@ var _ = Describe("Deadlock handling", func() { // Only the main worker thread, worker 0, will run COPY on all the test tables for _, dataTable := range dataTables { - expectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Executing "COPY %s`, dataTable) + expectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Writing data for table %s to file`, dataTable) Expect(stdout).To(ContainSubstring(expectedString)) } @@ -507,11 +507,11 @@ var _ = Describe("Deadlock handling", func() { // Only the main worker thread, worker 0, will run COPY on the 2 locked test tables for _, lockedTable := range lockedTables { - expectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Executing "COPY %s`, lockedTable) + expectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Writing data for table %s to file`, lockedTable) Expect(stdout).To(ContainSubstring(expectedString)) } for _, dataTable := range dataTables { - unexpectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Executing "COPY %s`, dataTable) + unexpectedString := fmt.Sprintf(`[DEBUG]:-Worker 0: Writing data for table %s to file`, dataTable) Expect(stdout).ToNot(ContainSubstring(unexpectedString)) } Expect(stdout).To(ContainSubstring("Backup completed successfully")) diff --git a/end_to_end/snapshot_retry_test.go b/end_to_end/snapshot_retry_test.go new file mode 100644 index 00000000..860328e3 --- /dev/null +++ b/end_to_end/snapshot_retry_test.go @@ -0,0 +1,431 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +package end_to_end_test + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "time" + + "github.com/apache/cloudberry-backup/history" + "github.com/apache/cloudberry-backup/testutils" + "github.com/apache/cloudberry-backup/toc" + "github.com/apache/cloudberry-go-libs/cluster" + "github.com/apache/cloudberry-go-libs/dbconn" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + . "github.com/onsi/gomega/gexec" + "gopkg.in/yaml.v2" +) + +// Wait for this backup's lock request, never a fixed sleep or another client's lock. +func waitForSnapshotBackupLock(relation string) { + query := fmt.Sprintf(`SELECT count(*) FROM pg_locks l JOIN pg_stat_activity a ON a.pid=l.pid + WHERE l.relation='%s'::regclass AND NOT l.granted AND l.mode='AccessShareLock' + AND a.datname=current_database() AND a.application_name LIKE 'gpbackup_%%'`, relation) + Eventually(func() (int, error) { var count int; err := backupConn.Get(&count, query); return count, err }, 30*time.Second, 100*time.Millisecond).Should(BeNumerically(">", 0)) +} + +func startSnapshotBackup(args ...string) *Session { + if !hasCommandArgument(args, "--plugin-config") { + args = append(args, "--backup-dir", backupDir) + } + args = append([]string{"--dbname", "testdb", "--verbose", "--no-history-sync-standby", "--snapshot-attempts", "1"}, args...) + session, err := Start(exec.Command(gpbackupPath, args...), GinkgoWriter, GinkgoWriter) + Expect(err).NotTo(HaveOccurred()) + DeferCleanup(func() { + if session.ExitCode() == -1 { + session.Terminate() + Eventually(session, 30*time.Second).Should(Exit()) + } + }) + return session +} + +func snapshotRetryRows(conn *dbconn.DBConn) []int { + var rows []int + Expect(conn.Select(&rows, "SELECT id FROM snapshot_retry.t ORDER BY id")).To(Succeed()) + return rows +} + +// Server backend removal from pg_stat_activity can lag the client process exit. +func waitForSnapshotBackupSessionsToClose() { + Eventually(func() (int, error) { + var count int + err := backupConn.Get(&count, "SELECT count(*) FROM pg_stat_activity WHERE datname=current_database() AND application_name LIKE 'gpbackup_%'") + return count, err + }, 10*time.Second, 100*time.Millisecond).Should(BeZero()) +} + +var _ = Describe("snapshot lock preparation", func() { + BeforeEach(func() { + if useOldBackupVersion || !backupConn.Version.IsCBDB() { + Skip("snapshot preparation requires Cloudberry and current gpbackup") + } + end_to_end_setup() + backupConn.MustExec("CREATE SCHEMA snapshot_retry") + }) + AfterEach(func() { + backupConn.MustExec("DROP SCHEMA IF EXISTS snapshot_retry CASCADE") + restoreConn.MustExec("DROP SCHEMA IF EXISTS snapshot_retry CASCADE") + end_to_end_teardown() + }) + + createTable := func(am string, partitioned bool) { + if partitioned { + backupConn.MustExec(fmt.Sprintf(`CREATE TABLE snapshot_retry.t(id int) USING %s DISTRIBUTED BY(id) PARTITION BY RANGE(id); + CREATE TABLE snapshot_retry.middle PARTITION OF snapshot_retry.t FOR VALUES FROM(0) TO(10) PARTITION BY RANGE(id); + CREATE TABLE snapshot_retry.leaf PARTITION OF snapshot_retry.middle FOR VALUES FROM(0) TO(10) USING %s`, am, am)) + } else { + backupConn.MustExec(fmt.Sprintf("CREATE TABLE snapshot_retry.t(id int) USING %s DISTRIBUTED BY(id)", am)) + } + backupConn.MustExec("INSERT INTO snapshot_retry.t VALUES(1),(2),(3)") + } + truncateDuringBackup := func(partitioned bool, args ...string) *Session { + writer := testutils.SetupTestDbConn("testdb") + defer writer.Close() + writer.MustBegin() + defer func() { + if writer.Tx[0] != nil { + writer.MustRollback() + } + }() + relation := "snapshot_retry.t" + if partitioned { + relation = "snapshot_retry.leaf" + } + writer.MustExec("TRUNCATE " + relation) + writer.MustExec("INSERT INTO " + relation + " VALUES(4),(5),(6)") + session := startSnapshotBackup(args...) + waitForSnapshotBackupLock(relation) + writer.MustCommit() + Eventually(session, 90*time.Second).Should(Exit()) + return session + } + restore := func(session *Session) { + Expect(session.ExitCode()).To(Equal(0)) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Starting snapshot attempt")) + ts := getBackupTimestamp(string(session.Out.Contents())) + gprestore(gprestorePath, restoreHelperPath, ts, "--backup-dir", backupDir, "--redirect-db", "restoredb") + Expect(snapshotRetryRows(backupConn)).To(Equal([]int{4, 5, 6})) + Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{4, 5, 6})) + } + for _, am := range []string{"heap", "ao_row", "ao_column", "pax"} { + for _, shape := range []string{"plain", "nested root data", "nested leaf data"} { + am, shape := am, shape + It(fmt.Sprintf("restores concurrent TRUNCATE for %s %s", am, shape), func() { + if am == "pax" && dbconn.MustSelectString(backupConn, "SELECT count(*) AS string FROM pg_am WHERE amname='pax'") == "0" { + Skip("PAX unavailable") + } + partitioned := shape != "plain" + createTable(am, partitioned) + args := []string{"--include-schema", "snapshot_retry", "--jobs", "2"} + if shape == "nested leaf data" { + args = append(args, "--leaf-partition-data") + } + restore(truncateDuringBackup(partitioned, args...)) + }) + } + } + It("restores with single data file and a table filter file", func() { + createTable("heap", true) + file, err := os.CreateTemp("", "snapshot-include") + Expect(err).NotTo(HaveOccurred()) + defer os.Remove(file.Name()) + _, err = file.WriteString("snapshot_retry.t\n") + Expect(err).NotTo(HaveOccurred()) + Expect(file.Close()).To(Succeed()) + restoreConn.MustExec("CREATE SCHEMA snapshot_retry") + restore(truncateDuringBackup(true, "--include-table-file", file.Name(), "--single-data-file", "--leaf-partition-data")) + }) + It("backs up a partitioned root with SELECT and applies its row policy", func() { + createTable("heap", true) + backupConn.MustExec("CREATE ROLE snapshot_retry_reader") + DeferCleanup(func() { + restoreConn.MustExec("DROP OWNED BY snapshot_retry_reader") + backupConn.MustExec("DROP OWNED BY snapshot_retry_reader; DROP ROLE snapshot_retry_reader") + }) + backupConn.MustExec(`GRANT USAGE ON SCHEMA snapshot_retry TO snapshot_retry_reader; + GRANT SELECT ON ALL TABLES IN SCHEMA snapshot_retry, pg_catalog TO snapshot_retry_reader; + GRANT pg_execute_server_program TO snapshot_retry_reader; + ALTER TABLE snapshot_retry.t ENABLE ROW LEVEL SECURITY; + CREATE POLICY root_read ON snapshot_retry.t FOR SELECT TO snapshot_retry_reader USING (id <> 2)`) + cmd := exec.Command(gpbackupPath, "--dbname", "testdb", "--include-table", "snapshot_retry.t", "--without-globals", + "--no-history", "--no-history-sync-standby", "--backup-dir", backupDir) + cmd.Env = append(os.Environ(), "PGOPTIONS="+strings.TrimSpace(os.Getenv("PGOPTIONS")+" -c role=snapshot_retry_reader")) + output, err := cmd.CombinedOutput() + Expect(err).NotTo(HaveOccurred(), "%s", output) + + restoreConn.MustExec("CREATE SCHEMA snapshot_retry") + gprestore(gprestorePath, restoreHelperPath, getBackupTimestamp(string(output)), "--redirect-db", "restoredb", "--backup-dir", backupDir) + Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{1, 3})) + }) + + It("writes a failure report when snapshot preparation runs out of attempts", func() { + createTable("heap", false) + writer := testutils.SetupTestDbConn("testdb") + defer writer.Close() + writer.MustBegin() + defer func() { + if writer.Tx[0] != nil { + writer.MustRollback() + } + }() + writer.MustExec("LOCK TABLE snapshot_retry.t IN ACCESS EXCLUSIVE MODE") + session := startSnapshotBackup("--include-schema", "snapshot_retry") + waitForSnapshotBackupLock("snapshot_retry.t") + backupConn.MustExec("CREATE TABLE snapshot_retry.added(id int) DISTRIBUTED BY(id)") + writer.MustCommit() + + Eventually(session, 90*time.Second).Should(Exit(2)) + Expect(string(session.Out.Contents())).To(ContainSubstring("after 1 attempt(s): snapshot_retry.added")) + reports, err := filepath.Glob(filepath.Join(backupDir, "*-1", "backups", "*", "*", "*_report")) + Expect(err).NotTo(HaveOccurred()) + Expect(reports).To(HaveLen(1)) + contents, err := os.ReadFile(reports[0]) + Expect(err).NotTo(HaveOccurred()) + Expect(string(contents)).To(ContainSubstring("backup status:")) + Expect(string(contents)).To(ContainSubstring("Failure")) + Expect(string(contents)).To(ContainSubstring("after 1 attempt(s): snapshot_retry.added")) + contents, err = os.ReadFile(strings.TrimSuffix(reports[0], "_report") + "_config.yaml") + Expect(err).NotTo(HaveOccurred()) + var config history.BackupConfig + Expect(yaml.Unmarshal(contents, &config)).To(Succeed()) + Expect(config.Status).To(Equal(history.BackupStatusFailed)) + }) + + It("validates table filters before plugin setup and takes the snapshot afterward", func() { + createTable("heap", false) + pluginPath := filepath.Join(backupDir, "snapshot-plugin.bash") + pluginConfig := filepath.Join(backupDir, "snapshot-plugin.yaml") + setupMarker := filepath.Join(backupDir, "snapshot-plugin-started") + plugin, err := os.ReadFile(examplePluginExec) + Expect(err).NotTo(HaveOccurred()) + setup := fmt.Sprintf(`setup_plugin_for_backup(){ + if [[ "$3" == "coordinator" || "$3" == "master" ]]; then + touch %q + PGOPTIONS="${PGOPTIONS:-} -c lock_timeout=5000" psql -X -v ON_ERROR_STOP=1 -d testdb \ + -c 'VACUUM FULL snapshot_retry.t' -c 'INSERT INTO snapshot_retry.t VALUES (4)' + fi`, setupMarker) + Expect(os.WriteFile(pluginPath, []byte(strings.Replace(string(plugin), "setup_plugin_for_backup(){", setup, 1)), 0755)).To(Succeed()) + Expect(os.WriteFile(pluginConfig, []byte(fmt.Sprintf("executablepath: %s\noptions:\n password: unknown\n", pluginPath)), 0600)).To(Succeed()) + copyPluginToAllHosts(backupConn, pluginPath) + + invalid := startSnapshotBackup("--include-table", "snapshot_retry.absent", "--plugin-config", pluginConfig) + Eventually(invalid, 90*time.Second).Should(Exit(2)) + Expect(string(invalid.Out.Contents())).To(ContainSubstring("Table snapshot_retry.absent does not exist")) + Expect(setupMarker).NotTo(BeAnExistingFile()) + + session := startSnapshotBackup("--include-table", "snapshot_retry.t", "--plugin-config", pluginConfig) + Eventually(session, 90*time.Second).Should(Exit(0)) + Expect(setupMarker).To(BeAnExistingFile()) + ts := getBackupTimestamp(string(session.Out.Contents())) + restoreConn.MustExec("CREATE SCHEMA snapshot_retry") + gprestore(gprestorePath, restoreHelperPath, ts, "--redirect-db", "restoredb", "--plugin-config", pluginConfig) + Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{1, 2, 3, 4})) + }) + + DescribeTable("preserves the root copy when ATTACH starts after the backup snapshot", func(nested, empty bool) { + backupConn.MustExec("CREATE TABLE snapshot_retry.t(id int) DISTRIBUTED BY(id) PARTITION BY RANGE(id)") + parent := "snapshot_retry.t" + if nested { + backupConn.MustExec(`CREATE TABLE snapshot_retry.middle PARTITION OF snapshot_retry.t + FOR VALUES FROM (0) TO (100) PARTITION BY RANGE(id)`) + parent = "snapshot_retry.middle" + } + var expectedRows []int + if !empty { + backupConn.MustExec(fmt.Sprintf(`CREATE TABLE snapshot_retry.leaf PARTITION OF %s FOR VALUES FROM (0) TO (10); + INSERT INTO snapshot_retry.t VALUES (1),(2),(3)`, parent)) + expectedRows = []int{1, 2, 3} + } + backupConn.MustExec(`CREATE TABLE snapshot_retry.new_leaf(id int) DISTRIBUTED BY(id); + INSERT INTO snapshot_retry.new_leaf VALUES (11),(12),(13)`) + + gate := testutils.SetupTestDbConn("testdb") + defer gate.Close() + gate.MustBegin() + defer func() { + if gate.Tx[0] != nil { + gate.MustRollback() + } + }() + gate.MustExec("LOCK TABLE pg_catalog.pg_description IN ACCESS EXCLUSIVE MODE") + session := startSnapshotBackup("--include-table", "snapshot_retry.t", "--jobs", "2") + waitForSnapshotBackupLock("pg_catalog.pg_description") + + writer := testutils.SetupTestDbConn("testdb") + defer writer.Close() + writer.MustExec("SET lock_timeout = '5s'") + writer.MustExec(fmt.Sprintf("ALTER TABLE %s ATTACH PARTITION snapshot_retry.new_leaf FOR VALUES FROM (10) TO (20)", parent)) + gate.MustCommit() + Eventually(session, 90*time.Second).Should(Exit(0)) + + ts := getBackupTimestamp(string(session.Out.Contents())) + restoreConn.MustExec("CREATE SCHEMA snapshot_retry") + gprestore(gprestorePath, restoreHelperPath, ts, "--redirect-db", "restoredb", "--backup-dir", backupDir) + Expect(snapshotRetryRows(restoreConn)).To(Equal(expectedRows)) + Expect(snapshotRetryRows(backupConn)).To(Equal(append(expectedRows, 11, 12, 13))) + }, Entry("on the root", false, false), Entry("on a subparent", true, false), Entry("on an empty root", false, true)) + It("does not deadlock when another exclusive lock queues behind the backup", func() { + createTable("heap", false) + first := testutils.SetupTestDbConn("testdb") + defer first.Close() + first.MustBegin() + defer func() { + if first.Tx[0] != nil { + first.MustRollback() + } + }() + first.MustExec("TRUNCATE snapshot_retry.t; INSERT INTO snapshot_retry.t VALUES(4),(5),(6)") + session := startSnapshotBackup("--include-schema", "snapshot_retry", "--jobs", "2") + waitForSnapshotBackupLock("snapshot_retry.t") + second := testutils.SetupTestDbConn("testdb") + defer second.Close() + var pid int + Expect(second.Get(&pid, "SELECT pg_backend_pid()")).To(Succeed()) + second.MustBegin() + defer func() { + if second.Tx[0] != nil { + second.MustRollback() + } + }() + defer func() { + if first.Tx[0] != nil { + first.MustRollback() + } + }() + ready := make(chan error, 1) + go func() { + _, err := second.Exec("TRUNCATE snapshot_retry.t") + if err == nil { + _, err = second.Exec("INSERT INTO snapshot_retry.t VALUES(7),(8),(9)") + } + ready <- err + }() + Eventually(func() (int, error) { + var count int + err := backupConn.Get(&count, fmt.Sprintf("SELECT count(*) FROM pg_locks WHERE pid=%d AND NOT granted AND relation='snapshot_retry.t'::regclass", pid)) + return count, err + }, 30*time.Second, 100*time.Millisecond).Should(BeNumerically(">", 0)) + first.MustCommit() + Eventually(session, 90*time.Second).Should(Exit(0)) + Eventually(ready, 30*time.Second).Should(Receive(BeNil())) + second.MustCommit() + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Starting snapshot attempt")) + ts := getBackupTimestamp(string(session.Out.Contents())) + gprestore(gprestorePath, restoreHelperPath, ts, "--backup-dir", backupDir, "--redirect-db", "restoredb") + Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{4, 5, 6})) + Expect(snapshotRetryRows(backupConn)).To(Equal([]int{7, 8, 9})) + waitForSnapshotBackupSessionsToClose() + }) + + It("restores an incremental after TRUNCATE and retains hashes for unchanged heap tables", func() { + createTable("heap", false) + backupConn.MustExec("CREATE TABLE snapshot_retry.unchanged(id int) DISTRIBUTED BY(id); INSERT INTO snapshot_retry.unchanged VALUES(42)") + var count int + Expect(backupConn.Get(&count, "SELECT count(*) FROM snapshot_retry.unchanged")).To(Succeed()) + full := gpbackup(gpbackupPath, backupHelperPath, "--backup-dir", backupDir, "--include-schema", "snapshot_retry", "--leaf-partition-data", "--heap-file-hash") + fullTS := getBackupTimestamp(string(full)) + session := truncateDuringBackup(false, "--include-schema", "snapshot_retry", "--leaf-partition-data", "--heap-file-hash", "--incremental", "--from-timestamp", fullTS) + Expect(session.ExitCode()).To(Equal(0)) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Starting snapshot attempt")) + var currentTOC toc.TOC + ts := getBackupTimestamp(string(session.Out.Contents())) + Expect(yaml.Unmarshal(getMetdataFileContents(backupDir, ts, "toc.yaml"), ¤tTOC)).To(Succeed()) + Expect(currentTOC.IncrementalMetadata.Heap["snapshot_retry.unchanged"].FileHashMD5).NotTo(BeEmpty()) + gprestore(gprestorePath, restoreHelperPath, ts, "--backup-dir", backupDir, "--redirect-db", "restoredb") + Expect(snapshotRetryRows(restoreConn)).To(Equal([]int{4, 5, 6})) + next := gpbackup(gpbackupPath, backupHelperPath, "--backup-dir", backupDir, "--include-schema", "snapshot_retry", "--leaf-partition-data", "--heap-file-hash", "--incremental", "--from-timestamp", ts) + nextTS := getBackupTimestamp(string(next)) + var nextTOC toc.TOC + Expect(yaml.Unmarshal(getMetdataFileContents(backupDir, nextTS, "toc.yaml"), &nextTOC)).To(Succeed()) + Expect(nextTOC.IncrementalMetadata.Heap["snapshot_retry.unchanged"].FileHashMD5).NotTo(BeEmpty()) + for _, entry := range nextTOC.DataEntries { + Expect(entry.Schema + "." + entry.Name).NotTo(Equal("snapshot_retry.unchanged")) + } + }) + DescribeTable("accepts a safe heap rewrite before the snapshot without retrying", func(command string) { + createTable("heap", false) + backupConn.MustExec("CREATE TABLE snapshot_retry.rewrite(id int) DISTRIBUTED BY(id); INSERT INTO snapshot_retry.rewrite VALUES(41),(42); CREATE INDEX snapshot_rewrite_idx ON snapshot_retry.rewrite(id)") + if command == "ALTER TABLE snapshot_retry.rewrite SET TABLESPACE snapshot_rewrite_ts" { + output := backupCluster.GenerateAndExecuteCommand("Creating snapshot test tablespace directories", cluster.ON_HOSTS|cluster.INCLUDE_COORDINATOR, func(host string) string { return "mkdir -p /tmp/snapshot_rewrite_ts" }) + Expect(output.NumErrors).To(BeZero()) + backupConn.MustExec("CREATE TABLESPACE snapshot_rewrite_ts LOCATION '/tmp/snapshot_rewrite_ts'") + DeferCleanup(func() { + backupConn.MustExec("DROP TABLESPACE snapshot_rewrite_ts") + output := backupCluster.GenerateAndExecuteCommand("Removing snapshot test tablespace directories", cluster.ON_HOSTS|cluster.INCLUDE_COORDINATOR, func(host string) string { return "rmdir /tmp/snapshot_rewrite_ts" }) + Expect(output.NumErrors).To(BeZero()) + }) + } + var before, after uint32 + Expect(backupConn.Get(&before, "SELECT relfilenode FROM pg_class WHERE oid='snapshot_retry.rewrite'::regclass")).To(Succeed()) + gate := testutils.SetupTestDbConn("testdb") + defer gate.Close() + gate.MustBegin() + defer func() { + if gate.Tx[0] != nil { + gate.MustRollback() + } + }() + gate.MustExec("LOCK TABLE snapshot_retry.t IN ACCESS EXCLUSIVE MODE") + session := startSnapshotBackup("--include-schema", "snapshot_retry") + waitForSnapshotBackupLock("snapshot_retry.t") + backupConn.MustExec(command) + Expect(backupConn.Get(&after, "SELECT relfilenode FROM pg_class WHERE oid='snapshot_retry.rewrite'::regclass")).To(Succeed()) + Expect(after).NotTo(Equal(before)) + gate.MustCommit() + Eventually(session, 90*time.Second).Should(Exit(0)) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Starting snapshot attempt")) + ts := getBackupTimestamp(string(session.Out.Contents())) + gprestore(gprestorePath, restoreHelperPath, ts, "--backup-dir", backupDir, "--redirect-db", "restoredb") + var rows []int + Expect(restoreConn.Select(&rows, "SELECT id FROM snapshot_retry.rewrite ORDER BY id")).To(Succeed()) + Expect(rows).To(Equal([]int{41, 42})) + }, Entry("VACUUM FULL", "VACUUM FULL snapshot_retry.rewrite"), + Entry("CLUSTER", "CLUSTER snapshot_retry.rewrite USING snapshot_rewrite_idx"), + Entry("SET TABLESPACE", "ALTER TABLE snapshot_retry.rewrite SET TABLESPACE snapshot_rewrite_ts")) + + DescribeTable("cancels blocked locks and completes cleanup after interruption", func(args []string) { + createTable("heap", false) + writer := testutils.SetupTestDbConn("testdb") + defer writer.Close() + writer.MustBegin() + defer writer.MustRollback() + writer.MustExec("TRUNCATE snapshot_retry.t") + session := startSnapshotBackup(append([]string{"--include-schema", "snapshot_retry"}, args...)...) + waitForSnapshotBackupLock("snapshot_retry.t") + var application string + Expect(backupConn.Get(&application, "SELECT application_name FROM pg_stat_activity WHERE datname=current_database() AND application_name LIKE 'gpbackup_%' AND query LIKE 'LOCK TABLE%'")).To(Succeed()) + session.Signal(syscall.SIGINT) + Eventually(session, 30*time.Second).Should(Exit()) + Expect(session.ExitCode()).NotTo(Equal(0)) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Backup completed successfully")) + Expect(string(session.Out.Contents())).NotTo(ContainSubstring("Encountered error during cleanup")) + Expect(string(session.Out.Contents())).To(ContainSubstring("Cleanup complete")) + _, err := os.Stat("/tmp/" + strings.TrimPrefix(application, "gpbackup_") + ".lck") + Expect(os.IsNotExist(err)).To(BeTrue()) + waitForSnapshotBackupSessionsToClose() + }, Entry("with history", []string{}), Entry("with single data file", []string{"--single-data-file"}), Entry("without history", []string{"--no-history"})) +}) diff --git a/integration/snapshot_test.go b/integration/snapshot_test.go index 503ab2a7..f9210cde 100644 --- a/integration/snapshot_test.go +++ b/integration/snapshot_test.go @@ -2,9 +2,13 @@ package integration import ( "fmt" + "time" "github.com/apache/cloudberry-backup/backup" + "github.com/apache/cloudberry-backup/options" "github.com/apache/cloudberry-backup/testutils" + "github.com/apache/cloudberry-go-libs/dbconn" + "github.com/spf13/pflag" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -219,3 +223,169 @@ var _ = Describe("synchronized snapshot integration tests", func() { }) }) }) + +var _ = Describe("lock before snapshot integration", func() { + var reader *dbconn.DBConn + var opts *options.Options + var readerPID int + BeforeEach(func() { + if !connectionPool.Version.IsCBDB() { + Skip("lock-before-snapshot preparation requires Cloudberry") + } + connectionPool.MustExec("CREATE SCHEMA snapshot_prepare; CREATE TABLE snapshot_prepare.t(id int) DISTRIBUTED BY(id); INSERT INTO snapshot_prepare.t VALUES(1),(2),(3)") + reader = dbconn.NewDBConnFromEnvironment("testdb") + reader.MustConnect(2) + backup.SetConnection(reader) + backup.InitializeMetadataParams(reader) + for i := 0; i < 2; i++ { + reader.MustExec("SET application_name TO 'snapshot_prepare_test'", i) + backup.SetSessionGUCs(i) + } + Expect(reader.Get(&readerPID, "SELECT pg_backend_pid()")).To(Succeed()) + Expect(backupCmdFlags.Set(options.INCLUDE_SCHEMA, "snapshot_prepare")).To(Succeed()) + var err error + opts, err = options.NewOptions(backupCmdFlags) + Expect(err).NotTo(HaveOccurred()) + }) + AfterEach(func() { + if reader != nil { + for i := 0; i < reader.NumConns; i++ { + if reader.Tx[i] != nil { + reader.MustRollback(i) + } + } + reader.Close() + reader = nil + } + backup.SetConnection(connectionPool) + backup.InitializeMetadataParams(connectionPool) + backup.SetBackupSnapshot("") + backup.SetFilterRelationClause("") + connectionPool.MustExec("DROP SCHEMA IF EXISTS snapshot_prepare CASCADE") + }) + prepare := func() <-chan error { + ready := make(chan error, 1) + go func() { + defer GinkgoRecover() + ready <- backup.PrepareBackupSnapshot(opts) + }() + return ready + } + waitForLock := func(table string) { + Eventually(func() (int, error) { + var count int + err := connectionPool.Get(&count, fmt.Sprintf("SELECT count(*) FROM pg_locks WHERE pid=%d AND relation='%s'::regclass AND NOT granted", readerPID, table)) + return count, err + }, 30*time.Second, 50*time.Millisecond).Should(BeNumerically(">", 0)) + } + It("includes a TRUNCATE and related DML committed while locks wait, on every worker", func() { + connectionPool.MustExec("CREATE TABLE snapshot_prepare.marker(id int) DISTRIBUTED BY(id); INSERT INTO snapshot_prepare.marker VALUES(1)") + writer := testutils.SetupTestDbConn("testdb") + defer writer.Close() + writer.MustBegin() + defer func() { + if writer.Tx[0] != nil { + writer.MustRollback() + } + }() + writer.MustExec("TRUNCATE snapshot_prepare.t; INSERT INTO snapshot_prepare.t VALUES(4),(5),(6); UPDATE snapshot_prepare.marker SET id=2") + Expect(backupCmdFlags.Set(options.SNAPSHOT_ATTEMPTS, "1")).To(Succeed()) + ready := prepare() + waitForLock("snapshot_prepare.t") + writer.MustCommit() + Eventually(ready, 30*time.Second).Should(Receive(BeNil())) + connectionPool.MustExec("INSERT INTO snapshot_prepare.t VALUES(7); UPDATE snapshot_prepare.marker SET id=3") + for i := 0; i < 2; i++ { + var rows []int + Expect(reader.Select(&rows, "SELECT id FROM snapshot_prepare.t ORDER BY id", i)).To(Succeed()) + Expect(rows).To(Equal([]int{4, 5, 6})) + var marker int + Expect(reader.Get(&marker, "SELECT id FROM snapshot_prepare.marker", i)).To(Succeed()) + Expect(marker).To(Equal(2)) + } + }) + DescribeTable("retries only when the final snapshot contains an unprotected table", func(limit int) { + Expect(backupCmdFlags.Set(options.SNAPSHOT_ATTEMPTS, fmt.Sprint(limit))).To(Succeed()) + gate := testutils.SetupTestDbConn("testdb") + defer gate.Close() + gate.MustBegin() + defer func() { + if gate.Tx[0] != nil { + gate.MustRollback() + } + }() + gate.MustExec("LOCK TABLE snapshot_prepare.t IN ACCESS EXCLUSIVE MODE") + ready := prepare() + waitForLock("snapshot_prepare.t") + connectionPool.MustExec("CREATE TABLE snapshot_prepare.new_table(id int) DISTRIBUTED BY(id); INSERT INTO snapshot_prepare.new_table VALUES(9)") + gate.MustCommit() + if limit == 1 { + var err error + Eventually(ready, 30*time.Second).Should(Receive(&err)) + Expect(err).To(MatchError(ContainSubstring("snapshot_prepare.new_table"))) + Expect(reader.Tx[0]).To(BeNil()) + Expect(reader.Tx[1]).To(BeNil()) + } else { + Eventually(ready, 30*time.Second).Should(Receive(BeNil())) + for i := 0; i < 2; i++ { + var value int + Expect(reader.Get(&value, "SELECT id FROM snapshot_prepare.new_table", i)).To(Succeed()) + Expect(value).To(Equal(9)) + } + } + }, Entry("fails without retries", 1), Entry("locks the new table in a fresh transaction", 3)) + It("rebuilds explicit filters and partition expansion after a leaf is replaced", func() { + connectionPool.MustExec(`CREATE TABLE snapshot_prepare.root(id int) DISTRIBUTED BY(id) PARTITION BY RANGE(id); + CREATE TABLE snapshot_prepare.old_leaf PARTITION OF snapshot_prepare.root FOR VALUES FROM(0) TO(10)`) + Expect(backupCmdFlags.Lookup(options.INCLUDE_SCHEMA).Value.(pflag.SliceValue).Replace(nil)).To(Succeed()) + Expect(backupCmdFlags.Set(options.INCLUDE_RELATION, "snapshot_prepare.t")).To(Succeed()) + Expect(backupCmdFlags.Set(options.INCLUDE_RELATION, "snapshot_prepare.root")).To(Succeed()) + Expect(backupCmdFlags.Set(options.LEAF_PARTITION_DATA, "true")).To(Succeed()) + var err error + opts, err = options.NewOptions(backupCmdFlags) + Expect(err).NotTo(HaveOccurred()) + gate := testutils.SetupTestDbConn("testdb") + defer gate.Close() + gate.MustBegin() + defer func() { + if gate.Tx[0] != nil { + gate.MustRollback() + } + }() + gate.MustExec("LOCK TABLE snapshot_prepare.t IN ACCESS EXCLUSIVE MODE") + ready := prepare() + waitForLock("snapshot_prepare.t") + connectionPool.MustExec(`ALTER TABLE snapshot_prepare.root DETACH PARTITION snapshot_prepare.old_leaf; + DROP TABLE snapshot_prepare.old_leaf; + CREATE TABLE snapshot_prepare.new_leaf PARTITION OF snapshot_prepare.root FOR VALUES FROM(0) TO(10); + INSERT INTO snapshot_prepare.root VALUES(4),(5),(6)`) + gate.MustCommit() + Eventually(ready, 30*time.Second).Should(Receive(BeNil())) + Expect(opts.GetIncludedTables()).To(ContainElement("snapshot_prepare.new_leaf")) + Expect(opts.GetIncludedTables()).NotTo(ContainElement("snapshot_prepare.old_leaf")) + for i := 0; i < 2; i++ { + var rows []int + Expect(reader.Select(&rows, "SELECT id FROM snapshot_prepare.root ORDER BY id", i)).To(Succeed()) + Expect(rows).To(Equal([]int{4, 5, 6})) + } + }) + It("checks nested descendants even when only a root is supplied", func() { + connectionPool.MustExec(`CREATE TABLE snapshot_prepare.root(id int) DISTRIBUTED BY(id) PARTITION BY RANGE(id); + CREATE TABLE snapshot_prepare.middle PARTITION OF snapshot_prepare.root FOR VALUES FROM(0) TO(10) PARTITION BY RANGE(id); + CREATE TABLE snapshot_prepare.leaf PARTITION OF snapshot_prepare.middle FOR VALUES FROM(0) TO(10)`) + var oid uint32 + Expect(reader.Get(&oid, "SELECT 'snapshot_prepare.root'::regclass::oid")).To(Succeed()) + reader.MustBegin() + reader.MustExec("LOCK TABLE ONLY snapshot_prepare.root IN ACCESS SHARE MODE") + tables := []backup.Relation{{Oid: oid, Schema: "snapshot_prepare", Name: "root"}} + conflicts, err := backup.CheckSnapshotTableLocks(reader, tables) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(ConsistOf("snapshot_prepare.middle", "snapshot_prepare.leaf")) + reader.MustRollback() + reader.MustBegin() + Expect(backup.LockTables(reader, tables)).To(Succeed()) + conflicts, err = backup.CheckSnapshotTableLocks(reader, tables) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(BeEmpty()) + }) +}) diff --git a/options/flag.go b/options/flag.go index dad5ea76..a0ba8204 100644 --- a/options/flag.go +++ b/options/flag.go @@ -57,6 +57,7 @@ const ( NO_INHERITS = "no-inherits" REPORT_DIR = "report-dir" HEAP_FILE_HASH = "heap-file-hash" + SNAPSHOT_ATTEMPTS = "snapshot-attempts" DEFAULT_HISTORY_SYNC_STANDBY_TIMEOUT = 300 ) @@ -95,6 +96,7 @@ func SetBackupFlagDefaults(flagSet *pflag.FlagSet) { flagSet.Bool(WITH_STATS, false, "Back up query plan statistics") flagSet.Bool(WITHOUT_GLOBALS, false, "Skip backup of global metadata") flagSet.Bool(NO_INHERITS, false, "For a filtered backup, don't back up all tables that inherit included tables") + flagSet.Int(SNAPSHOT_ATTEMPTS, 3, "Maximum Cloudberry snapshot preparation attempts when concurrent DDL changes the table set, including the first; 1 disables retries") flagSet.Bool(HEAP_FILE_HASH, false, "Skip unchanged heap tables in incremental backups by hashing their data files. Issues a cluster-wide CHECKPOINT before the backup starts") } diff --git a/options/options.go b/options/options.go index 716c249f..9ef1fb06 100644 --- a/options/options.go +++ b/options/options.go @@ -23,6 +23,7 @@ type Options struct { ExcludedSchemas []string IncludedSchemas []string originalIncludedRelations []string + originalExcludedRelations []string RedirectSchema string } @@ -74,7 +75,8 @@ func NewOptions(initialFlags *pflag.FlagSet) (*Options, error) { IncludedSchemas: includedSchemas, ExcludedSchemas: excludedSchemas, isLeafPartitionData: leafPartitionData, - originalIncludedRelations: includedRelations, + originalIncludedRelations: append([]string(nil), includedRelations...), + originalExcludedRelations: append([]string(nil), excludedRelations...), RedirectSchema: redirectSchema, }, nil } @@ -136,6 +138,16 @@ func (o Options) GetExcludedSchemas() []string { return o.ExcludedSchemas } +// ResetTableFilters restores the input names without rereading filter files. +func (o *Options) ResetTableFilters(flags *pflag.FlagSet) error { + o.IncludedRelations = append([]string(nil), o.originalIncludedRelations...) + o.ExcludedRelations = append([]string(nil), o.originalExcludedRelations...) + if err := flags.Lookup(INCLUDE_RELATION).Value.(pflag.SliceValue).Replace(o.IncludedRelations); err != nil { + return err + } + return flags.Lookup(EXCLUDE_RELATION).Value.(pflag.SliceValue).Replace(o.ExcludedRelations) +} + func (o *Options) AddIncludedRelation(relation string) { o.IncludedRelations = append(o.IncludedRelations, relation) } diff --git a/options/options_test.go b/options/options_test.go index 539f82b1..1888dc19 100644 --- a/options/options_test.go +++ b/options/options_test.go @@ -21,6 +21,49 @@ var _ = Describe("options", func() { myflags = &pflag.FlagSet{} options.SetBackupFlagDefaults(myflags) }) + Describe("snapshot attempts and filter reset", func() { + It("defaults to three attempts and rejects noninteger values", func() { + value, err := myflags.GetInt(options.SNAPSHOT_ATTEMPTS) + Expect(err).NotTo(HaveOccurred()) + Expect(value).To(Equal(3)) + Expect(myflags.Set(options.SNAPSHOT_ATTEMPTS, "1.5")).NotTo(Succeed()) + restoreFlags := pflag.NewFlagSet("restore", pflag.ContinueOnError) + options.SetRestoreFlagDefaults(restoreFlags) + Expect(restoreFlags.Lookup(options.SNAPSHOT_ATTEMPTS)).To(BeNil()) + }) + It("restores original names after expansion without reading the filter file again", func() { + file, err := os.CreateTemp("", "snapshot-filters") + Expect(err).NotTo(HaveOccurred()) + defer os.Remove(file.Name()) + _, err = file.WriteString("public.root\n") + Expect(err).NotTo(HaveOccurred()) + Expect(file.Close()).To(Succeed()) + Expect(myflags.Set(options.INCLUDE_RELATION_FILE, file.Name())).To(Succeed()) + subject, err := options.NewOptions(myflags) + Expect(err).NotTo(HaveOccurred()) + subject.AddIncludedRelation("public.old_leaf") + Expect(myflags.Set(options.INCLUDE_RELATION, "public.old_leaf")).To(Succeed()) + Expect(os.Remove(file.Name())).To(Succeed()) + Expect(subject.ResetTableFilters(myflags)).To(Succeed()) + Expect(subject.GetIncludedTables()).To(Equal([]string{"public.root"})) + Expect(options.MustGetFlagStringArray(myflags, options.INCLUDE_RELATION)).To(Equal([]string{"public.root"})) + Expect(subject.GetOriginalIncludedTables()).To(Equal([]string{"public.root"})) + Expect(subject.ResetTableFilters(myflags)).To(Succeed()) + }) + It("restores exclusions and owns copies of original names", func() { + Expect(myflags.Set(options.INCLUDE_RELATION, "public.root")).To(Succeed()) + Expect(myflags.Set(options.EXCLUDE_RELATION, "public.omitted")).To(Succeed()) + subject, err := options.NewOptions(myflags) + Expect(err).NotTo(HaveOccurred()) + subject.IncludedRelations[0] = "public.changed" + subject.ExcludedRelations[0] = "public.changed" + Expect(subject.ResetTableFilters(myflags)).To(Succeed()) + Expect(subject.GetIncludedTables()).To(Equal([]string{"public.root"})) + Expect(subject.GetExcludedTables()).To(Equal([]string{"public.omitted"})) + Expect(options.MustGetFlagStringArray(myflags, options.EXCLUDE_RELATION)).To(Equal([]string{"public.omitted"})) + }) + }) + Describe("Options initialization", func() { It("returns no included tables when none specified", func() { subject, err := options.NewOptions(myflags)