Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/designs/product-neutral-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ whose PostgreSQL extension uses dotted semantic versions set
`core.ExtensionVersionSemver`; automatic upgrades, explicit targets, comparison,
events, and schema status then use that format without rewriting it.

`ExtensionUpdateSQL` upgrades `documentdb_core` before `documentdb` in one
transaction. Explicit schema versions apply to both extensions; `auto` uses
each extension's packaged default. Other products and independently versioned
dependencies are unchanged. Existing version mismatches are not repaired.

The DocumentDB controllers and webhook in `internal/controller` and
`internal/webhook` are now thin wrappers over these packages. They keep their
types, method names, and `cmd/main.go` wiring. CRD schemas are unchanged;
Expand Down
17 changes: 12 additions & 5 deletions operator/src/internal/cnpg/extension_sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
cnpgv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1"
"github.com/lib/pq"

"github.com/documentdb/documentdb-operator/internal/product"
util "github.com/documentdb/documentdb-operator/internal/utils"
)

Expand All @@ -22,14 +23,20 @@ func ExtensionVersionSQL(extension string) string {
return fmt.Sprintf("SELECT default_version, installed_version FROM pg_available_extensions WHERE name = %s", pq.QuoteLiteral(extension))
}

// ExtensionUpdateSQL returns the ALTER EXTENSION statement for the named
// extension. An empty targetVersion updates to the binary's default version.
// ExtensionUpdateSQL returns SQL to upgrade the named extension. DocumentDB
// upgrades documentdb_core first in the same transaction. An empty targetVersion
// updates each extension to its binary's default version.
// targetVersion must already be validated (digits, dots, and hyphens only).
func ExtensionUpdateSQL(extension, targetVersion string) string {
if targetVersion == "" {
return fmt.Sprintf("ALTER EXTENSION %s UPDATE", pq.QuoteIdentifier(extension))
updateSQL := fmt.Sprintf("ALTER EXTENSION %s UPDATE", pq.QuoteIdentifier(extension))
if targetVersion != "" {
updateSQL += " TO " + pq.QuoteLiteral(targetVersion)
}
return fmt.Sprintf("ALTER EXTENSION %s UPDATE TO %s", pq.QuoteIdentifier(extension), pq.QuoteLiteral(targetVersion))
if extension == product.DocumentDBExtensionName {
coreSQL := ExtensionUpdateSQL(product.DocumentDBCoreExtensionName, targetVersion)
return "BEGIN; " + coreSQL + "; " + updateSQL + "; COMMIT;"
}
return updateSQL
}

// ReplicationRoleCheckSQL returns the query that yields one row when CNPG's
Expand Down
13 changes: 8 additions & 5 deletions operator/src/internal/cnpg/extension_sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ import (

func TestExtensionLifecycleSQLUsesProductNames(t *testing.T) {
cases := map[string]string{
ExtensionVersionSQL("pgcosmos"): "SELECT default_version, installed_version FROM pg_available_extensions WHERE name = 'pgcosmos'",
ExtensionUpdateSQL("pgcosmos", ""): `ALTER EXTENSION "pgcosmos" UPDATE`,
ExtensionUpdateSQL("pgcosmos", "1.2-0"): `ALTER EXTENSION "pgcosmos" UPDATE TO '1.2-0'`,
ReplicationRoleCheckSQL("cosmos_admin"): "SELECT 1 FROM pg_roles WHERE rolname = 'streaming_replica' AND pg_has_role('streaming_replica', 'cosmos_admin', 'USAGE');",
ReplicationRoleGrantSQL("cosmos_admin"): `GRANT "cosmos_admin" TO streaming_replica;`,
ExtensionVersionSQL("pgcosmos"): "SELECT default_version, installed_version FROM pg_available_extensions WHERE name = 'pgcosmos'",
ExtensionUpdateSQL("pgcosmos", ""): `ALTER EXTENSION "pgcosmos" UPDATE`,
ExtensionUpdateSQL("pgcosmos", "1.2-0"): `ALTER EXTENSION "pgcosmos" UPDATE TO '1.2-0'`,
ExtensionUpdateSQL("documentdb", ""): `BEGIN; ALTER EXTENSION "documentdb_core" UPDATE; ALTER EXTENSION "documentdb" UPDATE; COMMIT;`,
ExtensionUpdateSQL("documentdb", "1.2-0"): `BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '1.2-0'; ALTER EXTENSION "documentdb" UPDATE TO '1.2-0'; COMMIT;`,
ExtensionUpdateSQL("documentdb_core", ""): `ALTER EXTENSION "documentdb_core" UPDATE`,
ReplicationRoleCheckSQL("cosmos_admin"): "SELECT 1 FROM pg_roles WHERE rolname = 'streaming_replica' AND pg_has_role('streaming_replica', 'cosmos_admin', 'USAGE');",
ReplicationRoleGrantSQL("cosmos_admin"): `GRANT "cosmos_admin" TO streaming_replica;`,
}
for got, want := range cases {
if got != want {
Expand Down
12 changes: 6 additions & 6 deletions operator/src/internal/controller/documentdb_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -855,7 +855,7 @@ var _ = Describe("DocumentDB Controller", func() {
// Verify both SQL calls were made
Expect(sqlCalls).To(HaveLen(2))
Expect(sqlCalls[0]).To(ContainSubstring("pg_available_extensions"))
Expect(sqlCalls[1]).To(Equal(`ALTER EXTENSION "documentdb" UPDATE`))
Expect(sqlCalls[1]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE; ALTER EXTENSION "documentdb" UPDATE; COMMIT;`))

// Status should reflect the upgraded version (default version as semver)
updatedDB := &dbv1.DocumentDB{}
Expand Down Expand Up @@ -1362,7 +1362,7 @@ var _ = Describe("DocumentDB Controller", func() {
// Both version-check and ALTER EXTENSION should have been called
Expect(sqlCalls).To(HaveLen(2))
Expect(sqlCalls[0]).To(ContainSubstring("pg_available_extensions"))
Expect(sqlCalls[1]).To(Equal(`ALTER EXTENSION "documentdb" UPDATE`))
Expect(sqlCalls[1]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE; ALTER EXTENSION "documentdb" UPDATE; COMMIT;`))

// Status should reflect the upgraded version
updatedDB := &dbv1.DocumentDB{}
Expand Down Expand Up @@ -1396,7 +1396,7 @@ var _ = Describe("DocumentDB Controller", func() {
},
}

// Explicit version: update to 0.110.0 (binary is also 0.110-0)
// Explicit version: update both extensions to 0.110.0, below binary 0.111-0.
documentdb := &dbv1.DocumentDB{
ObjectMeta: metav1.ObjectMeta{
Name: "test-documentdb",
Expand All @@ -1421,8 +1421,8 @@ var _ = Describe("DocumentDB Controller", func() {
SQLExecutor: func(_ context.Context, _ *cnpgv1.Cluster, sql string) (string, error) {
sqlCalls = append(sqlCalls, sql)
if len(sqlCalls) == 1 {
// Binary is 0.110-0, installed is 0.109-0
return " default_version | installed_version \n-----------------+-------------------\n 0.110-0 | 0.109-0 \n", nil
// Binary is 0.111-0, installed is 0.109-0.
return " default_version | installed_version \n-----------------+-------------------\n 0.111-0 | 0.109-0 \n", nil
}
return "ALTER EXTENSION", nil
},
Expand All @@ -1434,7 +1434,7 @@ var _ = Describe("DocumentDB Controller", func() {
// Should run ALTER EXTENSION UPDATE TO specific version
Expect(sqlCalls).To(HaveLen(2))
Expect(sqlCalls[0]).To(ContainSubstring("pg_available_extensions"))
Expect(sqlCalls[1]).To(Equal(`ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'`))
Expect(sqlCalls[1]).To(Equal(`BEGIN; ALTER EXTENSION "documentdb_core" UPDATE TO '0.110-0'; ALTER EXTENSION "documentdb" UPDATE TO '0.110-0'; COMMIT;`))

// Status should reflect the explicit version
updatedDB := &dbv1.DocumentDB{}
Expand Down
3 changes: 3 additions & 0 deletions operator/src/internal/product/documentdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ func DocumentDBProfile() ProductProfile {
// DocumentDBExtensionName is the PostgreSQL extension backing DocumentDB.
const DocumentDBExtensionName = "documentdb"

// DocumentDBCoreExtensionName is the co-versioned PostgreSQL core extension.
const DocumentDBCoreExtensionName = "documentdb_core"

// DocumentDBAdapter is the first product adapter. It maps the DocumentDB custom
// resource onto the product-neutral model consumed by the reconciler.
type DocumentDBAdapter struct{}
Expand Down
3 changes: 2 additions & 1 deletion operator/src/pkg/core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ func ValidateResources(res Resources, monitoring bool, base *field.Path, cfg Spl
func ExtensionVersionSQL(extension string) string { return cnpg.ExtensionVersionSQL(extension) }

// ExtensionUpdateSQL upgrades extension, to targetVersion when set. Pass the
// unquoted extension name; it is quoted as a SQL identifier.
// unquoted extension name; it is quoted as a SQL identifier. For DocumentDB,
// documentdb_core is upgraded first in the same transaction.
func ExtensionUpdateSQL(extension, targetVersion string) string {
return cnpg.ExtensionUpdateSQL(extension, targetVersion)
}
Expand Down
33 changes: 27 additions & 6 deletions test/e2e/tests/upgrade/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

. "github.com/onsi/ginkgo/v2" //nolint:revive

cnpgclusterutils "github.com/cloudnative-pg/cloudnative-pg/tests/utils/clusterutils"
"github.com/cloudnative-pg/cloudnative-pg/tests/utils/environment"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
Expand Down Expand Up @@ -251,8 +252,23 @@ func replicaInstalledSchemaVersion(
return agreed, nil
}

// podInstalledSchemaVersion execs psql on a single pod and returns the
// installed documentdb extension version normalized to semver.
func primaryInstalledSchemaVersion(
ctx context.Context,
env *environment.TestingEnvironment,
ns, clusterName string,
) (string, error) {
pod, err := cnpgclusterutils.GetPrimary(ctx, env.Client, ns, clusterName)
if err != nil {
return "", fmt.Errorf("get primary pod for cluster %s/%s: %w", ns, clusterName, err)
}
if pod == nil || pod.Name == "" {
return "", fmt.Errorf("no primary pod found for cluster %s/%s", ns, clusterName)
}
return podInstalledSchemaVersion(ctx, env, *pod)
}

// podInstalledSchemaVersion requires documentdb and documentdb_core to agree
// and returns their installed version normalized to semver.
func podInstalledSchemaVersion(
ctx context.Context,
env *environment.TestingEnvironment,
Expand All @@ -261,15 +277,20 @@ func podInstalledSchemaVersion(
timeout := time.Minute
stdout, stderr, err := env.EventuallyExecCommand(ctx, pod, "postgres", &timeout,
"psql", "-U", "postgres", "-d", "postgres", "-tAc",
"SELECT extversion FROM pg_extension WHERE extname='documentdb'")
"SELECT extversion FROM pg_extension WHERE extname IN ('documentdb', 'documentdb_core') ORDER BY extname")
if err != nil {
return "", fmt.Errorf("exec psql on pod %s: %w (stderr: %s)", pod.Name, err, stderr)
}

raw := strings.TrimSpace(stdout)
if raw == "" {
return "", fmt.Errorf("documentdb extension not installed on pod %s", pod.Name)
versions := strings.Fields(stdout)
if len(versions) != 2 {
return "", fmt.Errorf("expected documentdb and documentdb_core versions on pod %s, got %q", pod.Name, stdout)
}
if versions[0] != versions[1] {
return "", fmt.Errorf("extension versions differ on pod %s: documentdb=%s, documentdb_core=%s",
pod.Name, versions[0], versions[1])
}
raw := versions[0]
// "0.110-0" -> "0.110.0"; a value already in semver form is unchanged.
if i := strings.LastIndex(raw, "-"); i >= 0 {
raw = raw[:i] + "." + raw[i+1:]
Expand Down
8 changes: 8 additions & 0 deletions test/e2e/tests/upgrade/upgrade_schema_auto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,14 @@ var _ = Describe("DocumentDB upgrade — schema (auto mode)",
timeouts.PollInterval(timeouts.DocumentDBUpgrade),
).Should(Equal(newVersion), "auto mode should migrate schema to %s in a single step", newVersion)

By("verifying documentdb and documentdb_core both migrated")
Eventually(func() (string, error) {
return primaryInstalledSchemaVersion(ctx, env, ns, ddName)
},
timeouts.For(timeouts.DocumentDBUpgrade),
timeouts.PollInterval(timeouts.DocumentDBUpgrade),
).Should(Equal(newVersion), "both extensions must migrate to %s in auto mode", newVersion)

By("verifying seeded data survived the single-step upgrade")
handle2, err := e2emongo.NewFromDocumentDB(ctx, env, ns, ddName)
Expect(err).NotTo(HaveOccurred(), "reconnect to DocumentDB gateway after single-step upgrade")
Expand Down
8 changes: 8 additions & 0 deletions test/e2e/tests/upgrade/upgrade_schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,9 @@ var _ = Describe("DocumentDB upgrade — schema",
// Consistently below: it caches the last good read so a transient
// API error can't fail the Consistently window (see helper doc).
schemaVersion := schemaVersionGetter(ctx, c, key)
installedSchemaVersion := func() (string, error) {
return primaryInstalledSchemaVersion(ctx, env, ns, ddName)
}

By("waiting for status.schemaVersion to settle on the old version")
Eventually(schemaVersion,
Expand Down Expand Up @@ -214,6 +217,11 @@ var _ = Describe("DocumentDB upgrade — schema",
timeouts.PollInterval(timeouts.DocumentDBUpgrade),
).Should(Equal(newVersion), "schema did not migrate to %s after finalize", newVersion)

Eventually(installedSchemaVersion,
timeouts.For(timeouts.DocumentDBUpgrade),
timeouts.PollInterval(timeouts.DocumentDBUpgrade),
).Should(Equal(newVersion), "both extensions must migrate to %s", newVersion)

Eventually(assertions.AssertDocumentDBReady(ctx, c, key),
timeouts.For(timeouts.DocumentDBUpgrade),
timeouts.PollInterval(timeouts.DocumentDBUpgrade),
Expand Down
Loading