-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
registry.go
2102 lines (1934 loc) · 71.2 KB
/
registry.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 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 jobs
import (
"context"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/multitenant"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/server/tracedumper"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catpb"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"github.com/cockroachdb/cockroach/pkg/sql/sem/builtins"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlliveness"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/pprofutil"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/errors/oserror"
"github.com/cockroachdb/logtags"
)
// adoptedJobs represents a the epoch and cancelation of a job id being run
// by the registry.
type adoptedJob struct {
session sqlliveness.Session
isIdle bool
// Calling the func will cancel the context the job was resumed with.
cancel context.CancelFunc
}
// adoptionNotice is used by Run to notify the registry to resumeClaimedJobs
// and by TestingNudgeAdoptionQueue to claimAndResumeClaimedJobs.
type adoptionNotice bool
const (
resumeClaimedJobs adoptionNotice = false
claimAndResumeClaimedJobs adoptionNotice = true
)
// Registry creates Jobs and manages their leases and cancelation.
//
// Job information is stored in the `system.jobs` table. Each node will
// poll this table and establish a lease on any claimed job. Registry
// calculates its own liveness for a node based on the expiration time
// of the underlying node-liveness lease. This is because we want to
// allow jobs assigned to temporarily non-live (i.e. saturated) nodes to
// continue without being canceled.
//
// When a lease has been determined to be stale, a node may attempt to
// claim the relevant job. Thus, a Registry must occasionally
// re-validate its own leases to ensure that another node has not stolen
// the work and cancel the local job if so.
//
// Prior versions of Registry used the node's epoch value to determine
// whether or not a job should be stolen. The current implementation
// uses a time-based approach, where a node's last reported expiration
// timestamp is used to calculate a liveness value for the purpose
// of job scheduling.
//
// Mixed-version operation between epoch- and time-based nodes works
// since we still publish epoch information in the leases for time-based
// nodes. From the perspective of a time-based node, an epoch-based
// node simply behaves as though its leniency period is 0. Epoch-based
// nodes will see time-based nodes delay the act of stealing a job.
type Registry struct {
serverCtx context.Context
ac log.AmbientContext
stopper *stop.Stopper
clock *hlc.Clock
clusterID *base.ClusterIDContainer
nodeID *base.SQLIDContainer
settings *cluster.Settings
execCtx jobExecCtxMaker
metrics Metrics
td *tracedumper.TraceDumper
knobs TestingKnobs
// adoptionChan is used to nudge the registry to resume claimed jobs and
// potentially attempt to claim jobs.
adoptionCh chan adoptionNotice
sqlInstance sqlliveness.Instance
// db is used by the jobs subsystem to manage job records.
//
// This isql.DB is instantiated with special parameters that are
// tailored to job management. It is not suitable for execution of
// SQL queries by job resumers.
//
// Instead resumer functions should reach for the isql.DB that comes
// from the SQl executor config.
db isql.DB
// if non-empty, indicates path to file that prevents any job adoptions.
preventAdoptionFile string
preventAdoptionLogEvery log.EveryN
mu struct {
syncutil.Mutex
// adoptedJobs holds a map from job id to its context cancel func and epoch.
// It contains the jobs that are adopted and probably being run. One exception is
// jobs scheduled inside a transaction, they will show in this map but will
// only be run when the transaction commits.
adoptedJobs map[jobspb.JobID]*adoptedJob
// waiting is a set of jobs for which we're waiting to complete. In general,
// we expect these jobs to have been started with a claim by this instance.
// That may not have lasted to completion. Separately a goroutine will be
// passively polling for these jobs to complete. If they complete locally,
// the waitingSet will be updated appropriately.
waiting jobWaitingSets
// draining indicates whether this node is draining or
// not. It is set by the drain server when the drain
// process starts.
draining bool
// numDrainWait is the number of jobs that are still
// processing drain request.
numDrainWait int
// ingestingJobs is a map of jobs which are actively ingesting on this node
// including via a processor.
ingestingJobs map[jobspb.JobID]struct{}
}
// drainRequested signaled to indicate that this registry will shut
// down soon. It's an opportunity for currently running jobs
// to detect this (OnDrain) and to have a bit of time to do cleanup/shutdown
// in an orderly fashion, prior to resumer context being canceled.
// The registry will no longer adopt new jobs once this channel closed.
drainRequested chan struct{}
// jobDrained signaled to indicate that the job watching drainRequested channel
// completed its drain logic.
jobDrained chan struct{}
// drainJobs closed when registry should drain/cancel all active
// jobs and should no longer adopt new jobs.
drainJobs chan struct{}
startedControllerTasksWG sync.WaitGroup
// withSessionEvery ensures that logging when failing to get a live session
// is not too loud.
withSessionEvery log.EveryN
// test only overrides for resumer creation.
creationKnobs sync.Map
}
func (r *Registry) UpdateJobWithTxn(
ctx context.Context, jobID jobspb.JobID, txn isql.Txn, useReadLock bool, updateFunc UpdateFn,
) error {
job, err := r.LoadJobWithTxn(ctx, jobID, txn)
if err != nil {
return err
}
return job.WithTxn(txn).Update(ctx, updateFunc)
}
// jobExecCtxMaker is a wrapper around sql.NewInternalPlanner. It returns an
// *sql.planner as an interface{} due to package dependency cycles. It should
// be cast to that type in the sql package when it is used. Returns a cleanup
// function that must be called once the caller is done with the planner.
//
// TODO(mjibson): Can we do something to avoid passing an interface{} here
// that must be cast in a Resumer? It cannot be done here because
// JobExecContext lives in the sql package, which would create a dependency
// cycle if listed here. Furthermore, moving JobExecContext into a common
// subpackage like sqlbase is difficult because of the amount of sql-only
// stuff that JobExecContext exports. One other choice is to merge this package
// back into the sql package. There's maybe a better way that I'm unaware of.
type jobExecCtxMaker func(ctx context.Context, opName string, user username.SQLUsername) (interface{}, func())
// PreventAdoptionFile is the name of the file which, if present in the first
// on-disk store, will prevent the adoption of background jobs by that node.
const PreventAdoptionFile = "DISABLE_STARTING_BACKGROUND_JOBS"
// MakeRegistry creates a new Registry. planFn is a wrapper around
// sql.newInternalPlanner. It returns a sql.JobExecCtx, but must be
// coerced into that in the Resumer functions.
func MakeRegistry(
ctx context.Context,
ac log.AmbientContext,
stopper *stop.Stopper,
clock *hlc.Clock,
clusterID *base.ClusterIDContainer,
nodeID *base.SQLIDContainer,
sqlInstance sqlliveness.Instance,
settings *cluster.Settings,
histogramWindowInterval time.Duration,
execCtxFn jobExecCtxMaker,
preventAdoptionFile string,
td *tracedumper.TraceDumper,
knobs *TestingKnobs,
) *Registry {
r := &Registry{
serverCtx: ctx,
ac: ac,
stopper: stopper,
clock: clock,
clusterID: clusterID,
nodeID: nodeID,
sqlInstance: sqlInstance,
settings: settings,
execCtx: execCtxFn,
preventAdoptionFile: preventAdoptionFile,
preventAdoptionLogEvery: log.Every(time.Minute),
td: td,
// Use a non-zero buffer to allow queueing of notifications.
// The writing method will use a default case to avoid blocking
// if a notification is already queued.
adoptionCh: make(chan adoptionNotice, 1),
withSessionEvery: log.Every(time.Second),
drainJobs: make(chan struct{}),
drainRequested: make(chan struct{}),
jobDrained: make(chan struct{}, 1),
}
if knobs != nil {
r.knobs = *knobs
if knobs.TimeSource != nil {
r.clock = knobs.TimeSource
}
}
r.mu.adoptedJobs = make(map[jobspb.JobID]*adoptedJob)
r.mu.waiting = make(map[jobspb.JobID]map[*waitingSet]struct{})
r.metrics.init(histogramWindowInterval)
return r
}
// SetInternalDB sets the DB that will be used by the job registry
// executor. We expose this separately from the constructor to avoid a circular
// dependency.
func (r *Registry) SetInternalDB(db isql.DB) {
r.db = db
}
// MetricsStruct returns the metrics for production monitoring of each job type.
// They're all stored as the `metric.Struct` interface because of dependency
// cycles.
func (r *Registry) MetricsStruct() *Metrics {
return &r.metrics
}
// CurrentlyRunningJobs returns a slice of the ids of all jobs running on this node.
func (r *Registry) CurrentlyRunningJobs() []jobspb.JobID {
r.mu.Lock()
defer r.mu.Unlock()
jobs := make([]jobspb.JobID, 0, len(r.mu.adoptedJobs))
for jID := range r.mu.adoptedJobs {
jobs = append(jobs, jID)
}
return jobs
}
// ID returns a unique during the lifetime of the registry id that is
// used for keying sqlliveness claims held by the registry.
func (r *Registry) ID() base.SQLInstanceID {
return r.nodeID.SQLInstanceID()
}
// makeCtx returns a new context from r's ambient context and an associated
// cancel func.
func (r *Registry) makeCtx() (context.Context, func()) {
ctx := r.ac.AnnotateCtx(context.Background())
// AddTags and not WithTags, so that we combine the tags with those
// filled by AnnotateCtx.
// TODO(knz): This may not be necessary if the AmbientContext had
// all the tags already.
// See: https://github.com/cockroachdb/cockroach/issues/72815
ctx = logtags.AddTags(ctx, logtags.FromContext(r.serverCtx))
return context.WithCancel(ctx)
}
// A static Job ID must be sufficiently small to avoid collisions with
// IDs generated by MakeJobID.
const (
// KeyVisualizerJobID A static job ID is used to easily check if the
// Key Visualizer job already exists.
KeyVisualizerJobID = jobspb.JobID(100)
// JobMetricsPollerJobID A static job ID is used for the job metrics polling job.
JobMetricsPollerJobID = jobspb.JobID(101)
// AutoConfigRunnerJobID A static job ID is used for the auto config runner job.
AutoConfigRunnerJobID = jobspb.JobID(102)
// SqlActivityUpdaterJobID A static job ID is used for the SQL activity tables.
SqlActivityUpdaterJobID = jobspb.JobID(103)
)
// MakeJobID generates a new job ID.
func (r *Registry) MakeJobID() jobspb.JobID {
return jobspb.JobID(builtins.GenerateUniqueInt(
builtins.ProcessUniqueID(r.nodeID.SQLInstanceID()),
))
}
// newJob creates a new Job.
func (r *Registry) newJob(ctx context.Context, record Record) (*Job, error) {
job := &Job{
id: record.JobID,
registry: r,
createdBy: record.CreatedBy,
}
payload, err := r.makePayload(ctx, &record)
if err != nil {
return nil, err
}
job.mu.payload = payload
job.mu.progress = r.makeProgress(&record)
job.mu.status = StatusRunning
return job, nil
}
// makePayload creates a Payload structure based on the given Record.
func (r *Registry) makePayload(ctx context.Context, record *Record) (jobspb.Payload, error) {
if record.Username.Undefined() {
return jobspb.Payload{}, errors.AssertionFailedf("job record missing username; could not make payload")
}
return jobspb.Payload{
Description: record.Description,
Statement: record.Statements,
UsernameProto: record.Username.EncodeProto(),
DescriptorIDs: record.DescriptorIDs,
Details: jobspb.WrapPayloadDetails(record.Details),
Noncancelable: record.NonCancelable,
CreationClusterVersion: r.settings.Version.ActiveVersion(ctx).Version,
CreationClusterID: r.clusterID.Get(),
MaximumPTSAge: record.MaximumPTSAge,
}, nil
}
// makeProgress creates a Progress structure based on the given Record.
func (r *Registry) makeProgress(record *Record) jobspb.Progress {
return jobspb.Progress{
Details: jobspb.WrapProgressDetails(record.Progress),
RunningStatus: string(record.RunningStatus),
}
}
// CreateJobsWithTxn creates jobs in fixed-size batches. There must be at least
// one job to create, otherwise the function returns an error. The function
// returns the IDs of the jobs created.
func (r *Registry) CreateJobsWithTxn(
ctx context.Context, txn isql.Txn, records []*Record,
) ([]jobspb.JobID, error) {
created := make([]jobspb.JobID, 0, len(records))
for toCreate := records; len(toCreate) > 0; {
const maxBatchSize = 100
batchSize := len(toCreate)
if batchSize > maxBatchSize {
batchSize = maxBatchSize
}
createdInBatch, err := createJobsInBatchWithTxn(ctx, r, txn, toCreate[:batchSize])
if err != nil {
return nil, err
}
created = append(created, createdInBatch...)
toCreate = toCreate[batchSize:]
}
return created, nil
}
// createJobsInBatchWithTxn creates a batch of jobs from given records in a
// transaction.
func createJobsInBatchWithTxn(
ctx context.Context, r *Registry, txn isql.Txn, records []*Record,
) ([]jobspb.JobID, error) {
s, err := r.sqlInstance.Session(ctx)
if err != nil {
return nil, errors.Wrap(err, "error getting live session")
}
start := txn.KV().ReadTimestamp().GoTime()
modifiedMicros := timeutil.ToUnixMicros(start)
jobs := make([]*Job, len(records))
for i, record := range records {
j, err := r.newJob(ctx, *record)
if err != nil {
return nil, err
}
jobs[i] = j
}
stmt, args, jobIDs, err := batchJobInsertStmt(ctx, r, s.ID(), jobs, modifiedMicros)
if err != nil {
return nil, err
}
_, err = txn.ExecEx(
ctx, "job-rows-batch-insert", txn.KV(),
sessiondata.RootUserSessionDataOverride,
stmt, args...,
)
if err != nil {
return nil, err
}
// Insert the job payload and details into the system.jobs_info table if the
// associated cluster version is active.
//
// TODO(adityamaru): Stop writing the payload and details to the system.jobs
// table once we are outside the compatability window for 22.2.
if r.settings.Version.IsActive(ctx, clusterversion.V23_1CreateSystemJobInfoTable) {
if err := batchJobWriteToJobInfo(ctx, txn, jobs, modifiedMicros); err != nil {
return nil, err
}
}
return jobIDs, nil
}
func batchJobWriteToJobInfo(
ctx context.Context, txn isql.Txn, jobs []*Job, modifiedMicros int64,
) error {
for _, j := range jobs {
infoStorage := j.InfoStorage(txn)
payload := j.Payload()
var payloadBytes, progressBytes []byte
var err error
if payloadBytes, err = protoutil.Marshal(&payload); err != nil {
return err
}
if err := infoStorage.WriteLegacyPayload(ctx, payloadBytes); err != nil {
return err
}
progress := j.Progress()
if progressBytes, err = protoutil.Marshal(&progress); err != nil {
return err
}
progress.ModifiedMicros = modifiedMicros
if err := infoStorage.WriteLegacyProgress(ctx, progressBytes); err != nil {
return err
}
}
return nil
}
// batchJobInsertStmt creates an INSERT statement and its corresponding arguments
// for batched jobs creation.
func batchJobInsertStmt(
ctx context.Context,
r *Registry,
sessionID sqlliveness.SessionID,
jobs []*Job,
modifiedMicros int64,
) (string, []interface{}, []jobspb.JobID, error) {
marshalPanic := func(m protoutil.Message) []byte {
data, err := protoutil.Marshal(m)
if err != nil {
panic(err)
}
return data
}
created, err := tree.MakeDTimestamp(timeutil.FromUnixMicros(modifiedMicros), time.Microsecond)
if err != nil {
return "", nil, nil, errors.NewAssertionErrorWithWrappedErrf(err, "failed to make timestamp for creation of job")
}
instanceID := r.ID()
columns := []string{`id`, `created`, `status`, `payload`, `progress`, `claim_session_id`, `claim_instance_id`, `job_type`}
valueFns := map[string]func(*Job) (interface{}, error){
`id`: func(job *Job) (interface{}, error) { return job.ID(), nil },
`created`: func(job *Job) (interface{}, error) { return created, nil },
`status`: func(job *Job) (interface{}, error) { return StatusRunning, nil },
`claim_session_id`: func(job *Job) (interface{}, error) { return sessionID.UnsafeBytes(), nil },
`claim_instance_id`: func(job *Job) (interface{}, error) { return instanceID, nil },
`payload`: func(job *Job) (interface{}, error) {
payload := job.Payload()
return marshalPanic(&payload), nil
},
`progress`: func(job *Job) (interface{}, error) {
progress := job.Progress()
progress.ModifiedMicros = modifiedMicros
return marshalPanic(&progress), nil
},
`job_type`: func(job *Job) (interface{}, error) {
payload := job.Payload()
return payload.Type().String(), nil
},
}
// TODO(adityamaru: Remove this once we are outside the compatability
// window for 22.2.
if r.settings.Version.IsActive(ctx, clusterversion.V23_1StopWritingPayloadAndProgressToSystemJobs) {
columns = []string{`id`, `created`, `status`, `claim_session_id`, `claim_instance_id`, `job_type`}
valueFns = map[string]func(*Job) (interface{}, error){
`id`: func(job *Job) (interface{}, error) { return job.ID(), nil },
`created`: func(job *Job) (interface{}, error) { return created, nil },
`status`: func(job *Job) (interface{}, error) { return StatusRunning, nil },
`claim_session_id`: func(job *Job) (interface{}, error) { return sessionID.UnsafeBytes(), nil },
`claim_instance_id`: func(job *Job) (interface{}, error) { return instanceID, nil },
`job_type`: func(job *Job) (interface{}, error) {
payload := job.Payload()
return payload.Type().String(), nil
},
}
}
numColumns := len(columns)
// TODO(jayant): remove this version gate in 24.1
// To run the upgrade below, migration and schema change jobs will need to be
// created using the old schema, which does not have the job_type column.
if !r.settings.Version.IsActive(ctx, clusterversion.V23_1AddTypeColumnToJobsTable) {
numColumns -= 1
}
appendValues := func(job *Job, vals *[]interface{}) (err error) {
defer func() {
switch r := recover(); r.(type) {
case nil:
case error:
err = errors.CombineErrors(err, errors.Wrapf(r.(error), "encoding job %d", job.ID()))
default:
panic(r)
}
}()
for j := 0; j < numColumns; j++ {
c := columns[j]
val, err := valueFns[c](job)
if err != nil {
return err
}
*vals = append(*vals, val)
}
return nil
}
args := make([]interface{}, 0, len(jobs)*numColumns)
jobIDs := make([]jobspb.JobID, 0, len(jobs))
var buf strings.Builder
buf.WriteString(`INSERT INTO system.jobs (`)
buf.WriteString(strings.Join(columns[:numColumns], ", "))
buf.WriteString(`) VALUES `)
argIdx := 1
for i, job := range jobs {
if i > 0 {
buf.WriteString(", ")
}
buf.WriteString("(")
for j := 0; j < numColumns; j++ {
if j > 0 {
buf.WriteString(", ")
}
buf.WriteString("$")
buf.WriteString(strconv.Itoa(argIdx))
argIdx++
}
buf.WriteString(")")
if err := appendValues(job, &args); err != nil {
return "", nil, nil, err
}
jobIDs = append(jobIDs, job.ID())
}
return buf.String(), args, jobIDs, nil
}
// CreateJobWithTxn creates a job to be started later with StartJob. It stores
// the job in the jobs table, marks it pending and gives the current node a
// lease.
func (r *Registry) CreateJobWithTxn(
ctx context.Context, record Record, jobID jobspb.JobID, txn isql.Txn,
) (*Job, error) {
// TODO(sajjad): Clean up the interface - remove jobID from the params as
// Record now has JobID field.
record.JobID = jobID
j, err := r.newJob(ctx, record)
if err != nil {
return nil, err
}
do := func(ctx context.Context, txn isql.Txn) error {
s, err := r.sqlInstance.Session(ctx)
if err != nil {
return errors.Wrap(err, "error getting live session")
}
j.session = s
start := timeutil.Now()
if txn != nil {
start = txn.KV().ReadTimestamp().GoTime()
}
jobType := j.mu.payload.Type()
j.mu.progress.ModifiedMicros = timeutil.ToUnixMicros(start)
payloadBytes, err := protoutil.Marshal(&j.mu.payload)
if err != nil {
return err
}
progressBytes, err := protoutil.Marshal(&j.mu.progress)
if err != nil {
return err
}
created, err := tree.MakeDTimestamp(start, time.Microsecond)
if err != nil {
return errors.NewAssertionErrorWithWrappedErrf(err, "failed to construct job created timestamp")
}
cols := []string{"id", "created", "status", "payload", "progress", "claim_session_id", "claim_instance_id", "job_type"}
vals := []interface{}{jobID, created, StatusRunning, payloadBytes, progressBytes, s.ID().UnsafeBytes(), r.ID(), jobType.String()}
if r.settings.Version.IsActive(ctx, clusterversion.V23_1StopWritingPayloadAndProgressToSystemJobs) {
cols = []string{"id", "created", "status", "claim_session_id", "claim_instance_id", "job_type"}
vals = []interface{}{jobID, created, StatusRunning, s.ID().UnsafeBytes(), r.ID(), jobType.String()}
}
totalNumCols := len(cols)
numCols := totalNumCols
placeholders := func() string {
var p strings.Builder
for i := 0; i < numCols; i++ {
if i > 0 {
p.WriteByte(',')
}
p.WriteByte('$')
p.WriteString(strconv.Itoa(i + 1))
}
return p.String()
}
// We need to override the database in case we're in a situation where the
// database in question is being dropped.
override := sessiondata.RootUserSessionDataOverride
override.Database = catconstants.SystemDatabaseName
hasJobTypeColumn := r.settings.Version.IsActive(ctx, clusterversion.V23_1AddTypeColumnToJobsTable)
if hasJobTypeColumn {
// Relying on the version gate may not be sufficient.
const pgAttributeStmt = `
SELECT * FROM system.pg_catalog.pg_attribute
WHERE attrelid = 'system.public.jobs'::REGCLASS
AND attname = 'job_type'`
row, err := txn.QueryRowEx(ctx, "job-columns-get", txn.KV(), override, pgAttributeStmt)
if err != nil {
return err
}
hasJobTypeColumn = row != nil
}
if !hasJobTypeColumn {
numCols -= 1
}
insertStmt := fmt.Sprintf(`INSERT INTO system.jobs (%s) VALUES (%s)`,
strings.Join(cols[:numCols], ","), placeholders())
_, err = txn.ExecEx(
ctx, "job-row-insert", txn.KV(),
override,
insertStmt, vals[:numCols]...,
)
if err != nil {
return err
}
// Insert the job payload and details into the system.jobs_info table if the
// associated cluster version is active.
//
// TODO(adityamaru): Stop writing the payload and details to the system.jobs
// table once we are outside the compatability window for 22.2.
if r.settings.Version.IsActive(ctx, clusterversion.V23_1CreateSystemJobInfoTable) {
infoStorage := j.InfoStorage(txn)
if err := infoStorage.WriteLegacyPayload(ctx, payloadBytes); err != nil {
return err
}
if err := infoStorage.WriteLegacyProgress(ctx, progressBytes); err != nil {
return err
}
}
return nil
}
run := r.db.Txn
if txn != nil {
run = func(
ctx context.Context, f func(context.Context, isql.Txn) error,
_ ...isql.TxnOption,
) error {
return f(ctx, txn)
}
}
if err := run(ctx, do); err != nil {
return nil, err
}
return j, nil
}
// CreateIfNotExistAdoptableJobWithTxn checks if a job already exists in
// the system.jobs table, and if it does not it will create the job. The job
// will be adopted for execution at a later time by some node in the cluster.
func (r *Registry) CreateIfNotExistAdoptableJobWithTxn(
ctx context.Context, record Record, txn isql.Txn,
) error {
if record.JobID == 0 {
return fmt.Errorf("invalid record.JobID value: %d", record.JobID)
}
if txn == nil {
return fmt.Errorf("txn is required for job: %d", record.JobID)
}
// Make sure job with id doesn't already exist in system.jobs.
// Use a txn to avoid race conditions
row, err := txn.QueryRowEx(
ctx,
"check if job exists",
txn.KV(),
sessiondata.InternalExecutorOverride{User: username.RootUserName()},
"SELECT id FROM system.jobs WHERE id = $1",
record.JobID,
)
if err != nil {
return err
}
// If there isn't a row for the job, create the job.
if row == nil {
if _, err = r.CreateAdoptableJobWithTxn(ctx, record, record.JobID, txn); err != nil {
return err
}
}
return nil
}
// CreateAdoptableJobWithTxn creates a job which will be adopted for execution
// at a later time by some node in the cluster.
func (r *Registry) CreateAdoptableJobWithTxn(
ctx context.Context, record Record, jobID jobspb.JobID, txn isql.Txn,
) (*Job, error) {
// TODO(sajjad): Clean up the interface - remove jobID from the params as
// Record now has JobID field.
record.JobID = jobID
j, err := r.newJob(ctx, record)
if err != nil {
return nil, err
}
do := func(ctx context.Context, txn isql.Txn) error {
// Note: although the following uses ReadTimestamp and
// ReadTimestamp can diverge from the value of now() throughout a
// transaction, this may be OK -- we merely required ModifiedMicro
// to be equal *or greater* than previously inserted timestamps
// computed by now(). For now ReadTimestamp can only move forward
// and the assertion ReadTimestamp >= now() holds at all times.
j.mu.progress.ModifiedMicros = timeutil.ToUnixMicros(txn.KV().ReadTimestamp().GoTime())
payloadBytes, err := protoutil.Marshal(&j.mu.payload)
if err != nil {
return err
}
progressBytes, err := protoutil.Marshal(&j.mu.progress)
if err != nil {
return err
}
// Set createdByType and createdByID to NULL if we don't know them.
var createdByType, createdByID interface{}
if j.createdBy != nil {
createdByType = j.createdBy.Name
createdByID = j.createdBy.ID
}
typ := j.mu.payload.Type().String()
nCols := 7
cols := []string{"id", "status", "payload", "progress", "created_by_type", "created_by_id", "job_type"}
placeholders := []string{"$1", "$2", "$3", "$4", "$5", "$6", "$7"}
values := []interface{}{jobID, StatusRunning, payloadBytes, progressBytes, createdByType, createdByID, typ}
if !r.settings.Version.IsActive(ctx, clusterversion.V23_1AddTypeColumnToJobsTable) {
nCols -= 1
}
if r.settings.Version.IsActive(ctx, clusterversion.V23_1StopWritingPayloadAndProgressToSystemJobs) {
cols = []string{"id", "status", "created_by_type", "created_by_id", "job_type"}
placeholders = []string{"$1", "$2", "$3", "$4", "$5"}
values = []interface{}{jobID, StatusRunning, createdByType, createdByID, typ}
nCols = 5
}
// Insert the job row, but do not set a `claim_session_id`. By not
// setting the claim, the job can be adopted by any node and will
// be adopted by the node which next runs the adoption loop.
stmt := fmt.Sprintf(
`INSERT INTO system.jobs (%s) VALUES (%s);`,
strings.Join(cols[:nCols], ","), strings.Join(placeholders[:nCols], ","),
)
_, err = txn.ExecEx(ctx, "job-insert", txn.KV(), sessiondata.InternalExecutorOverride{
User: username.NodeUserName(),
Database: catconstants.SystemDatabaseName,
}, stmt, values[:nCols]...)
if err != nil {
return err
}
// Insert the job payload and details into the system.jobs_info table if the
// associated cluster version is active.
//
// TODO(adityamaru): Stop writing the payload and details to the system.jobs
// table once we are outside the compatability window for 22.2.
if r.settings.Version.IsActive(ctx, clusterversion.V23_1CreateSystemJobInfoTable) {
infoStorage := j.InfoStorage(txn)
if err := infoStorage.WriteLegacyPayload(ctx, payloadBytes); err != nil {
return err
}
if err := infoStorage.WriteLegacyProgress(ctx, progressBytes); err != nil {
return err
}
}
return nil
}
run := r.db.Txn
if txn != nil {
run = func(
ctx context.Context, f func(context.Context, isql.Txn) error,
_ ...isql.TxnOption,
) error {
return f(ctx, txn)
}
}
if err := run(ctx, do); err != nil {
return nil, errors.Wrap(err, "CreateAdoptableJobInTxn")
}
return j, nil
}
// CreateStartableJobWithTxn creates a job to be started later, after the
// creating txn commits. The method uses the passed txn to write the job in the
// jobs table, marks it pending and gives the current node a lease. It
// additionally registers the job with the Registry which will prevent the
// Registry from adopting the job after the transaction commits. The resultsCh
// will be connected to the output of the job and written to after the returned
// StartableJob is started.
//
// The returned job is not associated with the user transaction. The intention
// is that the job will not be modified again in txn. If the transaction is
// committed, the caller must explicitly Start it. If the transaction is rolled
// back then the caller must call CleanupOnRollback to unregister the job from
// the Registry.
//
// When used in a closure that is retryable in the presence of transaction
// restarts, the job ID must be stable across retries to avoid leaking tracing
// spans and registry entries. The intended usage is to define the ID and
// *StartableJob outside the closure. The StartableJob referred to will remain
// the same if the method is called with the same job ID and has already been
// initialized with a tracing span and registered; otherwise, a new one will be
// allocated, and sj will point to it. The point is to ensure that the tracing
// span is created and the job registered exactly once, if and only if the
// transaction commits. This is a fragile API.
func (r *Registry) CreateStartableJobWithTxn(
ctx context.Context, sj **StartableJob, jobID jobspb.JobID, txn isql.Txn, record Record,
) error {
if txn == nil {
return errors.AssertionFailedf("cannot create a startable job without a txn")
}
alreadyInitialized := *sj != nil
if alreadyInitialized {
if jobID != (*sj).Job.ID() {
log.Fatalf(ctx,
"attempted to rewrite startable job for ID %d with unexpected ID %d",
(*sj).Job.ID(), jobID,
)
}
}
j, err := r.CreateJobWithTxn(ctx, record, jobID, txn)
if err != nil {
return err
}
resumer, err := r.createResumer(j, r.settings)
if err != nil {
return err
}
var resumerCtx context.Context
var cancel func()
var execDone chan struct{}
if !alreadyInitialized {
// Using a new context allows for independent lifetimes and cancellation.
resumerCtx, cancel = r.makeCtx()
if alreadyAdopted := r.addAdoptedJob(jobID, j.session, cancel); alreadyAdopted {
log.Fatalf(
ctx,
"job %d: was just created but found in registered adopted jobs",
jobID,
)
}
execDone = make(chan struct{})
}
if !alreadyInitialized {
*sj = &StartableJob{}
(*sj).resumerCtx = resumerCtx
(*sj).cancel = cancel
(*sj).execDone = execDone
}
(*sj).Job = j
(*sj).resumer = resumer
(*sj).txn = txn.KV()
return nil
}
// LoadJob loads an existing job with the given jobID from the system.jobs
// table.
//
// WARNING: Avoid new uses of this function. The returned Job allows
// for mutation even if the instance no longer holds a valid claim on
// the job.
//
// TODO(ssd): Remove this API and replace it with a safer API.
func (r *Registry) LoadJob(ctx context.Context, jobID jobspb.JobID) (*Job, error) {
return r.LoadJobWithTxn(ctx, jobID, nil)
}
// LoadClaimedJob loads an existing job with the given jobID from the
// system.jobs table. The job must have already been claimed by this
// Registry.
func (r *Registry) LoadClaimedJob(ctx context.Context, jobID jobspb.JobID) (*Job, error) {
j, err := r.getClaimedJob(jobID)
if err != nil {
return nil, err
}
if err := j.NoTxn().load(ctx); err != nil {
return nil, err
}
return j, nil
}
// LoadJobWithTxn does the same as above, but using the transaction passed in
// the txn argument. Passing a nil transaction is equivalent to calling LoadJob
// in that a transaction will be automatically created.
func (r *Registry) LoadJobWithTxn(
ctx context.Context, jobID jobspb.JobID, txn isql.Txn,
) (*Job, error) {
j := &Job{
id: jobID,
registry: r,
}
if err := j.WithTxn(txn).load(ctx); err != nil {
return nil, err
}
return j, nil
}
// UpdateJobWithTxn calls the Update method on an existing job with jobID, using
// a transaction passed in the txn argument. Passing a nil transaction means
// that a txn will be automatically created. The useReadLock parameter will
// have the update acquire an exclusive lock on the job row when reading. This
// can help eliminate restarts in the face of concurrent updates at the cost of
// locking the row from readers. Most updates of a job do not expect contention
// and may do extra work and thus should not do locking. Cases where the job
// is used to coordinate resources from multiple nodes may benefit from locking.
// TODO (sajjad): make maxAdoptionsPerLoop a cluster setting.
var maxAdoptionsPerLoop = envutil.EnvOrDefaultInt(`COCKROACH_JOB_ADOPTIONS_PER_PERIOD`, 10)
const removeClaimsForDeadSessionsQuery = `
UPDATE system.jobs
SET claim_session_id = NULL
WHERE claim_session_id in (
SELECT claim_session_id
WHERE claim_session_id <> $1
AND status IN ` + claimableStatusTupleString + `
AND NOT crdb_internal.sql_liveness_is_alive(claim_session_id)
FETCH FIRST $2 ROWS ONLY)
`
const removeClaimsForSessionQuery = `
UPDATE system.jobs
SET claim_session_id = NULL
WHERE claim_session_id in (
SELECT claim_session_id
WHERE claim_session_id = $1
AND status IN ` + claimableStatusTupleString + `
)`
type withSessionFunc func(ctx context.Context, s sqlliveness.Session)
func (r *Registry) withSession(ctx context.Context, f withSessionFunc) {
s, err := r.sqlInstance.Session(ctx)
if err != nil {