Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support SQL Server Switchover (after resolving conflicts) #11850

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"log"
"reflect"
"slices"
"strings"
"time"

Expand Down Expand Up @@ -89,6 +90,7 @@ var (
}

replicaConfigurationKeys = []string{
"replica_configuration.0.cascadable_replica",
"replica_configuration.0.ca_certificate",
"replica_configuration.0.client_certificate",
"replica_configuration.0.client_key",
Expand Down Expand Up @@ -136,7 +138,10 @@ func ResourceSqlDatabaseInstance() *schema.Resource {
CustomizeDiff: customdiff.All(
tpgresource.DefaultProviderProject,
customdiff.ForceNewIfChange("settings.0.disk_size", compute.IsDiskShrinkage),
customdiff.ForceNewIfChange("master_instance_name", isMasterInstanceNameSet),
customdiff.ForceNewIf("master_instance_name", func(_ context.Context, d *schema.ResourceDiff, meta interface{}) bool {
// If we set master but this is not the new master of a switchover, require replacement and warn user.
return !isSwitchoverFromOldPrimarySide(d)
}),
customdiff.IfValueChange("instance_type", isReplicaPromoteRequested, checkPromoteConfigurationsAndUpdateDiff),
privateNetworkCustomizeDiff,
pitrSupportDbCustomizeDiff,
Expand Down Expand Up @@ -800,6 +805,13 @@ is set to true. Defaults to ZONAL.`,
AtLeastOneOf: replicaConfigurationKeys,
Description: `PEM representation of the trusted CA's x509 certificate.`,
},
"cascadable_replica": {
Type: schema.TypeBool,
Optional: true,
ForceNew: false,
AtLeastOneOf: replicaConfigurationKeys,
Description: `Specifies if a SQL Server replica is a cascadable replica. A cascadable replica is a SQL Server cross region replica that supports replica(s) under it.`,
},
"client_certificate": {
Type: schema.TypeString,
Optional: true,
Expand Down Expand Up @@ -875,6 +887,15 @@ is set to true. Defaults to ZONAL.`,
},
Description: `The configuration for replication.`,
},
"replica_names": {
Type: schema.TypeList,
Computed: true,
Optional: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Description: `The replicas of the instance.`,
},
"server_ca_cert": {
Type: schema.TypeList,
Computed: true,
Expand Down Expand Up @@ -1317,6 +1338,7 @@ func expandReplicaConfiguration(configured []interface{}) *sqladmin.ReplicaConfi

_replicaConfiguration := configured[0].(map[string]interface{})
return &sqladmin.ReplicaConfiguration{
CascadableReplica: _replicaConfiguration["cascadable_replica"].(bool),
FailoverTarget: _replicaConfiguration["failover_target"].(bool),

// MysqlReplicaConfiguration has been flattened in the TF schema, so
Expand Down Expand Up @@ -1642,8 +1664,13 @@ func resourceSqlDatabaseInstanceRead(d *schema.ResourceData, meta interface{}) e
}
}

if err := d.Set("replica_configuration", flattenReplicaConfiguration(instance.ReplicaConfiguration, d)); err != nil {
log.Printf("[WARN] Failed to set SQL Database Instance Replica Configuration")
if instance.ReplicaConfiguration != nil {
if err := d.Set("replica_configuration", flattenReplicaConfiguration(instance.ReplicaConfiguration, d)); err != nil {
log.Printf("[WARN] Failed to set SQL Database Instance Replica Configuration")
}
}
if err := d.Set("replica_names", instance.ReplicaNames); err != nil {
return fmt.Errorf("Error setting replica_names: %w", err)
}
ipAddresses := flattenIpAddresses(instance.IpAddresses)
if err := d.Set("ip_address", ipAddresses); err != nil {
Expand Down Expand Up @@ -1699,6 +1726,14 @@ func resourceSqlDatabaseInstanceRead(d *schema.ResourceData, meta interface{}) e
return nil
}

type replicaDRKind int

const (
replicaDRNone replicaDRKind = iota
replicaDRByPromote
replicaDRBySwitchover
)

func resourceSqlDatabaseInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
Expand All @@ -1715,17 +1750,20 @@ func resourceSqlDatabaseInstanceUpdate(d *schema.ResourceData, meta interface{})
maintenance_version = v.(string)
}

promoteReadReplicaRequired := false
replicaDRKind := replicaDRNone
if d.HasChange("instance_type") {
oldInstanceType, newInstanceType := d.GetChange("instance_type")

if isReplicaPromoteRequested(nil, oldInstanceType, newInstanceType, nil) {
err = checkPromoteConfigurations(d)
if err != nil {
return err
if isSwitchoverRequested(d) {
replicaDRKind = replicaDRBySwitchover
} else {
err = checkPromoteConfigurations(d)
if err != nil {
return err
}
replicaDRKind = replicaDRByPromote
}

promoteReadReplicaRequired = true
}
}

Expand Down Expand Up @@ -1873,12 +1911,25 @@ func resourceSqlDatabaseInstanceUpdate(d *schema.ResourceData, meta interface{})
}
}

if promoteReadReplicaRequired {
err = transport_tpg.Retry(transport_tpg.RetryOptions{
RetryFunc: func() (rerr error) {
if replicaDRKind != replicaDRNone {
var retryFunc func() (rerr error)
switch replicaDRKind {
case replicaDRByPromote:
retryFunc = func() (rerr error) {
op, rerr = config.NewSqlAdminClient(userAgent).Instances.PromoteReplica(project, d.Get("name").(string)).Do()
return rerr
},
}
case replicaDRBySwitchover:
retryFunc = func() (rerr error) {
op, rerr = config.NewSqlAdminClient(userAgent).Instances.Switchover(project, d.Get("name").(string)).Do()
return rerr
}
default:
return fmt.Errorf("unknown replica DR scenario: %v", replicaDRKind)
}

err = transport_tpg.Retry(transport_tpg.RetryOptions{
RetryFunc: retryFunc,
Timeout: d.Timeout(schema.TimeoutUpdate),
ErrorRetryPredicates: []transport_tpg.RetryErrorPredicateFunc{transport_tpg.IsSqlOperationInProgressError},
})
Expand Down Expand Up @@ -2339,6 +2390,7 @@ func flattenReplicaConfiguration(replicaConfiguration *sqladmin.ReplicaConfigura

if replicaConfiguration != nil {
data := map[string]interface{}{
"cascadable_replica": replicaConfiguration.CascadableReplica,
"failover_target": replicaConfiguration.FailoverTarget,

// Don't attempt to assign anything from replicaConfiguration.MysqlReplicaConfiguration,
Expand Down Expand Up @@ -2526,6 +2578,20 @@ func isMasterInstanceNameSet(_ context.Context, oldMasterInstanceName interface{
return true
}

func isSwitchoverRequested(d *schema.ResourceData) bool {
originalPrimaryName, _ := d.GetChange("master_instance_name")
_, newReplicaNames := d.GetChange("replica_names")
if !slices.Contains(newReplicaNames.([]interface{}), originalPrimaryName) {
return false
}
dbVersion, _ := d.GetChange("database_version")
if !strings.HasPrefix(dbVersion.(string), "SQLSERVER") {
log.Printf("[WARN] Switchover is only supported for SQL Server %q", dbVersion)
return false
}
return true
}

func isReplicaPromoteRequested(_ context.Context, oldInstanceType interface{}, newInstanceType interface{}, _ interface{}) bool {
oldInstanceType = oldInstanceType.(string)
newInstanceType = newInstanceType.(string)
Expand All @@ -2537,6 +2603,30 @@ func isReplicaPromoteRequested(_ context.Context, oldInstanceType interface{}, n
return false
}

// Check if this resource change is the manual update done on old primary after a switchover. If true, no replacement is needed.
func isSwitchoverFromOldPrimarySide(d *schema.ResourceDiff) bool {
dbVersion, _ := d.GetChange("database_version")
if !strings.HasPrefix(dbVersion.(string), "SQLSERVER") {
log.Printf("[WARN] Switchover is only supported for SQL Server %q", dbVersion)
return false
}
oldInstanceType, newInstanceType := d.GetChange("instance_type")
oldReplicaNames, newReplicaNames := d.GetChange("replica_names")
_, newMasterInstanceName := d.GetChange("master_instance_name")
_, newReplicaConfiguration := d.GetChange("replica_configuration")
if len(newReplicaConfiguration.([]interface{})) != 1 || newReplicaConfiguration.([]interface{})[0] == nil{
return false;
}
replicaConfiguration := newReplicaConfiguration.([]interface{})[0].(map[string]interface{})
cascadableReplica, cascadableReplicaFieldExists := replicaConfiguration["cascadable_replica"]

return newMasterInstanceName != nil &&
oldInstanceType.(string) == "CLOUD_SQL_INSTANCE" && newInstanceType.(string) == "READ_REPLICA_INSTANCE" &&
slices.Contains(oldReplicaNames.([]interface{}), newMasterInstanceName) &&
!slices.Contains(newReplicaNames.([]interface{}), newMasterInstanceName) &&
cascadableReplicaFieldExists && cascadableReplica.(bool)
}

func checkPromoteConfigurations(d *schema.ResourceData) error {
masterInstanceName := d.GetRawConfig().GetAttr("master_instance_name")
replicaConfiguration := d.GetRawConfig().GetAttr("replica_configuration").AsValueSlice()
Expand Down Expand Up @@ -2574,4 +2664,4 @@ func validatePromoteConfigurations(masterInstanceName cty.Value, replicaConfigur
return fmt.Errorf("Replica promote configuration check failed. Please remove replica_configuration and try again.")
}
return nil
}
}
Loading