Skip to content
Merged
5 changes: 5 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ linters:
- pkg: github.com/pingcap/ticdc/pkg/errors
alias: ""

modernize:
# Keep pointer construction consistent with the repository's util.AddressOf convention.
disable:
- newexpr

revive:
rules:
- name: blank-imports
Expand Down
23 changes: 22 additions & 1 deletion api/v2/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,9 @@ type ReplicaConfig struct {
EnableSyncPoint *bool `json:"enable_sync_point,omitempty" toml:"enable-sync-point,omitempty"`
EnableTableMonitor *bool `json:"enable_table_monitor,omitempty" toml:"enable-table-monitor,omitempty"`
BDRMode *bool `json:"bdr_mode,omitempty" toml:"bdr-mode,omitempty"`
// AllowSameCluster allows the downstream to be the same TiDB logical cluster as the upstream.
// By default TiCDC rejects such a changefeed to avoid self-replication loops.
AllowSameCluster *bool `json:"allow_same_cluster,omitempty" toml:"allow-same-cluster,omitempty"`
// EnableActiveActive enables active-active replication mode on top of BDR.
// It requires BDRMode to be true and is only supported by TiDB and storage sinks.
EnableActiveActive *bool `json:"enable_active_active,omitempty" toml:"enable-active-active,omitempty"`
Expand Down Expand Up @@ -295,6 +298,9 @@ func (c *ReplicaConfig) toInternalReplicaConfigWithOriginConfig(
if c.BDRMode != nil {
res.BDRMode = c.BDRMode
}
if c.AllowSameCluster != nil {
res.AllowSameCluster = c.AllowSameCluster
}
if c.EnableActiveActive != nil {
res.EnableActiveActive = c.EnableActiveActive
}
Expand Down Expand Up @@ -366,7 +372,13 @@ func (c *ReplicaConfig) toInternalReplicaConfigWithOriginConfig(
}
if c.Sink != nil {
var dispatchRules []*config.DispatchRule
if c.Sink.DispatchRules != nil {
dispatchRules = make([]*config.DispatchRule, 0, len(c.Sink.DispatchRules))
}
for _, rule := range c.Sink.DispatchRules {
if rule == nil {
continue
}
dispatchRules = append(dispatchRules, &config.DispatchRule{
Matcher: rule.Matcher,
DispatcherRule: "",
Expand Down Expand Up @@ -728,6 +740,7 @@ func ToAPIReplicaConfig(c *config.ReplicaConfig) *ReplicaConfig {
EnableSyncPoint: cloned.EnableSyncPoint,
EnableTableMonitor: cloned.EnableTableMonitor,
BDRMode: cloned.BDRMode,
AllowSameCluster: cloned.AllowSameCluster,
EnableActiveActive: cloned.EnableActiveActive,
}

Expand Down Expand Up @@ -759,7 +772,14 @@ func ToAPIReplicaConfig(c *config.ReplicaConfig) *ReplicaConfig {
}
if cloned.Sink != nil {
var dispatchRules []*DispatchRule
// Clone omits empty slices; use the original to preserve an explicit clear.
if c.Sink.DispatchRules != nil {
dispatchRules = make([]*DispatchRule, 0, len(c.Sink.DispatchRules))
}
for _, rule := range cloned.Sink.DispatchRules {
if rule == nil {
continue
}
dispatchRules = append(dispatchRules, &DispatchRule{
Matcher: rule.Matcher,
PartitionRule: rule.PartitionRule,
Expand Down Expand Up @@ -1232,11 +1252,12 @@ type Table struct {

// SinkConfig represents sink config for a changefeed
// This is a duplicate of config.SinkConfig
// Nil dispatchers preserve stored routes on update; an empty list clears them.
type SinkConfig struct {
Protocol *string `json:"protocol,omitempty" toml:"protocol,omitempty"`
SchemaRegistry *string `json:"schema_registry,omitempty" toml:"schema-registry,omitempty"`
CSVConfig *CSVConfig `json:"csv,omitempty" toml:"csv,omitempty"`
DispatchRules []*DispatchRule `json:"dispatchers,omitempty" toml:"dispatchers,omitempty"`
DispatchRules []*DispatchRule `json:"dispatchers,omitzero" toml:"dispatchers,omitempty"`
ColumnSelectors []*ColumnSelector `json:"column_selectors,omitempty" toml:"column-selectors,omitempty"`
TxnAtomicity *string `json:"transaction_atomicity,omitempty" toml:"transaction-atomicity,omitempty"`
EncoderConcurrency *int `json:"encoder_concurrency,omitempty" toml:"encoder-concurrency,omitempty"`
Expand Down
70 changes: 70 additions & 0 deletions api/v2/model_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,38 @@ func TestSinkConfigDateSeparator(t *testing.T) {
require.ErrorContains(t, err, "CDC:ErrStorageSinkInvalidConfig")
}

func TestSinkDispatchRulesUpdate(t *testing.T) {
storedRules := []*DispatchRule{{Matcher: []string{"src.*"}, TargetSchema: "dst"}}
for _, tc := range []struct {
name string
rules []*DispatchRule
}{
{name: "omitted"},
{name: "clear", rules: []*DispatchRule{}},
{name: "replace", rules: []*DispatchRule{{Matcher: []string{"new_src.*"}, TargetSchema: "new_dst"}}},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := &ReplicaConfig{Sink: &SinkConfig{DispatchRules: tc.rules}}
converted := ToAPIReplicaConfig(cfg.ToInternalReplicaConfig())
require.Equal(t, tc.rules, converted.Sink.DispatchRules)

info, err := (&ChangeFeedInfo{Config: converted}).Clone()
require.NoError(t, err)
require.Equal(t, tc.rules, info.Config.Sink.DispatchRules)

body, err := json.Marshal(info.Config)
require.NoError(t, err)
stored := &ReplicaConfig{Sink: &SinkConfig{DispatchRules: storedRules}}
require.NoError(t, json.Unmarshal(body, stored))
want := tc.rules
if tc.rules == nil {
want = storedRules
}
require.Equal(t, want, stored.Sink.DispatchRules)
})
}
}

func TestChangeFeedInfoCloneWithMaskedSensitiveData(t *testing.T) {
info := &ChangeFeedInfo{
ID: "test",
Expand Down Expand Up @@ -97,6 +129,7 @@ func TestReplicaConfigConversion(t *testing.T) {
EnableSyncPoint: util.AddressOf(true),
EnableTableMonitor: util.AddressOf(true),
BDRMode: util.AddressOf(true),
AllowSameCluster: util.AddressOf(true),
Sink: &SinkConfig{
CloudStorageConfig: &CloudStorageConfig{
UseTableIDAsPath: util.AddressOf(true),
Expand All @@ -115,6 +148,18 @@ func TestReplicaConfigConversion(t *testing.T) {
KafkaConfig: &KafkaConfig{
SASLOAuthCA: util.AddressOf("/etc/ssl/oauth-ca.pem"),
},
DispatchRules: []*DispatchRule{
nil,
{
Matcher: []string{"src.orders"},
TargetSchema: "dst_orders",
},
nil,
{
Matcher: []string{"src.customers"},
TargetSchema: "dst_customers",
},
},
},
Mounter: &MounterConfig{
WorkerNum: util.AddressOf(16),
Expand Down Expand Up @@ -147,6 +192,7 @@ func TestReplicaConfigConversion(t *testing.T) {
require.True(t, util.GetOrZero(internalCfg.EnableSyncPoint))
require.True(t, util.GetOrZero(internalCfg.EnableTableMonitor))
require.True(t, util.GetOrZero(internalCfg.BDRMode))
require.True(t, util.GetOrZero(internalCfg.AllowSameCluster))
require.True(t, util.GetOrZero(internalCfg.Sink.CloudStorageConfig.UseTableIDAsPath))
require.Equal(t, int64(1024), util.GetOrZero(internalCfg.Sink.CloudStorageConfig.SpoolDiskQuota))
require.Equal(t, "/tmp/ticdc-spool", util.GetOrZero(internalCfg.Sink.CloudStorageConfig.SpoolBaseDir))
Expand All @@ -156,6 +202,16 @@ func TestReplicaConfigConversion(t *testing.T) {
require.Equal(t, "hex", util.GetOrZero(internalCfg.Sink.Debezium.BinaryHandlingMode))
require.True(t, util.GetOrZero(internalCfg.Sink.Simple.IncludeStartTs))
require.Equal(t, "/etc/ssl/oauth-ca.pem", util.GetOrZero(internalCfg.Sink.KafkaConfig.SASLOAuthCA))
require.Equal(t, []*config.DispatchRule{
{
Matcher: []string{"src.orders"},
TargetSchema: "dst_orders",
},
{
Matcher: []string{"src.customers"},
TargetSchema: "dst_customers",
},
}, internalCfg.Sink.DispatchRules)
require.Equal(t, internalCfg.Mounter.WorkerNum, *apiCfg.Mounter.WorkerNum)
require.True(t, util.GetOrZero(internalCfg.Scheduler.EnableTableAcrossNodes))
require.Equal(t, 1000, util.GetOrZero(internalCfg.Scheduler.RegionThreshold))
Expand Down Expand Up @@ -194,11 +250,15 @@ func TestReplicaConfigConversion(t *testing.T) {
require.Equal(t, util.GetOrZero(defaultCfg.CaseSensitive), util.GetOrZero(internalCfgNil.CaseSensitive))

// Test case 3: Conversion back to API config
internalCfg.Sink.DispatchRules = append(
[]*config.DispatchRule{nil}, internalCfg.Sink.DispatchRules...)
internalCfg.Sink.DispatchRules = append(internalCfg.Sink.DispatchRules, nil)
apiCfgBack := ToAPIReplicaConfig(internalCfg)
require.Equal(t, config.PerformanceModeLowLatency, util.GetOrZero(apiCfgBack.PerformanceMode))
require.Equal(t, uint64(1024), *apiCfgBack.MemoryQuota)
require.True(t, *apiCfgBack.CaseSensitive)
require.True(t, *apiCfgBack.ForceReplicate)
require.True(t, *apiCfgBack.AllowSameCluster)
require.True(t, *apiCfgBack.IgnoreIneligibleTable)
require.True(t, *apiCfgBack.Sink.CloudStorageConfig.UseTableIDAsPath)
require.Equal(t, int64(1024), *apiCfgBack.Sink.CloudStorageConfig.SpoolDiskQuota)
Expand All @@ -210,6 +270,16 @@ func TestReplicaConfigConversion(t *testing.T) {
require.True(t, util.GetOrZero(apiCfgBack.Sink.SimpleConfig.IncludeStartTs))
require.True(t, util.GetOrZero(apiCfgBack.Sink.DebeziumConfig.OutputOldValue))
require.Equal(t, "/etc/ssl/oauth-ca.pem", util.GetOrZero(apiCfgBack.Sink.KafkaConfig.SASLOAuthCA))
require.Equal(t, []*DispatchRule{
{
Matcher: []string{"src.orders"},
TargetSchema: "dst_orders",
},
{
Matcher: []string{"src.customers"},
TargetSchema: "dst_customers",
},
}, apiCfgBack.Sink.DispatchRules)
require.Equal(t, 16, *apiCfgBack.Mounter.WorkerNum)
require.True(t, *apiCfgBack.Scheduler.EnableTableAcrossNodes)
require.Equal(t, "correctness", *apiCfgBack.Integrity.IntegrityCheckLevel)
Expand Down
88 changes: 88 additions & 0 deletions cmd/cdc/cli/cli_changefeed_update_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package cli
import (
"bytes"
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
Expand All @@ -24,6 +25,7 @@ import (
"github.com/golang/mock/gomock"
"github.com/pingcap/log"
v2 "github.com/pingcap/ticdc/api/v2"
"github.com/pingcap/ticdc/pkg/check"
"github.com/pingcap/ticdc/pkg/config"
"github.com/pingcap/ticdc/pkg/errors"
"github.com/pingcap/ticdc/pkg/util"
Expand Down Expand Up @@ -191,6 +193,92 @@ func TestChangefeedUpdateCli(t *testing.T) {
require.NotNil(t, o.run(cmd))
}

func TestSameClusterUpdateConfigs(t *testing.T) {
replica := config.GetDefaultReplicaConfig()
replica.AllowSameCluster = new(true)
replica.Filter.Rules = []string{"src.*"}
replica.Sink.DispatchRules = []*config.DispatchRule{
{Matcher: []string{"src.*"}, TargetSchema: "dst", TargetTable: "{table}_copy"},
}
original := v2.ToAPIReplicaConfig(replica)

for _, tc := range []struct {
name string
config string
wantAllowSameCluster bool
wantFilterRules []string
wantDispatchRules []*v2.DispatchRule
}{
{
name: "replace filter and routing",
config: `allow-same-cluster = true
[filter]
rules = ['new_src.*']
[[sink.dispatchers]]
matcher = ['new_src.*']
target-schema = 'new_dst'
target-table = '{table}_routed'
`,
wantAllowSameCluster: true,
wantFilterRules: []string{"new_src.*"},
wantDispatchRules: []*v2.DispatchRule{
{Matcher: []string{"new_src.*"}, TargetSchema: "new_dst", TargetTable: "{table}_routed"},
},
},
{
name: "preserve omitted same-cluster configuration",
config: "memory-quota = 2097152\n",
wantAllowSameCluster: true,
wantFilterRules: original.Filter.Rules,
wantDispatchRules: original.Sink.DispatchRules,
},
{
name: "disable same-cluster replication",
config: "allow-same-cluster = false\n",
wantAllowSameCluster: false,
wantFilterRules: original.Filter.Rules,
wantDispatchRules: original.Sink.DispatchRules,
},
{
name: "clear routing",
config: "[sink]\ndispatchers = []\n",
wantAllowSameCluster: true,
wantFilterRules: original.Filter.Rules,
wantDispatchRules: []*v2.DispatchRule{},
},
} {
t.Run(tc.name, func(t *testing.T) {
oldInfo := &v2.ChangeFeedInfo{Config: v2.ToAPIReplicaConfig(replica)}
configPath := filepath.Join(t.TempDir(), "cf.toml")
require.NoError(t, os.WriteFile(configPath, []byte(tc.config), 0o644))
cmd := NewCmdCli()
o := newUpdateChangefeedOptions(newChangefeedCommonOptions())
o.addFlags(cmd)
require.NoError(t, cmd.ParseFlags([]string{"--config=" + configPath}))
updated, err := o.applyChanges(oldInfo, cmd)
require.NoError(t, err)
require.Equal(t, new(tc.wantAllowSameCluster), updated.Config.AllowSameCluster)
require.Equal(t, tc.wantFilterRules, updated.Config.Filter.Rules)
require.Equal(t, tc.wantDispatchRules, updated.Config.Sink.DispatchRules)
require.Equal(t, original, oldInfo.Config)

body, err := json.Marshal(o.getChangefeedConfig(cmd, updated))
require.NoError(t, err)
// The API applies the serialized request to the stored configuration.
request := &v2.ChangefeedConfig{ReplicaConfig: v2.ToAPIReplicaConfig(replica)}
require.NoError(t, json.Unmarshal(body, request))
require.Equal(t, tc.wantDispatchRules, request.ReplicaConfig.Sink.DispatchRules)
info := &config.ChangeFeedInfo{Config: request.ReplicaConfig.ToInternalReplicaConfig()}
err = check.ValidateSameClusterRouting(info.ToChangefeedConfig())
if tc.wantAllowSameCluster && len(tc.wantDispatchRules) == 0 {
require.True(t, errors.ErrInvalidReplicaConfig.Equal(err), "%v", err)
} else {
require.NoError(t, err)
}
})
}
}

func TestChangefeedUpdateReplicaCredentials(t *testing.T) {
for _, tc := range []struct {
name string
Expand Down
24 changes: 19 additions & 5 deletions pkg/check/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ var (
// because it can easily lead to self-replication loops.
//
// Compatibility and trade-offs:
// - If the changefeed config sets `allow-same-cluster = true`, the check is skipped and this
// returns false, so that creating/updating/resuming the changefeed is not blocked.
// - If the sink is not TiDB, or the downstream `cluster_id` is unavailable, this returns false (keep legacy behavior).
// - In TiDB Next-Gen, multiple keyspaces share the same physical `cluster_id`. When the downstream keyspace
// can be determined, we treat (cluster_id, keyspace) as the cluster identity to allow cross-keyspace replication.
Expand All @@ -49,11 +51,23 @@ var (
func IsSameUpstreamDownstream(
ctx context.Context, upPD pd.Client, changefeedCfg *config.ChangefeedConfig,
) (bool, error) {
if upPD == nil {
return false, cerrors.New("pd client is nil")
}
if changefeedCfg == nil {
return false, cerrors.New("changefeed config is nil")
return false, cerrors.ErrInternalCheckFailed.GenWithStackByArgs("changefeed config is nil")
}
// The user explicitly opted out of this verification, report "not same" so that the callers
// proceed. The flag only makes the changefeed safe when its routing rules keep every replicated
// table outside the filter, so the validation runs here, on the configuration in use.
if changefeedCfg.AllowSameCluster {
if err := ValidateSameClusterRouting(changefeedCfg); err != nil {
return false, err
}
log.Warn("skip the upstream/downstream cluster verification because allow-same-cluster is enabled",
zap.String("changefeedID", changefeedCfg.ChangefeedID.Name()),
zap.String("sinkURI", util.MaskSensitiveDataInURI(changefeedCfg.SinkURI)))
return false, nil
}
if upPD == nil {
return false, cerrors.ErrInternalCheckFailed.GenWithStackByArgs("pd client is nil")
}

upID := upPD.GetClusterID(ctx)
Expand Down Expand Up @@ -175,7 +189,7 @@ func getTiDBKeyspaceName(ctx context.Context, db *sql.DB) (string, error) {
continue
}
if value != keyspace {
return "", cerrors.New("downstream TiDB reports inconsistent keyspace-name across instances")
return "", cerrors.ErrInternalCheckFailed.GenWithStack("downstream TiDB reports inconsistent keyspace-name across instances, got %s and %s", keyspace, value)
}
}
if err := rows.Err(); err != nil {
Expand Down
Loading
Loading