diff --git a/cmd/kafka-consumer/writer.go b/cmd/kafka-consumer/writer.go index cd8807e4e3..ea0432c0a6 100644 --- a/cmd/kafka-consumer/writer.go +++ b/cmd/kafka-consumer/writer.go @@ -136,7 +136,7 @@ func newWriter(ctx context.Context, o *option) *writer { SinkURI: o.downstreamURI, SinkConfig: o.sinkConfig, } - w.mysqlSink, err = sink.New(ctx, cfg, changefeedID) + w.mysqlSink, err = sink.New(ctx, cfg, changefeedID, commonType.DefaultKeyspaceID) if err != nil { log.Panic("cannot create the mysql sink", zap.Error(err)) } diff --git a/cmd/pulsar-consumer/writer.go b/cmd/pulsar-consumer/writer.go index c2767191a8..9da883e1f2 100644 --- a/cmd/pulsar-consumer/writer.go +++ b/cmd/pulsar-consumer/writer.go @@ -128,7 +128,7 @@ func newWriter(ctx context.Context, o *option) *writer { SinkURI: o.downstreamURI, SinkConfig: o.replicaConfig.Sink, } - w.mysqlSink, err = sink.New(ctx, cfg, changefeedID) + w.mysqlSink, err = sink.New(ctx, cfg, changefeedID, commonType.DefaultKeyspaceID) if err != nil { log.Panic("cannot create the mysql sink", zap.Error(err)) } diff --git a/cmd/storage-consumer/consumer.go b/cmd/storage-consumer/consumer.go index e6e13f6cd4..072cccb0e9 100644 --- a/cmd/storage-consumer/consumer.go +++ b/cmd/storage-consumer/consumer.go @@ -148,7 +148,12 @@ func newConsumer(ctx context.Context) (*consumer, error) { SinkURI: downstreamURIStr, SinkConfig: replicaConfig.Sink, } - sink, err := sink.New(stdCtx, cfg, commonType.NewChangeFeedIDWithName(defaultChangefeedName, commonType.DefaultKeyspaceName)) + sink, err := sink.New( + stdCtx, + cfg, + commonType.NewChangeFeedIDWithName(defaultChangefeedName, commonType.DefaultKeyspaceName), + commonType.DefaultKeyspaceID, + ) if err != nil { log.Error("failed to create sink", zap.Error(err)) return nil, err diff --git a/coordinator/changefeed/changefeed_db.go b/coordinator/changefeed/changefeed_db.go index f369ed9761..db0e50a122 100644 --- a/coordinator/changefeed/changefeed_db.go +++ b/coordinator/changefeed/changefeed_db.go @@ -150,8 +150,16 @@ func (db *ChangefeedDB) StopByChangefeedID(cfID common.ChangeFeedID, remove bool db.stopped[cfID] = cf } - metrics.ChangefeedStatusGauge.DeleteLabelValues(cfID.Keyspace(), cfID.Name()) - metrics.DeleteChangefeedCheckpointMetrics(cfID.Keyspace(), cfID.Name()) + keyspaceID := common.DefaultKeyspaceID + if info := cf.GetInfo(); info != nil { + keyspaceID = info.KeyspaceID + } + metrics.ChangefeedStatusGauge.DeleteLabelValues( + cfID.Keyspace(), + cfID.Name(), + metrics.FormatKeyspaceID(keyspaceID), + ) + metrics.DeleteChangefeedCheckpointMetrics(cfID.Keyspace(), cfID.Name(), keyspaceID) return nodeID } diff --git a/coordinator/changefeed/changefeed_db_test.go b/coordinator/changefeed/changefeed_db_test.go index b7df02de80..a48d43fc5d 100644 --- a/coordinator/changefeed/changefeed_db_test.go +++ b/coordinator/changefeed/changefeed_db_test.go @@ -140,16 +140,26 @@ func TestStopByChangefeedIDDeletesCheckpointMetrics(t *testing.T) { t.Cleanup(metrics.ResetOwnerChangefeedMetrics) db := NewChangefeedDB(1216) - cf := &Changefeed{ID: common.NewChangeFeedIDWithName("test-metrics", common.DefaultKeyspaceName)} + cfID := common.NewChangeFeedIDWithName("test-metrics", common.DefaultKeyspaceName) + cf := NewChangefeed(cfID, &config.ChangeFeedInfo{ + ChangefeedID: cfID, + KeyspaceID: 123, + Config: config.GetDefaultReplicaConfig(), + SinkURI: "blackhole://", + State: config.StateNormal, + }, 100, false) db.AddReplicatingMaintainer(cf, "node1") + metrics.ChangefeedStatusGauge.WithLabelValues(cf.ID.Keyspace(), cf.ID.Name(), "123").Set(1) metrics.ChangefeedCheckpointTsGauge.WithLabelValues(cf.ID.Keyspace(), cf.ID.Name()).Set(100) - metrics.ChangefeedCheckpointTsLagGauge.WithLabelValues(cf.ID.Keyspace(), cf.ID.Name()).Set(10) + metrics.ChangefeedCheckpointTsLagGauge.WithLabelValues(cf.ID.Keyspace(), cf.ID.Name(), "123").Set(10) + require.Equal(t, 1, testutil.CollectAndCount(metrics.ChangefeedStatusGauge)) require.Equal(t, 1, testutil.CollectAndCount(metrics.ChangefeedCheckpointTsGauge)) require.Equal(t, 1, testutil.CollectAndCount(metrics.ChangefeedCheckpointTsLagGauge)) require.Equal(t, node.ID("node1"), db.StopByChangefeedID(cf.ID, true)) + require.Equal(t, 0, testutil.CollectAndCount(metrics.ChangefeedStatusGauge)) require.Equal(t, 0, testutil.CollectAndCount(metrics.ChangefeedCheckpointTsGauge)) require.Equal(t, 0, testutil.CollectAndCount(metrics.ChangefeedCheckpointTsLagGauge)) } diff --git a/coordinator/controller.go b/coordinator/controller.go index 50ee236857..39114c7a7d 100644 --- a/coordinator/controller.go +++ b/coordinator/controller.go @@ -264,11 +264,16 @@ func (c *Controller) collectMetrics(ctx context.Context) error { changefeedDownstreamTypeCache[displayName] = downstreamType metrics.ChangefeedDownstreamInfoGauge.WithLabelValues(keyspace, name, downstreamType).Set(1) - metrics.ChangefeedStatusGauge.WithLabelValues(keyspace, name).Set(float64(info.State.ToInt())) + metrics.ChangefeedStatusGauge.WithLabelValues( + keyspace, + name, + metrics.FormatKeyspaceID(info.KeyspaceID), + ).Set(float64(info.State.ToInt())) if !updateChangefeedCheckpointMetrics( keyspace, name, + info.KeyspaceID, info.State, cf.GetLastSavedCheckPointTs(), c.pdClock.CurrentTime(), @@ -324,13 +329,14 @@ func (c *Controller) collectMetrics(ctx context.Context) error { func updateChangefeedCheckpointMetrics( keyspace string, name string, + keyspaceID uint32, state config.FeedState, checkpointTs uint64, pdTime time.Time, ) bool { switch state { case config.StateStopped, config.StateFinished, config.StateRemoved: - metrics.DeleteChangefeedCheckpointMetrics(keyspace, name) + metrics.DeleteChangefeedCheckpointMetrics(keyspace, name, keyspaceID) return false } @@ -338,7 +344,11 @@ func updateChangefeedCheckpointMetrics( phyCkpTs := oracle.ExtractPhysical(checkpointTs) lag := float64(pdPhysicalTime-phyCkpTs) / 1e3 metrics.ChangefeedCheckpointTsGauge.WithLabelValues(keyspace, name).Set(float64(phyCkpTs)) - metrics.ChangefeedCheckpointTsLagGauge.WithLabelValues(keyspace, name).Set(lag) + metrics.ChangefeedCheckpointTsLagGauge.WithLabelValues( + keyspace, + name, + metrics.FormatKeyspaceID(keyspaceID), + ).Set(lag) return true } diff --git a/coordinator/controller_test.go b/coordinator/controller_test.go index 899e9911ce..c378c067b6 100644 --- a/coordinator/controller_test.go +++ b/coordinator/controller_test.go @@ -59,12 +59,14 @@ func TestUpdateChangefeedCheckpointMetricsDeletesFinishedLabels(t *testing.T) { keyspace := common.DefaultKeyspaceName name := "finished-metrics" + keyspaceID := uint32(123) pdTime := time.UnixMilli(2000) checkpointTs := oracle.ComposeTS(1000, 0) require.True(t, updateChangefeedCheckpointMetrics( keyspace, name, + keyspaceID, config.StateNormal, checkpointTs, pdTime, @@ -75,6 +77,7 @@ func TestUpdateChangefeedCheckpointMetricsDeletesFinishedLabels(t *testing.T) { require.False(t, updateChangefeedCheckpointMetrics( keyspace, name, + keyspaceID, config.StateFinished, checkpointTs, pdTime, diff --git a/downstreamadapter/dispatchermanager/dispatcher_manager.go b/downstreamadapter/dispatchermanager/dispatcher_manager.go index baa8c72fbf..f1a77d0d37 100644 --- a/downstreamadapter/dispatchermanager/dispatcher_manager.go +++ b/downstreamadapter/dispatchermanager/dispatcher_manager.go @@ -283,7 +283,7 @@ func NewDispatcherManager( } } - createdSink, err := sink.New(ctx, manager.config, manager.changefeedID) + createdSink, err := sink.New(ctx, manager.config, manager.changefeedID, manager.keyspaceID) if err != nil { return nil, errors.Trace(err) } diff --git a/downstreamadapter/sink/blackhole/sink.go b/downstreamadapter/sink/blackhole/sink.go index 984b2d3079..6124219ad4 100644 --- a/downstreamadapter/sink/blackhole/sink.go +++ b/downstreamadapter/sink/blackhole/sink.go @@ -31,10 +31,10 @@ type Sink struct { statistics *metrics.Statistics } -func New(changefeedID common.ChangeFeedID) (*Sink, error) { +func New(changefeedID common.ChangeFeedID, keyspaceID uint32) (*Sink, error) { return &Sink{ eventCh: chann.NewUnlimitedChannelDefault[*commonEvent.DMLEvent](), - statistics: metrics.NewStatistics(changefeedID, "sink"), + statistics: metrics.NewStatistics(changefeedID, keyspaceID, "sink"), }, nil } diff --git a/downstreamadapter/sink/blackhole/sink_test.go b/downstreamadapter/sink/blackhole/sink_test.go index cd36457bf1..0c0c047e5e 100644 --- a/downstreamadapter/sink/blackhole/sink_test.go +++ b/downstreamadapter/sink/blackhole/sink_test.go @@ -26,7 +26,7 @@ import ( // Test callback and tableProgress works as expected after AddDMLEvent func TestBlacHoleSinkBasicFunctionality(t *testing.T) { - sink, err := New(common.NewChangefeedID(common.DefaultKeyspaceName)) + sink, err := New(common.NewChangefeedID(common.DefaultKeyspaceName), common.DefaultKeyspaceID) ctx, cancel := context.WithCancel(context.Background()) defer cancel() go sink.Run(ctx) @@ -91,7 +91,7 @@ func TestBlacHoleSinkBasicFunctionality(t *testing.T) { } func TestBlackHoleSinkBatchConfig(t *testing.T) { - sink, err := New(common.NewChangefeedID(common.DefaultKeyspaceName)) + sink, err := New(common.NewChangefeedID(common.DefaultKeyspaceName), common.DefaultKeyspaceID) require.NoError(t, err) require.Equal(t, 4096, sink.BatchCount()) require.Zero(t, sink.BatchBytes()) diff --git a/downstreamadapter/sink/cloudstorage/sink.go b/downstreamadapter/sink/cloudstorage/sink.go index dfb9b232da..eb5519772a 100644 --- a/downstreamadapter/sink/cloudstorage/sink.go +++ b/downstreamadapter/sink/cloudstorage/sink.go @@ -102,6 +102,7 @@ func Verify(ctx context.Context, changefeedID common.ChangeFeedID, sinkURI *url. func New( ctx context.Context, changefeedID common.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, enableTableAcrossNodes bool, cleanupJobs []func(), /* only for test */ + keyspaceID uint32, ) (*sink, error) { // create cloud storage config and then apply the params of sinkURI to it. cfg := cloudstorage.NewConfig() @@ -126,7 +127,7 @@ func New( if err != nil { return nil, err } - statistics := metrics.NewStatistics(changefeedID, "cloudstorage") + statistics := metrics.NewStatistics(changefeedID, keyspaceID, "cloudstorage") defer func() { if err != nil { statistics.Close() diff --git a/downstreamadapter/sink/cloudstorage/sink_test.go b/downstreamadapter/sink/cloudstorage/sink_test.go index 5a44dd400a..7ea81044d7 100644 --- a/downstreamadapter/sink/cloudstorage/sink_test.go +++ b/downstreamadapter/sink/cloudstorage/sink_test.go @@ -47,7 +47,7 @@ func newSinkForTest( cleanUpJobs []func(), ) (*sink, error) { changefeedID := common.NewChangefeedID4Test("test", "test") - result, err := New(ctx, changefeedID, sinkURI, replicaConfig.Sink, true, cleanUpJobs) + result, err := New(ctx, changefeedID, sinkURI, replicaConfig.Sink, true, cleanUpJobs, common.DefaultKeyspaceID) if err != nil { return nil, err } @@ -667,7 +667,7 @@ func TestCloseBeforeRunDoesNotPanicAndCleansSpool(t *testing.T) { setPDClockForTest(t, pdutil.NewClock4Test()) changefeedID := common.NewChangefeedID4Test("test", "close-before-run") - cloudStorageSink, err := New(ctx, changefeedID, sinkURI, replicaConfig.Sink, true, nil) + cloudStorageSink, err := New(ctx, changefeedID, sinkURI, replicaConfig.Sink, true, nil, common.DefaultKeyspaceID) require.NoError(t, err) spoolDir := filepath.Join(spoolBaseDir, changefeedID.Keyspace(), changefeedID.Name()) diff --git a/downstreamadapter/sink/cloudstorage/writer_test.go b/downstreamadapter/sink/cloudstorage/writer_test.go index 250c7b00a6..5bbcf578af 100644 --- a/downstreamadapter/sink/cloudstorage/writer_test.go +++ b/downstreamadapter/sink/cloudstorage/writer_test.go @@ -59,7 +59,7 @@ func testWriter(ctx context.Context, t *testing.T, dir string) *writer { require.NoError(t, err) changefeedID := commonType.NewChangefeedID4Test("test", t.Name()) - statistics := metrics.NewStatistics(changefeedID, t.Name()) + statistics := metrics.NewStatistics(changefeedID, commonType.DefaultKeyspaceID, t.Name()) spoolBuffer := newTestSpool(t, changefeedID, cfg) d := newWriter(1, changefeedID, storage, cfg, ".json", statistics, spoolBuffer) @@ -483,7 +483,7 @@ func TestWriterStoresPendingMessagesInSpoolBeforeFlush(t *testing.T) { cfg.FlushInterval = time.Hour changefeedID := commonType.NewChangefeedID4Test("test", "spool-pending") - statistics := metrics.NewStatistics(changefeedID, t.Name()) + statistics := metrics.NewStatistics(changefeedID, commonType.DefaultKeyspaceID, t.Name()) setPDClockForTest(t, pdutil.NewClock4Test()) spoolBuffer := newTestSpool(t, changefeedID, cfg) @@ -651,7 +651,7 @@ func TestWriterIndexWriteError(t *testing.T) { cfg.FlushInterval = time.Hour changefeedID := commonType.NewChangefeedID4Test("test", "writer-error-metric") - statistics := metrics.NewStatistics(changefeedID, t.Name()) + statistics := metrics.NewStatistics(changefeedID, commonType.DefaultKeyspaceID, t.Name()) setPDClockForTest(t, pdutil.NewClock4Test()) spoolBuffer := newTestSpool(t, changefeedID, cfg) d := newWriter(1, changefeedID, storage, cfg, ".json", statistics, spoolBuffer) @@ -716,7 +716,7 @@ func TestWriterDataFileCloseError(t *testing.T) { cfg.FlushInterval = time.Hour changefeedID := commonType.NewChangefeedID4Test("test", "writer-close-error") - statistics := metrics.NewStatistics(changefeedID, t.Name()) + statistics := metrics.NewStatistics(changefeedID, commonType.DefaultKeyspaceID, t.Name()) setPDClockForTest(t, pdutil.NewClock4Test()) spoolBuffer := newTestSpool(t, changefeedID, cfg) d := newWriter(1, changefeedID, storage, cfg, ".json", statistics, spoolBuffer) diff --git a/downstreamadapter/sink/kafka/sink.go b/downstreamadapter/sink/kafka/sink.go index 2f5f7dd005..cc104292ea 100644 --- a/downstreamadapter/sink/kafka/sink.go +++ b/downstreamadapter/sink/kafka/sink.go @@ -74,18 +74,19 @@ func Verify(ctx context.Context, changefeedID commonType.ChangeFeedID, uri *url. } func New( - ctx context.Context, changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, + ctx context.Context, changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, keyspaceID uint32, ) (*sink, error) { comp, protocol, err := newKafkaSinkComponent(ctx, changefeedID, sinkURI, sinkConfig) if err != nil { return nil, errors.Trace(err) } - return newWithComponents(ctx, changefeedID, protocol, comp) + return newWithComponents(ctx, changefeedID, keyspaceID, protocol, comp) } func newWithComponents( ctx context.Context, changefeedID commonType.ChangeFeedID, + keyspaceID uint32, protocol config.Protocol, comp components, ) (*sink, error) { @@ -106,7 +107,7 @@ func newWithComponents( } }() - statistics := metrics.NewStatistics(changefeedID, "sink") + statistics := metrics.NewStatistics(changefeedID, keyspaceID, "sink") asyncProducer, err = comp.factory.AsyncProducer(ctx) if err != nil { return nil, err diff --git a/downstreamadapter/sink/kafka/sink_test.go b/downstreamadapter/sink/kafka/sink_test.go index 7d46286e27..440806501c 100644 --- a/downstreamadapter/sink/kafka/sink_test.go +++ b/downstreamadapter/sink/kafka/sink_test.go @@ -138,7 +138,7 @@ func newKafkaSinkForTestWithProducers(ctx context.Context, } }() - s, err := newWithComponents(ctx, changefeedID, protocol, comp) + s, err := newWithComponents(ctx, changefeedID, common.DefaultKeyspaceID, protocol, comp) if err != nil { return nil, err } diff --git a/downstreamadapter/sink/mysql/sink.go b/downstreamadapter/sink/mysql/sink.go index 3a0c0966a9..2856d5fce4 100644 --- a/downstreamadapter/sink/mysql/sink.go +++ b/downstreamadapter/sink/mysql/sink.go @@ -95,6 +95,7 @@ func New( changefeedID common.ChangeFeedID, config *config.ChangefeedConfig, sinkURI *url.URL, + keyspaceID uint32, ) (*Sink, error) { cfg, dmlDB, controlDB, err := mysql.NewMysqlConfigAndDBs(ctx, changefeedID, sinkURI, config) if err != nil { @@ -112,7 +113,7 @@ func New( metrics.ChangefeedDownstreamIsTiDBGauge.DeleteLabelValues(keyspace, name) } - return newMySQLSinkWithControlDB(ctx, changefeedID, cfg, dmlDB, controlDB, config.BDRMode, config.EnableActiveActive, config.ActiveActiveProgressInterval), nil + return newMySQLSinkWithControlDB(ctx, changefeedID, cfg, dmlDB, controlDB, config.BDRMode, config.EnableActiveActive, config.ActiveActiveProgressInterval, keyspaceID), nil } func NewMySQLSink( @@ -123,8 +124,9 @@ func NewMySQLSink( bdrMode bool, enableActiveActive bool, progressInterval time.Duration, + keyspaceID uint32, ) *Sink { - return newMySQLSinkWithDBs(ctx, changefeedID, cfg, db, db, bdrMode, enableActiveActive, progressInterval) + return newMySQLSinkWithDBs(ctx, changefeedID, cfg, db, db, bdrMode, enableActiveActive, progressInterval, keyspaceID) } // newMySQLSinkWithControlDB creates a MySQL sink with separate pools for DML and @@ -140,8 +142,9 @@ func newMySQLSinkWithControlDB( bdrMode bool, enableActiveActive bool, progressInterval time.Duration, + keyspaceID uint32, ) *Sink { - return newMySQLSinkWithDBs(ctx, changefeedID, cfg, dmlDB, controlDB, bdrMode, enableActiveActive, progressInterval) + return newMySQLSinkWithDBs(ctx, changefeedID, cfg, dmlDB, controlDB, bdrMode, enableActiveActive, progressInterval, keyspaceID) } func newMySQLSinkWithDBs( @@ -153,8 +156,9 @@ func newMySQLSinkWithDBs( bdrMode bool, enableActiveActive bool, progressInterval time.Duration, + keyspaceID uint32, ) *Sink { - stat := metrics.NewStatistics(changefeedID, "TxnSink") + stat := metrics.NewStatistics(changefeedID, keyspaceID, "TxnSink") var activeActiveSyncStatsCollector *mysql.ActiveActiveSyncStatsCollector if enableActiveActive && cfg.IsTiDB && cfg.ActiveActiveSyncStatsInterval > 0 { diff --git a/downstreamadapter/sink/mysql/sink_test.go b/downstreamadapter/sink/mysql/sink_test.go index 3b71302424..d1da54d9e7 100644 --- a/downstreamadapter/sink/mysql/sink_test.go +++ b/downstreamadapter/sink/mysql/sink_test.go @@ -39,7 +39,7 @@ func getMysqlSink() (context.Context, *Sink, sqlmock.Sqlmock) { cfg.MaxAllowedPacket = int64(vardef.DefMaxAllowedPacket) cfg.CachePrepStmts = false - sink := NewMySQLSink(ctx, changefeedID, cfg, db, false, false, time.Minute) + sink := NewMySQLSink(ctx, changefeedID, cfg, db, false, false, time.Minute, common.DefaultKeyspaceID) return ctx, sink, mock } @@ -55,7 +55,7 @@ func getMysqlSinkWithDDLTs() (context.Context, *Sink, sqlmock.Sqlmock) { cfg.CachePrepStmts = false cfg.EnableDDLTs = true // Enable DDL-ts feature for testing - sink := NewMySQLSink(ctx, changefeedID, cfg, db, false, false, time.Minute) + sink := NewMySQLSink(ctx, changefeedID, cfg, db, false, false, time.Minute, common.DefaultKeyspaceID) return ctx, sink, mock } @@ -75,7 +75,7 @@ func getMysqlSinkWithSeparateDBs(t *testing.T) (context.Context, *Sink, sqlmock. cfg.MaxAllowedPacket = int64(vardef.DefMaxAllowedPacket) cfg.CachePrepStmts = false - sink := newMySQLSinkWithControlDB(ctx, changefeedID, cfg, dmlDB, controlDB, false, false, time.Minute) + sink := newMySQLSinkWithControlDB(ctx, changefeedID, cfg, dmlDB, controlDB, false, false, time.Minute, common.DefaultKeyspaceID) return ctx, sink, dmlMock, controlMock } diff --git a/downstreamadapter/sink/pulsar/sink.go b/downstreamadapter/sink/pulsar/sink.go index 5aae70bb2f..91c1d71729 100644 --- a/downstreamadapter/sink/pulsar/sink.go +++ b/downstreamadapter/sink/pulsar/sink.go @@ -77,7 +77,7 @@ func Verify(ctx context.Context, changefeedID commonType.ChangeFeedID, uri *url. } func New( - ctx context.Context, changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, + ctx context.Context, changefeedID commonType.ChangeFeedID, sinkURI *url.URL, sinkConfig *config.SinkConfig, keyspaceID uint32, ) (*sink, error) { comp, protocol, err := newPulsarSinkComponent(ctx, changefeedID, sinkURI, sinkConfig) if err != nil { @@ -86,6 +86,7 @@ func New( return newWithComponent( ctx, changefeedID, + keyspaceID, sinkConfig, comp, protocol, @@ -121,6 +122,7 @@ func newPulsarDDLProducer( func newWithComponent( ctx context.Context, changefeedID commonType.ChangeFeedID, + keyspaceID uint32, sinkConfig *config.SinkConfig, comp component, protocol config.Protocol, @@ -148,7 +150,7 @@ func newWithComponent( }() failpointCh := make(chan error, 1) - statistics = metrics.NewStatistics(changefeedID, "pulsar") + statistics = metrics.NewStatistics(changefeedID, keyspaceID, "pulsar") dmlProducer, err = newDMLProducer(changefeedID, comp, failpointCh) if err != nil { return nil, err diff --git a/downstreamadapter/sink/pulsar/sink_test.go b/downstreamadapter/sink/pulsar/sink_test.go index a433fd4b9d..973e4f15e6 100644 --- a/downstreamadapter/sink/pulsar/sink_test.go +++ b/downstreamadapter/sink/pulsar/sink_test.go @@ -48,7 +48,7 @@ func newPulsarSinkForTest(t *testing.T) (*sink, error) { comp, protocol, err := newPulsarSinkComponentForTest(ctx, changefeedID, sinkURI, replicaConfig.Sink) require.NoError(t, err) - statistics := metrics.NewStatistics(changefeedID, "sink") + statistics := metrics.NewStatistics(changefeedID, common.DefaultKeyspaceID, "sink") pulsarSink := &sink{ changefeedID: changefeedID, dmlProducer: newMockDMLProducer(), @@ -150,6 +150,7 @@ func TestPulsarSinkNewWithComponentReturnsDMLProducerError(t *testing.T) { _, err = newWithComponent( context.Background(), changefeedID, + common.DefaultKeyspaceID, &config.SinkConfig{}, component{}, config.ProtocolCanalJSON, @@ -178,6 +179,7 @@ func TestPulsarSinkNewWithComponentReturnsDDLProducerError(t *testing.T) { _, err = newWithComponent( context.Background(), changefeedID, + common.DefaultKeyspaceID, &config.SinkConfig{}, component{}, config.ProtocolCanalJSON, diff --git a/downstreamadapter/sink/sink.go b/downstreamadapter/sink/sink.go index 47e29be55a..7231a144b7 100644 --- a/downstreamadapter/sink/sink.go +++ b/downstreamadapter/sink/sink.go @@ -50,7 +50,7 @@ type Sink interface { BatchBytes() int } -func New(ctx context.Context, cfg *config.ChangefeedConfig, changefeedID common.ChangeFeedID) (Sink, error) { +func New(ctx context.Context, cfg *config.ChangefeedConfig, changefeedID common.ChangeFeedID, keyspaceID uint32) (Sink, error) { sinkURI, err := url.Parse(cfg.SinkURI) if err != nil { return nil, errors.WrapError( @@ -61,15 +61,15 @@ func New(ctx context.Context, cfg *config.ChangefeedConfig, changefeedID common. scheme := config.GetScheme(sinkURI) switch scheme { case config.MySQLScheme, config.MySQLSSLScheme, config.TiDBScheme, config.TiDBSSLScheme: - return mysql.New(ctx, changefeedID, cfg, sinkURI) + return mysql.New(ctx, changefeedID, cfg, sinkURI, keyspaceID) case config.KafkaScheme, config.KafkaSSLScheme: - return kafka.New(ctx, changefeedID, sinkURI, cfg.SinkConfig) + return kafka.New(ctx, changefeedID, sinkURI, cfg.SinkConfig, keyspaceID) case config.PulsarScheme, config.PulsarSSLScheme, config.PulsarHTTPScheme, config.PulsarHTTPSScheme: - return pulsar.New(ctx, changefeedID, sinkURI, cfg.SinkConfig) + return pulsar.New(ctx, changefeedID, sinkURI, cfg.SinkConfig, keyspaceID) case config.S3Scheme, config.FileScheme, config.GCSScheme, config.GSScheme, config.AzblobScheme, config.AzureScheme, config.CloudStorageNoopScheme: - return cloudstorage.New(ctx, changefeedID, sinkURI, cfg.SinkConfig, cfg.EnableTableAcrossNodes, nil) + return cloudstorage.New(ctx, changefeedID, sinkURI, cfg.SinkConfig, cfg.EnableTableAcrossNodes, nil, keyspaceID) case config.BlackHoleScheme: - return blackhole.New(changefeedID) + return blackhole.New(changefeedID, keyspaceID) } return nil, errors.ErrSinkURIInvalid.GenWithStackByArgs( util.MaskSensitiveDataInURIForError(sinkURI.String())) diff --git a/downstreamadapter/sink/sink_test.go b/downstreamadapter/sink/sink_test.go index 0d812aa533..48c347da9a 100644 --- a/downstreamadapter/sink/sink_test.go +++ b/downstreamadapter/sink/sink_test.go @@ -30,7 +30,7 @@ func TestUnknownSchemeMasksSensitiveSinkURI(t *testing.T) { SinkURI: "unknown://127.0.0.1:9092/topic?sasl-password=verysecure&access-key=rawkey", } - _, err := New(context.Background(), cfg, changefeedID) + _, err := New(context.Background(), cfg, changefeedID, common.DefaultKeyspaceID) require.Error(t, err) requireMaskedSinkURIError(t, err) @@ -47,7 +47,7 @@ func TestParseErrorMasksSensitiveSinkURI(t *testing.T) { SinkURI: "mysql://root:verysecure@127.0.0.1/%zz", } - _, err := New(context.Background(), cfg, changefeedID) + _, err := New(context.Background(), cfg, changefeedID, common.DefaultKeyspaceID) require.Error(t, err) requireInvalidSinkURIError(t, err) diff --git a/pkg/applier/redo.go b/pkg/applier/redo.go index adb914f4a9..f53d8e928e 100644 --- a/pkg/applier/redo.go +++ b/pkg/applier/redo.go @@ -483,7 +483,13 @@ func (ra *RedoApplier) Apply(egCtx context.Context) (err error) { SinkConfig: &config.SinkConfig{}, } if ra.mysqlSink == nil { - ra.mysqlSink, err = mysql.New(egCtx, ra.rd.GetChangefeedID(), replicaConfig, sinkURI) + ra.mysqlSink, err = mysql.New( + egCtx, + ra.rd.GetChangefeedID(), + replicaConfig, + sinkURI, + commonType.DefaultKeyspaceID, + ) if err != nil { return err } diff --git a/pkg/applier/redo_test.go b/pkg/applier/redo_test.go index 726d48a373..24febac42d 100644 --- a/pkg/applier/redo_test.go +++ b/pkg/applier/redo_test.go @@ -377,7 +377,7 @@ func TestApply(t *testing.T) { sinkURI, err := url.Parse(cfg.SinkURI) require.NoError(t, err) mysqlCfg.Apply(sinkURI, cfg.ChangefeedID, cfg) - ap.mysqlSink = dmysql.NewMySQLSink(ctx, cfg.ChangefeedID, mysqlCfg, db, false, false, 1*time.Second) + ap.mysqlSink = dmysql.NewMySQLSink(ctx, cfg.ChangefeedID, mysqlCfg, db, false, false, 1*time.Second, common.DefaultKeyspaceID) ap.needRecoveryInfo = false err = ap.Apply(ctx) require.Nil(t, err) @@ -585,7 +585,7 @@ func TestApplyBigTxn(t *testing.T) { sinkURI, err := url.Parse(cfg.SinkURI) require.NoError(t, err) mysqlCfg.Apply(sinkURI, cfg.ChangefeedID, cfg) - ap.mysqlSink = dmysql.NewMySQLSink(ctx, cfg.ChangefeedID, mysqlCfg, db, false, false, 1*time.Second) + ap.mysqlSink = dmysql.NewMySQLSink(ctx, cfg.ChangefeedID, mysqlCfg, db, false, false, 1*time.Second, common.DefaultKeyspaceID) ap.needRecoveryInfo = false err = ap.Apply(ctx) require.Nil(t, err) diff --git a/pkg/metrics/changefeed.go b/pkg/metrics/changefeed.go index 6ac271d31c..fa1d54f175 100644 --- a/pkg/metrics/changefeed.go +++ b/pkg/metrics/changefeed.go @@ -14,6 +14,8 @@ package metrics import ( + "strconv" + "github.com/prometheus/client_golang/prometheus" ) @@ -71,7 +73,7 @@ var ( Subsystem: "owner", Name: "status", Help: "The status of changefeeds", - }, []string{getKeyspaceLabel(), "changefeed"}) + }, []string{getKeyspaceLabel(), "changefeed", "keyspace_id"}) // ChangefeedErrorInfoGauge records the current warning or failed reason and its occurrence time // for each changefeed. @@ -99,7 +101,7 @@ var ( Subsystem: "owner", Name: "checkpoint_ts_lag", Help: "changefeed checkpoint ts lag in changefeeds in seconds", - }, []string{getKeyspaceLabel(), "changefeed"}) + }, []string{getKeyspaceLabel(), "changefeed", "keyspace_id"}) // it's a metrics used in a large number of tcms, we should always keep this metrics ChangefeedCheckpointTsGauge = prometheus.NewGaugeVec( @@ -139,9 +141,14 @@ var ( }, []string{getKeyspaceLabel(), "changefeed"}) ) -func DeleteChangefeedCheckpointMetrics(keyspace, changefeed string) { +func DeleteChangefeedCheckpointMetrics(keyspace, changefeed string, keyspaceID uint32) { ChangefeedCheckpointTsGauge.DeleteLabelValues(keyspace, changefeed) - ChangefeedCheckpointTsLagGauge.DeleteLabelValues(keyspace, changefeed) + ChangefeedCheckpointTsLagGauge.DeleteLabelValues(keyspace, changefeed, FormatKeyspaceID(keyspaceID)) +} + +// FormatKeyspaceID formats a keyspace ID as a metric label value. +func FormatKeyspaceID(keyspaceID uint32) string { + return strconv.FormatUint(uint64(keyspaceID), 10) } func ResetOwnerChangefeedMetrics() { diff --git a/pkg/metrics/changefeed_test.go b/pkg/metrics/changefeed_test.go index 6d1fade2ff..3a5b3f50d7 100644 --- a/pkg/metrics/changefeed_test.go +++ b/pkg/metrics/changefeed_test.go @@ -16,21 +16,49 @@ package metrics import ( "testing" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/testutil" "github.com/stretchr/testify/require" ) +func requireMetricHasLabel( + t *testing.T, + collector prometheus.Collector, + labelName string, + labelValue string, +) { + t.Helper() + + registry := prometheus.NewPedanticRegistry() + registry.MustRegister(collector) + metricFamilies, err := registry.Gather() + require.NoError(t, err) + require.NotEmpty(t, metricFamilies) + + for _, metricFamily := range metricFamilies { + for _, metric := range metricFamily.Metric { + for _, label := range metric.Label { + if label.GetName() == labelName && label.GetValue() == labelValue { + return + } + } + } + } + require.Failf(t, "metric label not found", "%s=%q", labelName, labelValue) +} + func TestResetOwnerChangefeedMetrics(t *testing.T) { ResetOwnerChangefeedMetrics() t.Cleanup(ResetOwnerChangefeedMetrics) keyspace := "default" changefeed := "reset-owner-changefeed-metrics" + keyspaceID := "123" - ChangefeedStatusGauge.WithLabelValues(keyspace, changefeed).Set(1) + ChangefeedStatusGauge.WithLabelValues(keyspace, changefeed, keyspaceID).Set(1) ChangefeedErrorInfoGauge.WithLabelValues(keyspace, changefeed, "failed", "1000", "CDC:ErrTest", "test").Set(1) ChangefeedCheckpointTsGauge.WithLabelValues(keyspace, changefeed).Set(100) - ChangefeedCheckpointTsLagGauge.WithLabelValues(keyspace, changefeed).Set(10) + ChangefeedCheckpointTsLagGauge.WithLabelValues(keyspace, changefeed, keyspaceID).Set(10) ChangefeedDownstreamInfoGauge.WithLabelValues(keyspace, changefeed, "mysql/tidb").Set(1) require.Equal(t, 1, testutil.CollectAndCount(ChangefeedStatusGauge)) @@ -38,6 +66,8 @@ func TestResetOwnerChangefeedMetrics(t *testing.T) { require.Equal(t, 1, testutil.CollectAndCount(ChangefeedCheckpointTsGauge)) require.Equal(t, 1, testutil.CollectAndCount(ChangefeedCheckpointTsLagGauge)) require.Equal(t, 1, testutil.CollectAndCount(ChangefeedDownstreamInfoGauge)) + requireMetricHasLabel(t, ChangefeedStatusGauge, "keyspace_id", keyspaceID) + requireMetricHasLabel(t, ChangefeedCheckpointTsLagGauge, "keyspace_id", keyspaceID) ResetOwnerChangefeedMetrics() diff --git a/pkg/metrics/sink.go b/pkg/metrics/sink.go index ee7cde8f72..a45582e6c2 100644 --- a/pkg/metrics/sink.go +++ b/pkg/metrics/sink.go @@ -28,7 +28,7 @@ var ( Name: "batch_row_count", Help: "Row count number for a given batch.", Buckets: prometheus.ExponentialBuckets(1, 2, 18), - }, []string{getKeyspaceLabel(), "changefeed", "type"}) // type is for `sinkType` + }, []string{getKeyspaceLabel(), "changefeed", "type", "keyspace_id"}) // type is for `sinkType` // ExecBatchWriteBytesHistogram records bytes written for each batch. ExecBatchWriteBytesHistogram = prometheus.NewHistogramVec( diff --git a/pkg/metrics/statistics.go b/pkg/metrics/statistics.go index 04227cb9cf..f1815a63e5 100644 --- a/pkg/metrics/statistics.go +++ b/pkg/metrics/statistics.go @@ -26,11 +26,13 @@ import ( // NewStatistics creates a statistics func NewStatistics( changefeed common.ChangeFeedID, + keyspaceID uint32, sinkType string, ) *Statistics { statistics := &Statistics{ sinkType: sinkType, changefeedID: changefeed, + keyspaceID: FormatKeyspaceID(keyspaceID), ddlTypes: sync.Map{}, rowsAffectedMap: sync.Map{}, } @@ -39,7 +41,7 @@ func NewStatistics( changefeedID := changefeed.Name() statistics.metricExecDDLHis = ExecDDLHistogram.WithLabelValues(keyspace, changefeedID) statistics.metricExecDDLRunningCnt = ExecDDLRunningGauge.WithLabelValues(keyspace, changefeedID) - statistics.metricExecBatchHis = ExecBatchHistogram.WithLabelValues(keyspace, changefeedID, sinkType) + statistics.metricExecBatchHis = ExecBatchHistogram.WithLabelValues(keyspace, changefeedID, sinkType, statistics.keyspaceID) statistics.metricExecBatchBytesHis = ExecBatchWriteBytesHistogram.WithLabelValues(keyspace, changefeedID, sinkType) statistics.metricTotalWriteBytesCnt = TotalWriteBytesCounter.WithLabelValues(keyspace, changefeedID, sinkType) statistics.metricExecErrCntForDDL = ExecutionErrorCounter.WithLabelValues(keyspace, changefeedID, "ddl") @@ -54,6 +56,7 @@ func NewStatistics( type Statistics struct { sinkType string changefeedID common.ChangeFeedID + keyspaceID string ddlTypes sync.Map rowsAffectedMap sync.Map @@ -142,7 +145,7 @@ func (b *Statistics) Close() { keyspace := b.changefeedID.Keyspace() changefeedID := b.changefeedID.Name() ExecDDLHistogram.DeleteLabelValues(keyspace, changefeedID) - ExecBatchHistogram.DeleteLabelValues(keyspace, changefeedID, b.sinkType) + ExecBatchHistogram.DeleteLabelValues(keyspace, changefeedID, b.sinkType, b.keyspaceID) ExecBatchWriteBytesHistogram.DeleteLabelValues(keyspace, changefeedID, b.sinkType) EventSizeHistogram.DeleteLabelValues(keyspace, changefeedID) ExecutionErrorCounter.DeleteLabelValues(keyspace, changefeedID, "ddl") diff --git a/pkg/metrics/statistics_test.go b/pkg/metrics/statistics_test.go new file mode 100644 index 0000000000..3afbcb2c6d --- /dev/null +++ b/pkg/metrics/statistics_test.go @@ -0,0 +1,42 @@ +// Copyright 2026 PingCAP, Inc. +// +// Licensed 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, +// See the License for the specific language governing permissions and +// limitations under the License. + +package metrics + +import ( + "testing" + + "github.com/pingcap/ticdc/pkg/common" + "github.com/prometheus/client_golang/prometheus/testutil" + "github.com/stretchr/testify/require" +) + +func TestExecBatchHistogramKeyspaceIDLabel(t *testing.T) { + ExecBatchHistogram.Reset() + t.Cleanup(ExecBatchHistogram.Reset) + + statistics := NewStatistics( + common.NewChangefeedID4Test("test-keyspace", "batch-row-count-keyspace-id"), + 123, + "sink", + ) + require.NoError(t, statistics.RecordBatchExecution(func() (int, int64, error) { + return 2, 10, nil + })) + + require.Equal(t, 1, testutil.CollectAndCount(ExecBatchHistogram)) + requireMetricHasLabel(t, ExecBatchHistogram, "keyspace_id", "123") + + statistics.Close() + require.Equal(t, 0, testutil.CollectAndCount(ExecBatchHistogram)) +} diff --git a/pkg/sink/mysql/mysql_writer_ddl_ts_test.go b/pkg/sink/mysql/mysql_writer_ddl_ts_test.go index e2b112b325..f5ec56f7fe 100644 --- a/pkg/sink/mysql/mysql_writer_ddl_ts_test.go +++ b/pkg/sink/mysql/mysql_writer_ddl_ts_test.go @@ -41,7 +41,7 @@ func newTestMysqlWriterForDDLTs(t *testing.T) (*Writer, *sql.DB, sqlmock.Sqlmock cfg.EnableDDLTs = true cfg.IsTiDB = false // Default to non-TiDB changefeedID := common.NewChangefeedID4Test("test", "test") - statistics := metrics.NewStatistics(changefeedID, "mysqlSink") + statistics := metrics.NewStatistics(changefeedID, common.DefaultKeyspaceID, "mysqlSink") writer := NewWriter(ctx, 0, db, cfg, changefeedID, statistics, nil) t.Cleanup(writer.Close) @@ -63,7 +63,7 @@ func newTestMysqlWriterForDDLTsTiDB(t *testing.T) (*Writer, *sql.DB, sqlmock.Sql cfg.EnableDDLTs = true cfg.IsTiDB = true // TiDB downstream changefeedID := common.NewChangefeedID4Test("test", "test") - statistics := metrics.NewStatistics(changefeedID, "mysqlSink") + statistics := metrics.NewStatistics(changefeedID, common.DefaultKeyspaceID, "mysqlSink") writer := NewWriter(ctx, 0, db, cfg, changefeedID, statistics, nil) t.Cleanup(writer.Close) diff --git a/pkg/sink/mysql/mysql_writer_test.go b/pkg/sink/mysql/mysql_writer_test.go index 0126b76012..00c37f9f85 100644 --- a/pkg/sink/mysql/mysql_writer_test.go +++ b/pkg/sink/mysql/mysql_writer_test.go @@ -52,7 +52,7 @@ func newTestMysqlWriter(t *testing.T) (*Writer, *sql.DB, sqlmock.Sqlmock) { cfg.BatchDMLEnable = true cfg.EnableDDLTs = defaultEnableDDLTs changefeedID := common.NewChangefeedID4Test("test", "test") - statistics := metrics.NewStatistics(changefeedID, "mysqlSink") + statistics := metrics.NewStatistics(changefeedID, common.DefaultKeyspaceID, "mysqlSink") writer := NewWriter(ctx, 0, db, cfg, changefeedID, statistics, nil) t.Cleanup(writer.Close) // assign a no-op stmt cache to bypass actual DB operations in unit tests @@ -75,7 +75,7 @@ func newTestMysqlWriterForTiDB(t *testing.T) (*Writer, *sql.DB, sqlmock.Sqlmock) cfg.ServerInfo = version.ParseServerInfo(defaultRunningAddIndexNewSQLVersion) changefeedID := common.NewChangefeedID4Test("test", "test") - statistics := metrics.NewStatistics(changefeedID, "mysqlSink") + statistics := metrics.NewStatistics(changefeedID, common.DefaultKeyspaceID, "mysqlSink") writer := NewWriter(ctx, 0, db, cfg, changefeedID, statistics, nil) t.Cleanup(writer.Close)