-
Notifications
You must be signed in to change notification settings - Fork 54
api,metrics: add changefeed operation history (#5095) #5105
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
Open
ti-chi-bot
wants to merge
1
commit into
pingcap:release-8.5
Choose a base branch
from
ti-chi-bot:cherry-pick-5095-to-release-8.5
base: release-8.5
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,212 @@ | ||||||
| // 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, | ||||||
| // 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 middleware | ||||||
|
|
||||||
| import ( | ||||||
| "fmt" | ||||||
| "net/http" | ||||||
| "strings" | ||||||
| "sync" | ||||||
| "sync/atomic" | ||||||
| "time" | ||||||
| "unicode/utf8" | ||||||
|
|
||||||
| "github.com/gin-gonic/gin" | ||||||
| "github.com/pingcap/log" | ||||||
| "github.com/pingcap/ticdc/pkg/api" | ||||||
| "github.com/pingcap/ticdc/pkg/metrics" | ||||||
| "go.uber.org/zap" | ||||||
| ) | ||||||
|
|
||||||
| const ( | ||||||
| changefeedOperationContextKey = "changefeed-operation-info" | ||||||
| changefeedOperationHistoryLimit = 100 | ||||||
| changefeedOperationMetricTextLimit = 256 | ||||||
| ) | ||||||
|
|
||||||
| var ( | ||||||
| recentChangefeedOperations = newRecentChangefeedOperationStore(changefeedOperationHistoryLimit) | ||||||
| changefeedOperationEventID uint64 | ||||||
| ) | ||||||
|
|
||||||
| type changefeedOperationInfo struct { | ||||||
| keyspace string | ||||||
| changefeed string | ||||||
| details string | ||||||
| } | ||||||
|
|
||||||
| type changefeedOperationMetricLabels struct { | ||||||
| keyspace string | ||||||
| changefeed string | ||||||
| operation string | ||||||
| result string | ||||||
| username string | ||||||
| details string | ||||||
| err string | ||||||
| eventID string | ||||||
| } | ||||||
|
|
||||||
| func (l changefeedOperationMetricLabels) labelValues() []string { | ||||||
| return []string{ | ||||||
| l.keyspace, | ||||||
| l.changefeed, | ||||||
| l.operation, | ||||||
| l.result, | ||||||
| l.username, | ||||||
| l.details, | ||||||
| l.err, | ||||||
| l.eventID, | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| type recentChangefeedOperationStore struct { | ||||||
| mu sync.Mutex | ||||||
| limit int | ||||||
| events []changefeedOperationMetricLabels | ||||||
| } | ||||||
|
|
||||||
| func newRecentChangefeedOperationStore(limit int) *recentChangefeedOperationStore { | ||||||
| return &recentChangefeedOperationStore{limit: limit} | ||||||
| } | ||||||
|
|
||||||
| func (s *recentChangefeedOperationStore) record( | ||||||
| labels changefeedOperationMetricLabels, | ||||||
| operationTime time.Time, | ||||||
| ) { | ||||||
| s.mu.Lock() | ||||||
| defer s.mu.Unlock() | ||||||
|
|
||||||
| // The dashboard only needs a recent investigation window. Keep this cache | ||||||
| // bounded so user names and detail strings do not become unbounded metric | ||||||
| // cardinality over long-running clusters. | ||||||
| metrics.ChangefeedOperationTimeGauge.WithLabelValues(labels.labelValues()...).Set(float64(operationTime.UnixMilli())) | ||||||
| s.events = append(s.events, labels) | ||||||
| if len(s.events) <= s.limit { | ||||||
| return | ||||||
| } | ||||||
|
|
||||||
| oldest := s.events[0] | ||||||
| s.events = s.events[1:] | ||||||
| metrics.ChangefeedOperationTimeGauge.DeleteLabelValues(oldest.labelValues()...) | ||||||
| } | ||||||
|
|
||||||
| // ChangefeedOperationMiddleware records user initiated changefeed mutations for | ||||||
| // logs and the bounded recent-operation Grafana panel. | ||||||
| func ChangefeedOperationMiddleware(operation string) gin.HandlerFunc { | ||||||
| return func(c *gin.Context) { | ||||||
| start := time.Now() | ||||||
| c.Next() | ||||||
|
|
||||||
| statusCode := c.Writer.Status() | ||||||
| lastError := c.Errors.Last() | ||||||
| result := "success" | ||||||
| if statusCode >= http.StatusBadRequest || lastError != nil { | ||||||
| result = "failed" | ||||||
| } | ||||||
|
|
||||||
| info := getChangefeedOperationInfo(c) | ||||||
| if info.keyspace == "" { | ||||||
| info.keyspace = c.Query(api.APIOpVarKeyspace) | ||||||
| } | ||||||
| if info.changefeed == "" { | ||||||
| info.changefeed = c.Param(api.APIOpVarChangefeedID) | ||||||
| } | ||||||
|
|
||||||
| username, _, _ := c.Request.BasicAuth() | ||||||
| if username == "" { | ||||||
| username = "anonymous" | ||||||
| } | ||||||
|
|
||||||
| var operationErr error | ||||||
| if lastError != nil { | ||||||
| operationErr = lastError.Err | ||||||
| } | ||||||
|
|
||||||
| operationTime := time.Now() | ||||||
| eventID := atomic.AddUint64(&changefeedOperationEventID, 1) | ||||||
| labels := changefeedOperationMetricLabels{ | ||||||
| keyspace: normalizeChangefeedOperationMetricText(info.keyspace), | ||||||
| changefeed: normalizeChangefeedOperationMetricText(info.changefeed), | ||||||
| operation: operation, | ||||||
| result: result, | ||||||
| username: normalizeChangefeedOperationMetricText(username), | ||||||
| details: normalizeChangefeedOperationMetricText(info.details), | ||||||
| err: normalizeChangefeedOperationMetricError(operationErr), | ||||||
| eventID: fmt.Sprintf("%d", eventID), | ||||||
| } | ||||||
| recentChangefeedOperations.record(labels, operationTime) | ||||||
|
|
||||||
| log.Info("changefeed operation", | ||||||
| zap.String("operation", operation), | ||||||
| zap.String("result", result), | ||||||
| zap.String("keyspace", info.keyspace), | ||||||
| zap.String("changefeedID", info.changefeed), | ||||||
| zap.String("details", info.details), | ||||||
| zap.Int("status", statusCode), | ||||||
| zap.String("username", username), | ||||||
| zap.String("ip", c.ClientIP()), | ||||||
| zap.String("userAgent", c.Request.UserAgent()), | ||||||
| zap.String("clientVersion", c.Request.Header.Get(ClientVersionHeader)), | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The constant
Suggested change
|
||||||
| zap.Duration("duration", time.Since(start)), | ||||||
| zap.Error(operationErr), | ||||||
| ) | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| // SetChangefeedOperationTarget attaches the logical changefeed identity that the | ||||||
| // current mutation request targets. | ||||||
| func SetChangefeedOperationTarget(c *gin.Context, keyspace, changefeed string) { | ||||||
| info := getChangefeedOperationInfo(c) | ||||||
| info.keyspace = keyspace | ||||||
| info.changefeed = changefeed | ||||||
| c.Set(changefeedOperationContextKey, info) | ||||||
| } | ||||||
|
|
||||||
| // SetChangefeedOperationDetails attaches a concise, non-sensitive summary for | ||||||
| // the current mutation request. | ||||||
| func SetChangefeedOperationDetails(c *gin.Context, details string) { | ||||||
| info := getChangefeedOperationInfo(c) | ||||||
| info.details = details | ||||||
| c.Set(changefeedOperationContextKey, info) | ||||||
| } | ||||||
|
|
||||||
| func getChangefeedOperationInfo(c *gin.Context) changefeedOperationInfo { | ||||||
| raw, ok := c.Get(changefeedOperationContextKey) | ||||||
| if !ok { | ||||||
| return changefeedOperationInfo{} | ||||||
| } | ||||||
| info, ok := raw.(changefeedOperationInfo) | ||||||
| if !ok { | ||||||
| return changefeedOperationInfo{} | ||||||
| } | ||||||
| return info | ||||||
| } | ||||||
|
|
||||||
| func normalizeChangefeedOperationMetricError(err error) string { | ||||||
| if err == nil { | ||||||
| return "" | ||||||
| } | ||||||
| return normalizeChangefeedOperationMetricText(err.Error()) | ||||||
| } | ||||||
|
|
||||||
| func normalizeChangefeedOperationMetricText(value string) string { | ||||||
| value = strings.Join(strings.Fields(value), " ") | ||||||
| if utf8.RuneCountInString(value) <= changefeedOperationMetricTextLimit { | ||||||
| return value | ||||||
| } | ||||||
|
|
||||||
| runes := []rune(value) | ||||||
| return string(runes[:changefeedOperationMetricTextLimit-3]) + "..." | ||||||
| } | ||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| // 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, | ||
| // 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 middleware | ||
|
|
||
| import ( | ||
| "errors" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "sync/atomic" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/gin-gonic/gin" | ||
| "github.com/pingcap/ticdc/pkg/metrics" | ||
| "github.com/prometheus/client_golang/prometheus" | ||
| "github.com/prometheus/client_golang/prometheus/testutil" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| // TestChangefeedOperationMiddlewareRecordsSuccessfulMutation verifies that a | ||
| // successful request keeps the logical target, normalized detail summary, and | ||
| // authenticated user for the dashboard history row. | ||
| func TestChangefeedOperationMiddlewareRecordsSuccessfulMutation(t *testing.T) { | ||
| resetRecentChangefeedOperationStateForTest(t) | ||
|
|
||
| router := gin.New() | ||
| router.POST("/api/v2/changefeeds/:changefeed_id/resume", | ||
| ChangefeedOperationMiddleware("resume"), | ||
| func(c *gin.Context) { | ||
| SetChangefeedOperationTarget(c, "ks1", "test") | ||
| SetChangefeedOperationDetails(c, "overwrite_checkpoint_ts=true\nnew_checkpoint_ts=123") | ||
| c.Status(http.StatusOK) | ||
| }, | ||
| ) | ||
|
|
||
| recorder := httptest.NewRecorder() | ||
| req := httptest.NewRequest(http.MethodPost, "/api/v2/changefeeds/test/resume?keyspace=ks1", nil) | ||
| req.SetBasicAuth("alice", "secret") | ||
| router.ServeHTTP(recorder, req) | ||
|
|
||
| require.Len(t, recentChangefeedOperations.events, 1) | ||
| require.Equal(t, changefeedOperationMetricLabels{ | ||
| keyspace: "ks1", | ||
| changefeed: "test", | ||
| operation: "resume", | ||
| result: "success", | ||
| username: "alice", | ||
| details: "overwrite_checkpoint_ts=true new_checkpoint_ts=123", | ||
| err: "", | ||
| eventID: "1", | ||
| }, recentChangefeedOperations.events[0]) | ||
| } | ||
|
|
||
| // TestChangefeedOperationMiddlewareRecordsFailedMutation verifies that a failed | ||
| // request is still retained with its normalized error summary so oncall can see | ||
| // rejected user attempts as well as successful changes. | ||
| func TestChangefeedOperationMiddlewareRecordsFailedMutation(t *testing.T) { | ||
| resetRecentChangefeedOperationStateForTest(t) | ||
|
|
||
| router := gin.New() | ||
| router.PUT("/api/v2/changefeeds/:changefeed_id", | ||
| ChangefeedOperationMiddleware("update"), | ||
| func(c *gin.Context) { | ||
| _ = c.Error(errors.New("update rejected\nbecause state is normal")) | ||
| c.Status(http.StatusBadRequest) | ||
| }, | ||
| ) | ||
|
|
||
| recorder := httptest.NewRecorder() | ||
| req := httptest.NewRequest(http.MethodPut, "/api/v2/changefeeds/test?keyspace=ks1", nil) | ||
| router.ServeHTTP(recorder, req) | ||
|
|
||
| require.Len(t, recentChangefeedOperations.events, 1) | ||
| require.Equal(t, "failed", recentChangefeedOperations.events[0].result) | ||
| require.Equal(t, "anonymous", recentChangefeedOperations.events[0].username) | ||
| require.Equal(t, "update rejected because state is normal", recentChangefeedOperations.events[0].err) | ||
| } | ||
|
|
||
| // TestRecentChangefeedOperationStoreEvictsOldestMetric verifies that the recent | ||
| // operation cache preserves only the newest bounded rows and removes the evicted | ||
| // metric series to avoid unbounded label cardinality. | ||
| func TestRecentChangefeedOperationStoreEvictsOldestMetric(t *testing.T) { | ||
| resetRecentChangefeedOperationStateForTest(t) | ||
| store := newRecentChangefeedOperationStore(2) | ||
| now := time.UnixMilli(1_700_000_000_000) | ||
|
|
||
| first := changefeedOperationMetricLabels{eventID: "1"} | ||
| second := changefeedOperationMetricLabels{eventID: "2"} | ||
| third := changefeedOperationMetricLabels{eventID: "3"} | ||
| t.Cleanup(func() { | ||
| for _, labels := range []changefeedOperationMetricLabels{first, second, third} { | ||
| metrics.ChangefeedOperationTimeGauge.DeleteLabelValues(labels.labelValues()...) | ||
| } | ||
| }) | ||
| store.record(first, now) | ||
| store.record(second, now.Add(time.Millisecond)) | ||
| store.record(third, now.Add(2*time.Millisecond)) | ||
|
|
||
| require.Equal(t, []changefeedOperationMetricLabels{second, third}, store.events) | ||
| require.Equal(t, float64(0), testutil.ToFloat64(metricsGaugeForTest(first))) | ||
| require.Equal(t, float64(now.Add(time.Millisecond).UnixMilli()), testutil.ToFloat64(metricsGaugeForTest(second))) | ||
| require.Equal(t, float64(now.Add(2*time.Millisecond).UnixMilli()), testutil.ToFloat64(metricsGaugeForTest(third))) | ||
| } | ||
|
|
||
| // TestNormalizeChangefeedOperationMetricText verifies that dashboard labels are | ||
| // kept single-line and bounded so a malformed request cannot create oversized | ||
| // operation-history fields. | ||
| func TestNormalizeChangefeedOperationMetricText(t *testing.T) { | ||
| longText := strings.Repeat("a", changefeedOperationMetricTextLimit+10) | ||
| require.Equal(t, "a b", normalizeChangefeedOperationMetricText("a\n b")) | ||
| require.Equal(t, changefeedOperationMetricTextLimit, len(normalizeChangefeedOperationMetricText(longText))) | ||
| require.True(t, strings.HasSuffix(normalizeChangefeedOperationMetricText(longText), "...")) | ||
| } | ||
|
|
||
| func resetRecentChangefeedOperationStateForTest(t *testing.T) { | ||
| t.Helper() | ||
| for _, labels := range recentChangefeedOperations.events { | ||
| metrics.ChangefeedOperationTimeGauge.DeleteLabelValues(labels.labelValues()...) | ||
| } | ||
| recentChangefeedOperations = newRecentChangefeedOperationStore(changefeedOperationHistoryLimit) | ||
| atomic.StoreUint64(&changefeedOperationEventID, 0) | ||
| } | ||
|
|
||
| func metricsGaugeForTest(labels changefeedOperationMetricLabels) prometheus.Gauge { | ||
| return metrics.ChangefeedOperationTimeGauge.WithLabelValues(labels.labelValues()...) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Prometheus best practices generally recommend using seconds for timestamps in gauges. While the dashboard is configured for
dateTimeAsIso, Grafana usually expects the value to be in seconds for this unit. Using milliseconds might result in incorrect date displays in some Grafana versions or configurations unless explicitly handled.