-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathcompact_sql_stats.go
274 lines (236 loc) · 8.15 KB
/
compact_sql_stats.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package sql
import (
"context"
"fmt"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/scheduledjobs"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats/persistedsqlstats"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/errors"
)
type sqlStatsCompactionResumer struct {
job *jobs.Job
st *cluster.Settings
sj *jobs.ScheduledJob
}
var _ jobs.Resumer = &sqlStatsCompactionResumer{}
// Resume implements the jobs.Resumer interface.
func (r *sqlStatsCompactionResumer) Resume(ctx context.Context, execCtx interface{}) error {
log.Infof(ctx, "starting sql stats compaction job")
p := execCtx.(JobExecContext)
ie := p.ExecCfg().InternalExecutor
db := p.ExecCfg().DB
var (
scheduledJobID int64
err error
)
if err = db.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
scheduledJobID, err = r.getScheduleID(ctx, ie, txn, scheduledjobs.ProdJobSchedulerEnv)
if err != nil {
return err
}
if scheduledJobID != jobs.InvalidScheduleID {
r.sj, err = jobs.LoadScheduledJob(ctx, scheduledjobs.ProdJobSchedulerEnv, scheduledJobID, ie, txn)
if err != nil {
return err
}
r.sj.SetScheduleStatus(string(jobs.StatusRunning))
return r.sj.Update(ctx, ie, txn)
}
return nil
}); err != nil {
return err
}
// We check for concurrently running SQL Stats compaction jobs. We only allow
// one job to be running at the same time.
if err := persistedsqlstats.CheckExistingCompactionJob(ctx, r.job, ie, nil /* txn */); err != nil {
if errors.Is(err, persistedsqlstats.ErrConcurrentSQLStatsCompaction) {
log.Infof(ctx, "exiting due to a running sql stats compaction job")
}
return err
}
statsCompactor := persistedsqlstats.NewStatsCompactor(
r.st,
ie,
db,
ie.s.Metrics.StatsMetrics.SQLStatsRemovedRows,
p.ExecCfg().SQLStatsTestingKnobs)
if err = statsCompactor.DeleteOldestEntries(ctx); err != nil {
return err
}
return r.maybeNotifyJobTerminated(
ctx,
ie,
p.ExecCfg(),
jobs.StatusSucceeded)
}
// OnFailOrCancel implements the jobs.Resumer interface.
func (r *sqlStatsCompactionResumer) OnFailOrCancel(ctx context.Context, execCtx interface{}) error {
p := execCtx.(JobExecContext)
execCfg := p.ExecCfg()
ie := execCfg.InternalExecutor
return r.maybeNotifyJobTerminated(ctx, ie, execCfg, jobs.StatusFailed)
}
// maybeNotifyJobTerminated will notify the job termination
// (with termination status).
func (r *sqlStatsCompactionResumer) maybeNotifyJobTerminated(
ctx context.Context, ie sqlutil.InternalExecutor, exec *ExecutorConfig, status jobs.Status,
) error {
log.Infof(ctx, "sql stats compaction job terminated with status = %s", status)
if r.sj != nil {
env := scheduledjobs.ProdJobSchedulerEnv
if knobs, ok := exec.DistSQLSrv.TestingKnobs.JobsTestingKnobs.(*jobs.TestingKnobs); ok {
if knobs.JobSchedulerEnv != nil {
env = knobs.JobSchedulerEnv
}
}
if err := jobs.NotifyJobTermination(
ctx, env, r.job.ID(), status, r.job.Details(), r.sj.ScheduleID(),
ie, nil /* txn */); err != nil {
return err
}
return nil
}
return nil
}
func (r *sqlStatsCompactionResumer) getScheduleID(
ctx context.Context, ie sqlutil.InternalExecutor, txn *kv.Txn, env scheduledjobs.JobSchedulerEnv,
) (scheduleID int64, _ error) {
row, err := ie.QueryRowEx(ctx, "lookup-sql-stats-schedule", txn,
sessiondata.InternalExecutorOverride{User: security.NodeUserName()},
fmt.Sprintf("SELECT created_by_id FROM %s WHERE id=$1 AND created_by_type=$2", env.SystemJobsTableName()),
r.job.ID(), jobs.CreatedByScheduledJobs,
)
if err != nil {
return jobs.InvalidScheduleID, errors.Wrap(err, "fail to look up scheduled information")
}
if row == nil {
// Compaction not triggered by a scheduled job.
return jobs.InvalidScheduleID, nil
}
scheduleID = int64(tree.MustBeDInt(row[0]))
return scheduleID, nil
}
type sqlStatsCompactionMetrics struct {
*jobs.ExecutorMetrics
}
var _ metric.Struct = &sqlStatsCompactionMetrics{}
// MetricStruct implements metric.Struct interface.
func (m *sqlStatsCompactionMetrics) MetricStruct() {}
// scheduledSQLStatsCompactionExecutor is executed by scheduledjob subsystem
// to launch sqlStatsCompactionResumer through the job subsystem.
type scheduledSQLStatsCompactionExecutor struct {
metrics sqlStatsCompactionMetrics
}
var _ jobs.ScheduledJobExecutor = &scheduledSQLStatsCompactionExecutor{}
var _ jobs.ScheduledJobController = &scheduledSQLStatsCompactionExecutor{}
// OnDrop implements the jobs.ScheduledJobController interface.
func (e *scheduledSQLStatsCompactionExecutor) OnDrop(
ctx context.Context,
scheduleControllerEnv scheduledjobs.ScheduleControllerEnv,
env scheduledjobs.JobSchedulerEnv,
schedule *jobs.ScheduledJob,
txn *kv.Txn,
) error {
return persistedsqlstats.ErrScheduleUndroppable
}
// ExecuteJob implements the jobs.ScheduledJobExecutor interface.
func (e *scheduledSQLStatsCompactionExecutor) ExecuteJob(
ctx context.Context,
cfg *scheduledjobs.JobExecutionConfig,
env scheduledjobs.JobSchedulerEnv,
sj *jobs.ScheduledJob,
txn *kv.Txn,
) error {
if err := e.createSQLStatsCompactionJob(ctx, cfg, sj, txn); err != nil {
e.metrics.NumFailed.Inc(1)
}
e.metrics.NumStarted.Inc(1)
return nil
}
func (e *scheduledSQLStatsCompactionExecutor) createSQLStatsCompactionJob(
ctx context.Context, cfg *scheduledjobs.JobExecutionConfig, sj *jobs.ScheduledJob, txn *kv.Txn,
) error {
p, cleanup := cfg.PlanHookMaker("invoke-sql-stats-compact", txn, security.NodeUserName())
defer cleanup()
_, err :=
persistedsqlstats.CreateCompactionJob(ctx, &jobs.CreatedByInfo{
ID: sj.ScheduleID(),
Name: jobs.CreatedByScheduledJobs,
}, txn, cfg.InternalExecutor, p.(*planner).ExecCfg().JobRegistry)
if err != nil {
return err
}
return nil
}
// NotifyJobTermination implements the jobs.ScheduledJobExecutor interface.
func (e *scheduledSQLStatsCompactionExecutor) NotifyJobTermination(
ctx context.Context,
jobID jobspb.JobID,
jobStatus jobs.Status,
details jobspb.Details,
env scheduledjobs.JobSchedulerEnv,
sj *jobs.ScheduledJob,
ex sqlutil.InternalExecutor,
txn *kv.Txn,
) error {
if jobStatus == jobs.StatusFailed {
jobs.DefaultHandleFailedRun(sj, "sql stats compaction %d failed", jobID)
e.metrics.NumFailed.Inc(1)
return nil
}
if jobStatus == jobs.StatusSucceeded {
e.metrics.NumSucceeded.Inc(1)
}
sj.SetScheduleStatus(string(jobStatus))
return nil
}
// Metrics implements the jobs.ScheduledJobExecutor interface.
func (e *scheduledSQLStatsCompactionExecutor) Metrics() metric.Struct {
return &e.metrics
}
// GetCreateScheduleStatement implements the jobs.ScheduledJobExecutor interface.
func (e *scheduledSQLStatsCompactionExecutor) GetCreateScheduleStatement(
_ context.Context,
_ scheduledjobs.JobSchedulerEnv,
_ *kv.Txn,
_ *jobs.ScheduledJob,
_ sqlutil.InternalExecutor,
) (string, error) {
return "SELECT crdb_internal.schedule_sql_stats_compact()", nil
}
func init() {
jobs.RegisterConstructor(jobspb.TypeAutoSQLStatsCompaction, func(job *jobs.Job, settings *cluster.Settings) jobs.Resumer {
return &sqlStatsCompactionResumer{
job: job,
st: settings,
}
})
jobs.RegisterScheduledJobExecutorFactory(
tree.ScheduledSQLStatsCompactionExecutor.InternalName(),
func() (jobs.ScheduledJobExecutor, error) {
m := jobs.MakeExecutorMetrics(tree.ScheduledSQLStatsCompactionExecutor.InternalName())
return &scheduledSQLStatsCompactionExecutor{
metrics: sqlStatsCompactionMetrics{
ExecutorMetrics: &m,
},
}, nil
})
}