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

topsql: introduce pub/sub mode #29020

Closed
wants to merge 60 commits into from
Closed
Show file tree
Hide file tree
Changes from 58 commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
b464ff4
register pubusb
zhongzc Oct 20, 2021
ab68337
run fine
zhongzc Oct 20, 2021
8d6b03e
globally enabled not to affect instance level enabled directly
zhongzc Oct 21, 2021
38fccf9
tiny fix
zhongzc Oct 21, 2021
6d4a115
add license
zhongzc Oct 21, 2021
91d7143
add tests & add comment
zhongzc Oct 25, 2021
8f2eae6
fix tests
zhongzc Oct 25, 2021
b75478e
fix tests
zhongzc Oct 25, 2021
30201ec
fix
zhongzc Oct 25, 2021
9c3f723
update tipb
zhongzc Oct 26, 2021
ba167c3
Merge remote-tracking branch 'origin/master' into pubsub
zhongzc Oct 26, 2021
a6aa4f8
fix test
zhongzc Oct 26, 2021
27b47f7
Merge branch 'master' into pubsub
zhongzc Oct 26, 2021
f6537e2
add metrics
zhongzc Oct 26, 2021
24fb6ca
remove topsql var case
zhongzc Oct 27, 2021
c3784e7
Merge remote-tracking branch 'origin/master' into pubsub
zhongzc Oct 27, 2021
5abcea5
add profile metrics
zhongzc Oct 27, 2021
373197d
add profile metrics
zhongzc Oct 27, 2021
cb2fce3
fix unsubscribe
zhongzc Oct 27, 2021
1b076d9
fix timeout
zhongzc Nov 16, 2021
2437176
address comment
zhongzc Dec 1, 2021
2fdec8d
Merge remote-tracking branch 'origin/master' into pubsub
zhongzc Dec 1, 2021
433c1f3
tiny refactor
zhongzc Dec 6, 2021
b2afed8
address comment
zhongzc Dec 6, 2021
6610be4
Merge remote-tracking branch 'origin/master' into pubsub
zhongzc Dec 6, 2021
4874b81
address comment
zhongzc Dec 6, 2021
09a0f33
fix global var test
zhongzc Dec 6, 2021
cee41fa
address comments
zhongzc Dec 6, 2021
b1bb877
add keepalive
zhongzc Dec 6, 2021
13890a5
add more grpc configs
zhongzc Dec 9, 2021
1c58afd
client -> datasink
zhongzc Dec 9, 2021
2ed9c6e
share tipb report data construction
zhongzc Dec 9, 2021
2de6779
Merge branch 'master' into pubsub
zhongzc Dec 9, 2021
c3e92da
polish
zhongzc Dec 9, 2021
0d50283
remove the global service & timeout -> deadline
zhongzc Dec 9, 2021
3eb4cfd
Merge branch 'master' into pubsub
zhongzc Dec 9, 2021
bca0e17
remove session var
zhongzc Dec 9, 2021
5f09f4b
fix
zhongzc Dec 9, 2021
2909a57
fix
zhongzc Dec 9, 2021
c53a043
comment DataSink
zhongzc Dec 10, 2021
a3cf4d6
not to close receiver
zhongzc Dec 10, 2021
26c5812
split handleDataSinkRegistration
zhongzc Dec 10, 2021
a7474d7
fix leak goroutine in test
zhongzc Dec 10, 2021
2a64d59
Merge branch 'master' into pubsub
zhongzc Dec 10, 2021
9decb9d
Merge branch 'master' into pubsub
zhongzc Dec 10, 2021
3628b3e
fix imports
zhongzc Dec 10, 2021
991e309
Merge branch 'master' into pubsub
zhongzc Dec 10, 2021
1ecea77
enabled
zhongzc Dec 10, 2021
3b72c97
fix unbuffered
zhongzc Dec 10, 2021
df42ffe
fix InstanceEnabled
zhongzc Dec 10, 2021
7b813ff
Merge branch 'master' into pubsub
zhongzc Dec 10, 2021
2a7111f
fix init NewRemoteTopSQLReporter
zhongzc Dec 10, 2021
127c72e
use `globalTopSQLReport` to judge topsql enabled
zhongzc Dec 10, 2021
95c7d27
Merge branch 'master' into pubsub
zhongzc Dec 10, 2021
947ae62
Merge branch 'master' into pubsub
zhongzc Dec 11, 2021
04e6a5a
remove redundant `EnablePProfSQLCPU`
zhongzc Dec 13, 2021
0ce9795
Update util/topsql/reporter/reporter.go
zhongzc Dec 13, 2021
cc4cef3
refactor
zhongzc Dec 13, 2021
c8a6ea5
move tracecpu out of topsql
zhongzc Dec 13, 2021
54c34e0
polish
zhongzc Dec 13, 2021
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
32 changes: 21 additions & 11 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -439,12 +439,17 @@ func (s *Security) ClusterSecurity() tikvcfg.Security {

// Status is the status section of the config.
type Status struct {
StatusHost string `toml:"status-host" json:"status-host"`
MetricsAddr string `toml:"metrics-addr" json:"metrics-addr"`
StatusPort uint `toml:"status-port" json:"status-port"`
MetricsInterval uint `toml:"metrics-interval" json:"metrics-interval"`
ReportStatus bool `toml:"report-status" json:"report-status"`
RecordQPSbyDB bool `toml:"record-db-qps" json:"record-db-qps"`
StatusHost string `toml:"status-host" json:"status-host"`
MetricsAddr string `toml:"metrics-addr" json:"metrics-addr"`
StatusPort uint `toml:"status-port" json:"status-port"`
MetricsInterval uint `toml:"metrics-interval" json:"metrics-interval"`
ReportStatus bool `toml:"report-status" json:"report-status"`
RecordQPSbyDB bool `toml:"record-db-qps" json:"record-db-qps"`
GRPCKeepAliveTime uint `toml:"grpc-keepalive-time" json:"grpc-keepalive-time"`
GRPCKeepAliveTimeout uint `toml:"grpc-keepalive-timeout" json:"grpc-keepalive-timeout"`
GRPCConcurrentStreams uint `toml:"grpc-concurrent-streams" json:"grpc-concurrent-streams"`
GRPCInitialWindowSize int `toml:"grpc-initial-window-size" json:"grpc-initial-window-size"`
GRPCMaxSendMsgSize int `toml:"grpc-max-send-msg-size" json:"grpc-max-send-msg-size"`
}

// Performance is the performance section of the config.
Expand Down Expand Up @@ -658,11 +663,16 @@ var defaultConf = Config{
EnableSlowLog: *NewAtomicBool(logutil.DefaultTiDBEnableSlowLog),
},
Status: Status{
ReportStatus: true,
StatusHost: DefStatusHost,
StatusPort: DefStatusPort,
MetricsInterval: 15,
RecordQPSbyDB: false,
ReportStatus: true,
StatusHost: DefStatusHost,
StatusPort: DefStatusPort,
MetricsInterval: 15,
RecordQPSbyDB: false,
GRPCKeepAliveTime: 10,
GRPCKeepAliveTimeout: 3,
GRPCConcurrentStreams: 1024,
GRPCInitialWindowSize: 2 * 1024 * 1024,
GRPCMaxSendMsgSize: 10 * 1024 * 1024,
},
Performance: Performance{
MaxMemory: 0,
Expand Down
17 changes: 17 additions & 0 deletions config/config.toml.example
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,23 @@ metrics-interval = 15
# Record statements qps by database name if it is enabled.
record-db-qps = false

# After a duration of this time in seconds if the server doesn't see any activity it pings
# the client to see if the transport is still alive.
grpc-keepalive-time = 10

# After having pinged for keepalive check, the server waits for a duration of timeout in seconds
# and if no activity is seen even after that the connection is closed.
grpc-keepalive-timeout = 3

## The number of max concurrent streams/requests on a client connection.
# grpc-concurrent-streams = 1024

## Sets window size for stream. The default value is 2MB.
# grpc-initial-window-size = 2097152

## Set maximum message length in bytes that gRPC can send. `-1` means unlimited. The default value is 10MB.
# grpc-max-send-msg-size = 10485760

[performance]
# Max CPUs to use, 0 use number of CPUs in the machine.
max-procs = 0
Expand Down
2 changes: 1 addition & 1 deletion ddl/ddl_worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ func newMetaWithQueueTp(txn kv.Transaction, tp workerType) *meta.Meta {
}

func (w *worker) setDDLLabelForTopSQL(job *model.Job) {
if !variable.TopSQLEnabled() || job == nil {
if !topsql.InstanceEnabled() || job == nil {
return
}

Expand Down
3 changes: 2 additions & 1 deletion distsql/request_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/memory"
"github.com/pingcap/tidb/util/ranger"
"github.com/pingcap/tidb/util/topsql"
"github.com/pingcap/tipb/go-tipb"
)

Expand Down Expand Up @@ -291,7 +292,7 @@ func (builder *RequestBuilder) SetFromInfoSchema(pis interface{}) *RequestBuilde

// SetResourceGroupTagger sets the request resource group tagger.
func (builder *RequestBuilder) SetResourceGroupTagger(sc *stmtctx.StatementContext) *RequestBuilder {
if variable.TopSQLEnabled() {
if topsql.InstanceEnabled() {
builder.Request.ResourceGroupTagger = sc.GetResourceGroupTagger()
}
return builder
Expand Down
8 changes: 3 additions & 5 deletions domain/globalconfigsync/globalconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"github.com/pingcap/tidb/domain/globalconfigsync"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/store/mockstore"
"github.com/pingcap/tidb/testkit"
"github.com/pingcap/tidb/util/testbridge"
"github.com/stretchr/testify/require"
"go.etcd.io/etcd/integration"
Expand Down Expand Up @@ -67,11 +68,8 @@ func TestStoreGlobalConfig(t *testing.T) {
defer cluster.Terminate(t)
domain.GetGlobalConfigSyncer().SetEtcdClient(cluster.RandClient())

se, err := session.CreateSession4Test(store)
require.NoError(t, err)

_, err = se.Execute(context.Background(), "set @@global.tidb_enable_top_sql=1;")
require.NoError(t, err)
tk := testkit.NewTestKit(t, store)
tk.MustExec("set @@global.tidb_enable_top_sql=1;")
breezewish marked this conversation as resolved.
Show resolved Hide resolved

for i := 0; i < 20; i++ {
resp, err := cluster.RandClient().Get(context.Background(), "/global/config/enable_resource_metering")
Expand Down
12 changes: 6 additions & 6 deletions domain/sysvar_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import (
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/sqlexec"
"github.com/pingcap/tidb/util/stmtsummary"
"github.com/pingcap/tidb/util/topsql/reporter"
"github.com/pingcap/tidb/util/topsql/tracecpu"
storekv "github.com/tikv/client-go/v2/kv"
pd "github.com/tikv/pd/client"
"go.uber.org/zap"
Expand Down Expand Up @@ -201,36 +203,34 @@ func (do *Domain) checkEnableServerGlobalVar(name, sVal string) {
err = stmtsummary.StmtSummaryByDigestMap.SetMaxSQLLength(sVal, false)
case variable.TiDBCapturePlanBaseline:
variable.CapturePlanBaseline.Set(sVal, false)
case variable.TiDBEnableTopSQL:
variable.TopSQLVariable.Enable.Store(variable.TiDBOptOn(sVal))
case variable.TiDBTopSQLPrecisionSeconds:
var val int64
val, err = strconv.ParseInt(sVal, 10, 64)
if err != nil {
break
}
variable.TopSQLVariable.PrecisionSeconds.Store(val)
tracecpu.PrecisionSeconds.Store(val)
case variable.TiDBTopSQLMaxStatementCount:
var val int64
val, err = strconv.ParseInt(sVal, 10, 64)
if err != nil {
break
}
variable.TopSQLVariable.MaxStatementCount.Store(val)
reporter.MaxStatementCount.Store(val)
case variable.TiDBTopSQLMaxCollect:
var val int64
val, err = strconv.ParseInt(sVal, 10, 64)
if err != nil {
break
}
variable.TopSQLVariable.MaxCollect.Store(val)
reporter.MaxCollect.Store(val)
case variable.TiDBTopSQLReportIntervalSeconds:
var val int64
val, err = strconv.ParseInt(sVal, 10, 64)
if err != nil {
break
}
variable.TopSQLVariable.ReportIntervalSeconds.Store(val)
reporter.ReportIntervalSeconds.Store(val)
case variable.TiDBRestrictedReadOnly:
variable.RestrictedReadOnly.Store(variable.TiDBOptOn(sVal))
case variable.TiDBStoreLimit:
Expand Down
2 changes: 1 addition & 1 deletion executor/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ func (a *ExecStmt) RebuildPlan(ctx context.Context) (int64, error) {
}

func (a *ExecStmt) setPlanLabelForTopSQL(ctx context.Context) context.Context {
if a.Plan == nil || !variable.TopSQLEnabled() {
if a.Plan == nil || !topsql.InstanceEnabled() {
return ctx
}
vars := a.Ctx.GetSessionVars()
Expand Down
7 changes: 4 additions & 3 deletions executor/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ import (
"github.com/pingcap/tidb/util/memory"
"github.com/pingcap/tidb/util/resourcegrouptag"
"github.com/pingcap/tidb/util/topsql"
"github.com/pingcap/tidb/util/topsql/tracecpu"
tikverr "github.com/tikv/client-go/v2/error"
tikvstore "github.com/tikv/client-go/v2/kv"
tikvutil "github.com/tikv/client-go/v2/util"
Expand Down Expand Up @@ -1726,11 +1727,11 @@ func ResetContextOfStmt(ctx sessionctx.Context, s ast.StmtNode) (err error) {
sc.InitSQLDigest(prepareStmt.NormalizedSQL, prepareStmt.SQLDigest)
// For `execute stmt` SQL, should reset the SQL digest with the prepare SQL digest.
goCtx := context.Background()
if variable.EnablePProfSQLCPU.Load() && len(prepareStmt.NormalizedSQL) > 0 {
if tracecpu.EnablePProfSQLCPU.Load() && len(prepareStmt.NormalizedSQL) > 0 {
goCtx = pprof.WithLabels(goCtx, pprof.Labels("sql", util.QueryStrForLog(prepareStmt.NormalizedSQL)))
pprof.SetGoroutineLabels(goCtx)
}
if variable.TopSQLEnabled() && prepareStmt.SQLDigest != nil {
if topsql.InstanceEnabled() && prepareStmt.SQLDigest != nil {
topsql.AttachSQLInfo(goCtx, prepareStmt.NormalizedSQL, prepareStmt.SQLDigest, "", nil, vars.InRestrictedSQL)
}
}
Expand Down Expand Up @@ -1910,7 +1911,7 @@ func FillVirtualColumnValue(virtualRetTypes []*types.FieldType, virtualColumnInd
}

func setResourceGroupTaggerForTxn(sc *stmtctx.StatementContext, snapshot kv.Snapshot) {
if snapshot != nil && variable.TopSQLEnabled() {
if snapshot != nil && topsql.InstanceEnabled() {
snapshot.SetOption(kv.ResourceGroupTagger, sc.GetResourceGroupTagger())
}
}
9 changes: 4 additions & 5 deletions executor/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ import (
"github.com/pingcap/tidb/util/testkit"
"github.com/pingcap/tidb/util/testutil"
"github.com/pingcap/tidb/util/timeutil"
"github.com/pingcap/tidb/util/topsql"
topsqlmock "github.com/pingcap/tidb/util/topsql/tracecpu/mock"
"github.com/pingcap/tipb/go-tipb"
"github.com/stretchr/testify/require"
"github.com/tikv/client-go/v2/oracle"
Expand Down Expand Up @@ -8718,11 +8720,8 @@ func (s *testResourceTagSuite) TestResourceGroupTag(c *C) {
tk.MustExec("create table t(a int, b int, unique index idx(a));")
tbInfo := testGetTableByName(c, tk.Se, "test", "t")

// Enable Top SQL
variable.TopSQLVariable.Enable.Store(true)
config.UpdateGlobal(func(conf *config.Config) {
conf.TopSQL.ReceiverAddress = "mock-agent"
})
topsql.SetupTopSQL(topsqlmock.NewTopSQLCollector())
defer topsql.Close()

c.Assert(failpoint.Enable("github.com/pingcap/tidb/store/mockstore/unistore/unistoreRPCClientSendHook", `return(true)`), IsNil)
defer failpoint.Disable("github.com/pingcap/tidb/store/mockstore/unistore/unistoreRPCClientSendHook")
Expand Down
3 changes: 3 additions & 0 deletions executor/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ func TestMain(m *testing.M) {
goleak.IgnoreTopFunction("go.etcd.io/etcd/pkg/logutil.(*MergeLogger).outputLoop"),
goleak.IgnoreTopFunction("go.opencensus.io/stats/view.(*worker).start"),
goleak.IgnoreTopFunction("gopkg.in/natefinch/lumberjack%2ev2.(*Logger).millRun"),
goleak.IgnoreTopFunction("time.Sleep"),
goleak.IgnoreTopFunction("runtime/pprof.readProfile"),
goleak.IgnoreTopFunction("github.com/pingcap/tidb/util/topsql/tracecpu.(*sqlCPUProfiler).startAnalyzeProfileWorker"),
Copy link
Member

@breezewish breezewish Dec 13, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it may not be accepted to let this function leak.

}
callback := func(i int) int {
testDataMap.GenerateOutputIfNeeded()
Expand Down
3 changes: 1 addition & 2 deletions executor/prepared.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import (
"github.com/pingcap/tidb/planner"
plannercore "github.com/pingcap/tidb/planner/core"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/types"
driver "github.com/pingcap/tidb/types/parser_driver"
"github.com/pingcap/tidb/util"
Expand Down Expand Up @@ -194,7 +193,7 @@ func (e *PrepareExec) Next(ctx context.Context, req *chunk.Chunk) error {
SchemaVersion: ret.InfoSchema.SchemaMetaVersion(),
}
normalizedSQL, digest := parser.NormalizeDigest(prepared.Stmt.Text())
if variable.TopSQLEnabled() {
if topsql.InstanceEnabled() {
ctx = topsql.AttachSQLInfo(ctx, normalizedSQL, digest, "", nil, vars.InRestrictedSQL)
}

Expand Down
24 changes: 10 additions & 14 deletions executor/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ import (
"github.com/pingcap/tidb/util/mock"
"github.com/pingcap/tidb/util/testkit"
"github.com/pingcap/tidb/util/testutil"
"github.com/pingcap/tidb/util/topsql/reporter"
"github.com/pingcap/tidb/util/topsql/tracecpu"
)

func (s *testSerialSuite1) TestSetVar(c *C) {
Expand Down Expand Up @@ -1497,27 +1499,21 @@ func (s *testSerialSuite) TestSetTopSQLVariables(c *C) {
}()

tk := testkit.NewTestKit(c, s.store)
tk.MustExec("set @@global.tidb_enable_top_sql='On';")
tk.MustQuery("select @@global.tidb_enable_top_sql;").Check(testkit.Rows("1"))
c.Assert(variable.TopSQLVariable.Enable.Load(), IsTrue)
tk.MustExec("set @@global.tidb_enable_top_sql='off';")
tk.MustQuery("select @@global.tidb_enable_top_sql;").Check(testkit.Rows("0"))
c.Assert(variable.TopSQLVariable.Enable.Load(), IsFalse)

tk.MustExec("set @@global.tidb_top_sql_precision_seconds=2;")
tk.MustQuery("select @@global.tidb_top_sql_precision_seconds;").Check(testkit.Rows("2"))
c.Assert(variable.TopSQLVariable.PrecisionSeconds.Load(), Equals, int64(2))
c.Assert(tracecpu.PrecisionSeconds.Load(), Equals, int64(2))
_, err := tk.Exec("set @@global.tidb_top_sql_precision_seconds='abc';")
c.Assert(err.Error(), Equals, "[variable:1232]Incorrect argument type to variable 'tidb_top_sql_precision_seconds'")
tk.MustExec("set @@global.tidb_top_sql_precision_seconds='-1';")
tk.MustQuery("select @@global.tidb_top_sql_precision_seconds;").Check(testkit.Rows("1"))
tk.MustExec("set @@global.tidb_top_sql_precision_seconds=2;")
tk.MustQuery("select @@global.tidb_top_sql_precision_seconds;").Check(testkit.Rows("2"))
c.Assert(variable.TopSQLVariable.PrecisionSeconds.Load(), Equals, int64(2))
c.Assert(tracecpu.PrecisionSeconds.Load(), Equals, int64(2))

tk.MustExec("set @@global.tidb_top_sql_max_statement_count=20;")
tk.MustQuery("select @@global.tidb_top_sql_max_statement_count;").Check(testkit.Rows("20"))
c.Assert(variable.TopSQLVariable.MaxStatementCount.Load(), Equals, int64(20))
c.Assert(reporter.MaxStatementCount.Load(), Equals, int64(20))
_, err = tk.Exec("set @@global.tidb_top_sql_max_statement_count='abc';")
c.Assert(err.Error(), Equals, "[variable:1232]Incorrect argument type to variable 'tidb_top_sql_max_statement_count'")
tk.MustExec("set @@global.tidb_top_sql_max_statement_count='-1';")
Expand All @@ -1528,11 +1524,11 @@ func (s *testSerialSuite) TestSetTopSQLVariables(c *C) {

tk.MustExec("set @@global.tidb_top_sql_max_statement_count=20;")
tk.MustQuery("select @@global.tidb_top_sql_max_statement_count;").Check(testkit.Rows("20"))
c.Assert(variable.TopSQLVariable.MaxStatementCount.Load(), Equals, int64(20))
c.Assert(reporter.MaxStatementCount.Load(), Equals, int64(20))

tk.MustExec("set @@global.tidb_top_sql_max_collect=20000;")
tk.MustQuery("select @@global.tidb_top_sql_max_collect;").Check(testkit.Rows("20000"))
c.Assert(variable.TopSQLVariable.MaxCollect.Load(), Equals, int64(20000))
c.Assert(reporter.MaxCollect.Load(), Equals, int64(20000))
_, err = tk.Exec("set @@global.tidb_top_sql_max_collect='abc';")
c.Assert(err.Error(), Equals, "[variable:1232]Incorrect argument type to variable 'tidb_top_sql_max_collect'")
tk.MustExec("set @@global.tidb_top_sql_max_collect='-1';")
Expand All @@ -1545,11 +1541,11 @@ func (s *testSerialSuite) TestSetTopSQLVariables(c *C) {

tk.MustExec("set @@global.tidb_top_sql_max_collect=20000;")
tk.MustQuery("select @@global.tidb_top_sql_max_collect;").Check(testkit.Rows("20000"))
c.Assert(variable.TopSQLVariable.MaxCollect.Load(), Equals, int64(20000))
c.Assert(reporter.MaxCollect.Load(), Equals, int64(20000))

tk.MustExec("set @@global.tidb_top_sql_report_interval_seconds=120;")
tk.MustQuery("select @@global.tidb_top_sql_report_interval_seconds;").Check(testkit.Rows("120"))
c.Assert(variable.TopSQLVariable.ReportIntervalSeconds.Load(), Equals, int64(120))
c.Assert(reporter.ReportIntervalSeconds.Load(), Equals, int64(120))
_, err = tk.Exec("set @@global.tidb_top_sql_report_interval_seconds='abc';")
c.Assert(err.Error(), Equals, "[variable:1232]Incorrect argument type to variable 'tidb_top_sql_report_interval_seconds'")
tk.MustExec("set @@global.tidb_top_sql_report_interval_seconds='5000';")
Expand All @@ -1558,7 +1554,7 @@ func (s *testSerialSuite) TestSetTopSQLVariables(c *C) {

tk.MustExec("set @@global.tidb_top_sql_report_interval_seconds=120;")
tk.MustQuery("select @@global.tidb_top_sql_report_interval_seconds;").Check(testkit.Rows("120"))
c.Assert(variable.TopSQLVariable.ReportIntervalSeconds.Load(), Equals, int64(120))
c.Assert(reporter.ReportIntervalSeconds.Load(), Equals, int64(120))

// Test for hide top sql variable in show variable.
tk.MustQuery("show variables like '%top_sql%'").Check(testkit.Rows())
Expand Down
4 changes: 2 additions & 2 deletions executor/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ import (
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
plannercore "github.com/pingcap/tidb/planner/core"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/execdetails"
"github.com/pingcap/tidb/util/memory"
"github.com/pingcap/tidb/util/topsql"
"github.com/tikv/client-go/v2/txnkv/txnsnapshot"
)

Expand Down Expand Up @@ -271,7 +271,7 @@ func (e *UpdateExec) updateRows(ctx context.Context) (int, error) {
txn.GetSnapshot().SetOption(kv.CollectRuntimeStats, e.stats.SnapshotRuntimeStats)
}
}
if variable.TopSQLEnabled() {
if topsql.InstanceEnabled() {
txn, err := e.ctx.Txn(true)
if err == nil {
txn.SetOption(kv.ResourceGroupTagger, e.ctx.GetSessionVars().StmtCtx.GetResourceGroupTagger())
Expand Down
1 change: 1 addition & 0 deletions metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ func RegisterMetrics() {
prometheus.MustRegister(SmallTxnWriteDuration)
prometheus.MustRegister(TxnWriteThroughput)
prometheus.MustRegister(LoadSysVarCacheCounter)
prometheus.MustRegister(TopSQLProfileCounter)
prometheus.MustRegister(TopSQLIgnoredCounter)
prometheus.MustRegister(TopSQLReportDurationHistogram)
prometheus.MustRegister(TopSQLReportDataHistogram)
Expand Down
8 changes: 8 additions & 0 deletions metrics/topsql.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ import "github.com/prometheus/client_golang/prometheus"

// Top SQL metrics.
var (
TopSQLProfileCounter = prometheus.NewCounter(
prometheus.CounterOpts{
Namespace: "tidb",
Subsystem: "topsql",
Name: "profile_total",
Help: "Counter of profiling",
})

TopSQLIgnoredCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: "tidb",
Expand Down
Loading