forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeta.go
1122 lines (975 loc) · 32.4 KB
/
meta.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 2015 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 meta
import (
"encoding/binary"
"encoding/json"
"fmt"
"math"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/parser/model"
"github.com/pingcap/parser/mysql"
"github.com/pingcap/tidb/errno"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/metrics"
"github.com/pingcap/tidb/structure"
"github.com/pingcap/tidb/util/dbterror"
"github.com/pingcap/tidb/util/logutil"
"go.uber.org/zap"
)
var (
globalIDMutex sync.Mutex
)
// Meta structure:
// NextGlobalID -> int64
// SchemaVersion -> int64
// DBs -> {
// DB:1 -> db meta data []byte
// DB:2 -> db meta data []byte
// }
// DB:1 -> {
// Table:1 -> table meta data []byte
// Table:2 -> table meta data []byte
// TID:1 -> int64
// TID:2 -> int64
// }
//
var (
mMetaPrefix = []byte("m")
mNextGlobalIDKey = []byte("NextGlobalID")
mSchemaVersionKey = []byte("SchemaVersionKey")
mDBs = []byte("DBs")
mDBPrefix = "DB"
mTablePrefix = "Table"
mSequencePrefix = "SID"
mSeqCyclePrefix = "SequenceCycle"
mTableIDPrefix = "TID"
mRandomIDPrefix = "TARID"
mBootstrapKey = []byte("BootstrapKey")
mSchemaDiffPrefix = "Diff"
)
var (
// ErrDBExists is the error for db exists.
ErrDBExists = dbterror.ClassMeta.NewStd(mysql.ErrDBCreateExists)
// ErrDBNotExists is the error for db not exists.
ErrDBNotExists = dbterror.ClassMeta.NewStd(mysql.ErrBadDB)
// ErrTableExists is the error for table exists.
ErrTableExists = dbterror.ClassMeta.NewStd(mysql.ErrTableExists)
// ErrTableNotExists is the error for table not exists.
ErrTableNotExists = dbterror.ClassMeta.NewStd(mysql.ErrNoSuchTable)
// ErrDDLReorgElementNotExist is the error for reorg element not exists.
ErrDDLReorgElementNotExist = dbterror.ClassMeta.NewStd(errno.ErrDDLReorgElementNotExist)
)
// Meta is for handling meta information in a transaction.
type Meta struct {
txn *structure.TxStructure
StartTS uint64 // StartTS is the txn's start TS.
jobListKey JobListKeyType
}
// NewMeta creates a Meta in transaction txn.
// If the current Meta needs to handle a job, jobListKey is the type of the job's list.
func NewMeta(txn kv.Transaction, jobListKeys ...JobListKeyType) *Meta {
txn.SetOption(kv.Priority, kv.PriorityHigh)
txn.SetOption(kv.SyncLog, true)
t := structure.NewStructure(txn, txn, mMetaPrefix)
listKey := DefaultJobListKey
if len(jobListKeys) != 0 {
listKey = jobListKeys[0]
}
return &Meta{txn: t,
StartTS: txn.StartTS(),
jobListKey: listKey,
}
}
// NewSnapshotMeta creates a Meta with snapshot.
func NewSnapshotMeta(snapshot kv.Snapshot) *Meta {
t := structure.NewStructure(snapshot, nil, mMetaPrefix)
return &Meta{txn: t}
}
// GenGlobalID generates next id globally.
func (m *Meta) GenGlobalID() (int64, error) {
globalIDMutex.Lock()
defer globalIDMutex.Unlock()
return m.txn.Inc(mNextGlobalIDKey, 1)
}
// GenGlobalIDs generates the next n global IDs.
func (m *Meta) GenGlobalIDs(n int) ([]int64, error) {
globalIDMutex.Lock()
defer globalIDMutex.Unlock()
newID, err := m.txn.Inc(mNextGlobalIDKey, int64(n))
if err != nil {
return nil, err
}
origID := newID - int64(n)
ids := make([]int64, 0, n)
for i := origID + 1; i <= newID; i++ {
ids = append(ids, i)
}
return ids, nil
}
// GetGlobalID gets current global id.
func (m *Meta) GetGlobalID() (int64, error) {
return m.txn.GetInt64(mNextGlobalIDKey)
}
func (m *Meta) dbKey(dbID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mDBPrefix, dbID))
}
func (m *Meta) autoTableIDKey(tableID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mTableIDPrefix, tableID))
}
func (m *Meta) autoRandomTableIDKey(tableID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mRandomIDPrefix, tableID))
}
func (m *Meta) tableKey(tableID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mTablePrefix, tableID))
}
func (m *Meta) sequenceKey(sequenceID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mSequencePrefix, sequenceID))
}
func (m *Meta) sequenceCycleKey(sequenceID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mSeqCyclePrefix, sequenceID))
}
// DDLJobHistoryKey is only used for testing.
func DDLJobHistoryKey(m *Meta, jobID int64) []byte {
return m.txn.EncodeHashDataKey(mDDLJobHistoryKey, m.jobIDKey(jobID))
}
// GenAutoTableIDKeyValue generates meta key by dbID, tableID and corresponding value by autoID.
func (m *Meta) GenAutoTableIDKeyValue(dbID, tableID, autoID int64) (key, value []byte) {
dbKey := m.dbKey(dbID)
autoTableIDKey := m.autoTableIDKey(tableID)
return m.txn.EncodeHashAutoIDKeyValue(dbKey, autoTableIDKey, autoID)
}
// GenAutoTableID adds step to the auto ID of the table and returns the sum.
func (m *Meta) GenAutoTableID(dbID, tableID, step int64) (int64, error) {
// Check if DB exists.
dbKey := m.dbKey(dbID)
if err := m.checkDBExists(dbKey); err != nil {
return 0, errors.Trace(err)
}
// Check if table exists.
tableKey := m.tableKey(tableID)
if err := m.checkTableExists(dbKey, tableKey); err != nil {
return 0, errors.Trace(err)
}
return m.txn.HInc(dbKey, m.autoTableIDKey(tableID), step)
}
// GenAutoRandomID adds step to the auto shard ID of the table and returns the sum.
func (m *Meta) GenAutoRandomID(dbID, tableID, step int64) (int64, error) {
// Check if DB exists.
dbKey := m.dbKey(dbID)
if err := m.checkDBExists(dbKey); err != nil {
return 0, errors.Trace(err)
}
// Check if table exists.
tableKey := m.tableKey(tableID)
if err := m.checkTableExists(dbKey, tableKey); err != nil {
return 0, errors.Trace(err)
}
return m.txn.HInc(dbKey, m.autoRandomTableIDKey(tableID), step)
}
// GetAutoTableID gets current auto id with table id.
func (m *Meta) GetAutoTableID(dbID int64, tableID int64) (int64, error) {
return m.txn.HGetInt64(m.dbKey(dbID), m.autoTableIDKey(tableID))
}
// GetAutoRandomID gets current auto random id with table id.
func (m *Meta) GetAutoRandomID(dbID int64, tableID int64) (int64, error) {
return m.txn.HGetInt64(m.dbKey(dbID), m.autoRandomTableIDKey(tableID))
}
// GenSequenceValue adds step to the sequence value and returns the sum.
func (m *Meta) GenSequenceValue(dbID, sequenceID, step int64) (int64, error) {
// Check if DB exists.
dbKey := m.dbKey(dbID)
if err := m.checkDBExists(dbKey); err != nil {
return 0, errors.Trace(err)
}
// Check if sequence exists.
tableKey := m.tableKey(sequenceID)
if err := m.checkTableExists(dbKey, tableKey); err != nil {
return 0, errors.Trace(err)
}
return m.txn.HInc(dbKey, m.sequenceKey(sequenceID), step)
}
// GetSequenceValue gets current sequence value with sequence id.
func (m *Meta) GetSequenceValue(dbID int64, sequenceID int64) (int64, error) {
return m.txn.HGetInt64(m.dbKey(dbID), m.sequenceKey(sequenceID))
}
// SetSequenceValue sets start value when sequence in cycle.
func (m *Meta) SetSequenceValue(dbID int64, sequenceID int64, start int64) error {
return m.txn.HSet(m.dbKey(dbID), m.sequenceKey(sequenceID), []byte(strconv.FormatInt(start, 10)))
}
// GetSequenceCycle gets current sequence cycle times with sequence id.
func (m *Meta) GetSequenceCycle(dbID int64, sequenceID int64) (int64, error) {
return m.txn.HGetInt64(m.dbKey(dbID), m.sequenceCycleKey(sequenceID))
}
// SetSequenceCycle sets cycle times value when sequence in cycle.
func (m *Meta) SetSequenceCycle(dbID int64, sequenceID int64, round int64) error {
return m.txn.HSet(m.dbKey(dbID), m.sequenceCycleKey(sequenceID), []byte(strconv.FormatInt(round, 10)))
}
// GetSchemaVersion gets current global schema version.
func (m *Meta) GetSchemaVersion() (int64, error) {
return m.txn.GetInt64(mSchemaVersionKey)
}
// GenSchemaVersion generates next schema version.
func (m *Meta) GenSchemaVersion() (int64, error) {
return m.txn.Inc(mSchemaVersionKey, 1)
}
func (m *Meta) checkDBExists(dbKey []byte) error {
v, err := m.txn.HGet(mDBs, dbKey)
if err == nil && v == nil {
err = ErrDBNotExists.GenWithStack("database doesn't exist")
}
return errors.Trace(err)
}
func (m *Meta) checkDBNotExists(dbKey []byte) error {
v, err := m.txn.HGet(mDBs, dbKey)
if err == nil && v != nil {
err = ErrDBExists.GenWithStack("database already exists")
}
return errors.Trace(err)
}
func (m *Meta) checkTableExists(dbKey []byte, tableKey []byte) error {
v, err := m.txn.HGet(dbKey, tableKey)
if err == nil && v == nil {
err = ErrTableNotExists.GenWithStack("table doesn't exist")
}
return errors.Trace(err)
}
func (m *Meta) checkTableNotExists(dbKey []byte, tableKey []byte) error {
v, err := m.txn.HGet(dbKey, tableKey)
if err == nil && v != nil {
err = ErrTableExists.GenWithStack("table already exists")
}
return errors.Trace(err)
}
// CreateDatabase creates a database with db info.
func (m *Meta) CreateDatabase(dbInfo *model.DBInfo) error {
dbKey := m.dbKey(dbInfo.ID)
if err := m.checkDBNotExists(dbKey); err != nil {
return errors.Trace(err)
}
data, err := json.Marshal(dbInfo)
if err != nil {
return errors.Trace(err)
}
return m.txn.HSet(mDBs, dbKey, data)
}
// UpdateDatabase updates a database with db info.
func (m *Meta) UpdateDatabase(dbInfo *model.DBInfo) error {
dbKey := m.dbKey(dbInfo.ID)
if err := m.checkDBExists(dbKey); err != nil {
return errors.Trace(err)
}
data, err := json.Marshal(dbInfo)
if err != nil {
return errors.Trace(err)
}
return m.txn.HSet(mDBs, dbKey, data)
}
// CreateTableOrView creates a table with tableInfo in database.
func (m *Meta) CreateTableOrView(dbID int64, tableInfo *model.TableInfo) error {
// Check if db exists.
dbKey := m.dbKey(dbID)
if err := m.checkDBExists(dbKey); err != nil {
return errors.Trace(err)
}
// Check if table exists.
tableKey := m.tableKey(tableInfo.ID)
if err := m.checkTableNotExists(dbKey, tableKey); err != nil {
return errors.Trace(err)
}
data, err := json.Marshal(tableInfo)
if err != nil {
return errors.Trace(err)
}
return m.txn.HSet(dbKey, tableKey, data)
}
// CreateTableAndSetAutoID creates a table with tableInfo in database,
// and rebases the table autoID.
func (m *Meta) CreateTableAndSetAutoID(dbID int64, tableInfo *model.TableInfo, autoIncID, autoRandID int64) error {
err := m.CreateTableOrView(dbID, tableInfo)
if err != nil {
return errors.Trace(err)
}
_, err = m.txn.HInc(m.dbKey(dbID), m.autoTableIDKey(tableInfo.ID), autoIncID)
if err != nil {
return errors.Trace(err)
}
if tableInfo.AutoRandomBits > 0 {
_, err = m.txn.HInc(m.dbKey(dbID), m.autoRandomTableIDKey(tableInfo.ID), autoRandID)
if err != nil {
return errors.Trace(err)
}
}
return nil
}
// CreateSequenceAndSetSeqValue creates sequence with tableInfo in database, and rebase the sequence seqValue.
func (m *Meta) CreateSequenceAndSetSeqValue(dbID int64, tableInfo *model.TableInfo, seqValue int64) error {
err := m.CreateTableOrView(dbID, tableInfo)
if err != nil {
return errors.Trace(err)
}
_, err = m.txn.HInc(m.dbKey(dbID), m.sequenceKey(tableInfo.ID), seqValue)
return errors.Trace(err)
}
// RestartSequenceValue resets the the sequence value.
func (m *Meta) RestartSequenceValue(dbID int64, tableInfo *model.TableInfo, seqValue int64) error {
// Check if db exists.
dbKey := m.dbKey(dbID)
if err := m.checkDBExists(dbKey); err != nil {
return errors.Trace(err)
}
// Check if table exists.
tableKey := m.tableKey(tableInfo.ID)
if err := m.checkTableExists(dbKey, tableKey); err != nil {
return errors.Trace(err)
}
return errors.Trace(m.txn.HSet(m.dbKey(dbID), m.sequenceKey(tableInfo.ID), []byte(strconv.FormatInt(seqValue, 10))))
}
// DropDatabase drops whole database.
func (m *Meta) DropDatabase(dbID int64) error {
// Check if db exists.
dbKey := m.dbKey(dbID)
if err := m.txn.HClear(dbKey); err != nil {
return errors.Trace(err)
}
if err := m.txn.HDel(mDBs, dbKey); err != nil {
return errors.Trace(err)
}
return nil
}
// DropSequence drops sequence in database.
// Sequence is made of table struct and kv value pair.
func (m *Meta) DropSequence(dbID int64, tblID int64, delAutoID bool) error {
err := m.DropTableOrView(dbID, tblID, delAutoID)
if err != nil {
return err
}
err = m.txn.HDel(m.dbKey(dbID), m.sequenceKey(tblID))
return errors.Trace(err)
}
// DropTableOrView drops table in database.
// If delAutoID is true, it will delete the auto_increment id key-value of the table.
// For rename table, we do not need to rename auto_increment id key-value.
func (m *Meta) DropTableOrView(dbID int64, tblID int64, delAutoID bool) error {
// Check if db exists.
dbKey := m.dbKey(dbID)
if err := m.checkDBExists(dbKey); err != nil {
return errors.Trace(err)
}
// Check if table exists.
tableKey := m.tableKey(tblID)
if err := m.checkTableExists(dbKey, tableKey); err != nil {
return errors.Trace(err)
}
if err := m.txn.HDel(dbKey, tableKey); err != nil {
return errors.Trace(err)
}
if delAutoID {
if err := m.txn.HDel(dbKey, m.autoTableIDKey(tblID)); err != nil {
return errors.Trace(err)
}
if err := m.txn.HDel(dbKey, m.autoRandomTableIDKey(tblID)); err != nil {
return errors.Trace(err)
}
}
return nil
}
// UpdateTable updates the table with table info.
func (m *Meta) UpdateTable(dbID int64, tableInfo *model.TableInfo) error {
// Check if db exists.
dbKey := m.dbKey(dbID)
if err := m.checkDBExists(dbKey); err != nil {
return errors.Trace(err)
}
// Check if table exists.
tableKey := m.tableKey(tableInfo.ID)
if err := m.checkTableExists(dbKey, tableKey); err != nil {
return errors.Trace(err)
}
data, err := json.Marshal(tableInfo)
if err != nil {
return errors.Trace(err)
}
err = m.txn.HSet(dbKey, tableKey, data)
return errors.Trace(err)
}
// ListTables shows all tables in database.
func (m *Meta) ListTables(dbID int64) ([]*model.TableInfo, error) {
dbKey := m.dbKey(dbID)
if err := m.checkDBExists(dbKey); err != nil {
return nil, errors.Trace(err)
}
res, err := m.txn.HGetAll(dbKey)
if err != nil {
return nil, errors.Trace(err)
}
tables := make([]*model.TableInfo, 0, len(res)/2)
for _, r := range res {
// only handle table meta
tableKey := string(r.Field)
if !strings.HasPrefix(tableKey, mTablePrefix) {
continue
}
tbInfo := &model.TableInfo{}
err = json.Unmarshal(r.Value, tbInfo)
if err != nil {
return nil, errors.Trace(err)
}
tables = append(tables, tbInfo)
}
return tables, nil
}
// ListDatabases shows all databases.
func (m *Meta) ListDatabases() ([]*model.DBInfo, error) {
res, err := m.txn.HGetAll(mDBs)
if err != nil {
return nil, errors.Trace(err)
}
dbs := make([]*model.DBInfo, 0, len(res))
for _, r := range res {
dbInfo := &model.DBInfo{}
err = json.Unmarshal(r.Value, dbInfo)
if err != nil {
return nil, errors.Trace(err)
}
dbs = append(dbs, dbInfo)
}
return dbs, nil
}
// GetDatabase gets the database value with ID.
func (m *Meta) GetDatabase(dbID int64) (*model.DBInfo, error) {
dbKey := m.dbKey(dbID)
value, err := m.txn.HGet(mDBs, dbKey)
if err != nil || value == nil {
return nil, errors.Trace(err)
}
dbInfo := &model.DBInfo{}
err = json.Unmarshal(value, dbInfo)
return dbInfo, errors.Trace(err)
}
// GetTable gets the table value in database with tableID.
func (m *Meta) GetTable(dbID int64, tableID int64) (*model.TableInfo, error) {
// Check if db exists.
dbKey := m.dbKey(dbID)
if err := m.checkDBExists(dbKey); err != nil {
return nil, errors.Trace(err)
}
tableKey := m.tableKey(tableID)
value, err := m.txn.HGet(dbKey, tableKey)
if err != nil || value == nil {
return nil, errors.Trace(err)
}
tableInfo := &model.TableInfo{}
err = json.Unmarshal(value, tableInfo)
return tableInfo, errors.Trace(err)
}
// DDL job structure
// DDLJobList: list jobs
// DDLJobHistory: hash
// DDLJobReorg: hash
//
// for multi DDL workers, only one can become the owner
// to operate DDL jobs, and dispatch them to MR Jobs.
var (
mDDLJobListKey = []byte("DDLJobList")
mDDLJobAddIdxList = []byte("DDLJobAddIdxList")
mDDLJobHistoryKey = []byte("DDLJobHistory")
mDDLJobReorgKey = []byte("DDLJobReorg")
)
// JobListKeyType is a key type of the DDL job queue.
type JobListKeyType []byte
var (
// DefaultJobListKey keeps all actions of DDL jobs except "add index".
DefaultJobListKey JobListKeyType = mDDLJobListKey
// AddIndexJobListKey only keeps the action of adding index.
AddIndexJobListKey JobListKeyType = mDDLJobAddIdxList
)
func (m *Meta) enQueueDDLJob(key []byte, job *model.Job) error {
b, err := job.Encode(true)
if err == nil {
err = m.txn.RPush(key, b)
}
return errors.Trace(err)
}
// EnQueueDDLJob adds a DDL job to the list.
func (m *Meta) EnQueueDDLJob(job *model.Job, jobListKeys ...JobListKeyType) error {
listKey := m.jobListKey
if len(jobListKeys) != 0 {
listKey = jobListKeys[0]
}
return m.enQueueDDLJob(listKey, job)
}
func (m *Meta) deQueueDDLJob(key []byte) (*model.Job, error) {
value, err := m.txn.LPop(key)
if err != nil || value == nil {
return nil, errors.Trace(err)
}
job := &model.Job{}
err = job.Decode(value)
return job, errors.Trace(err)
}
// DeQueueDDLJob pops a DDL job from the list.
func (m *Meta) DeQueueDDLJob() (*model.Job, error) {
return m.deQueueDDLJob(m.jobListKey)
}
func (m *Meta) getDDLJob(key []byte, index int64) (*model.Job, error) {
value, err := m.txn.LIndex(key, index)
if err != nil || value == nil {
return nil, errors.Trace(err)
}
job := &model.Job{
// For compatibility, if the job is enqueued by old version TiDB and Priority field is omitted,
// set the default priority to kv.PriorityLow.
Priority: kv.PriorityLow,
}
err = job.Decode(value)
// Check if the job.Priority is valid.
if job.Priority < kv.PriorityNormal || job.Priority > kv.PriorityHigh {
job.Priority = kv.PriorityLow
}
return job, errors.Trace(err)
}
// GetDDLJobByIdx returns the corresponding DDL job by the index.
// The length of jobListKeys can only be 1 or 0.
// If its length is 1, we need to replace m.jobListKey with jobListKeys[0].
// Otherwise, we use m.jobListKey directly.
func (m *Meta) GetDDLJobByIdx(index int64, jobListKeys ...JobListKeyType) (*model.Job, error) {
listKey := m.jobListKey
if len(jobListKeys) != 0 {
listKey = jobListKeys[0]
}
startTime := time.Now()
job, err := m.getDDLJob(listKey, index)
metrics.MetaHistogram.WithLabelValues(metrics.GetDDLJobByIdx, metrics.RetLabel(err)).Observe(time.Since(startTime).Seconds())
return job, errors.Trace(err)
}
// updateDDLJob updates the DDL job with index and key.
// updateRawArgs is used to determine whether to update the raw args when encode the job.
func (m *Meta) updateDDLJob(index int64, job *model.Job, key []byte, updateRawArgs bool) error {
b, err := job.Encode(updateRawArgs)
if err == nil {
err = m.txn.LSet(key, index, b)
}
return errors.Trace(err)
}
// UpdateDDLJob updates the DDL job with index.
// updateRawArgs is used to determine whether to update the raw args when encode the job.
// The length of jobListKeys can only be 1 or 0.
// If its length is 1, we need to replace m.jobListKey with jobListKeys[0].
// Otherwise, we use m.jobListKey directly.
func (m *Meta) UpdateDDLJob(index int64, job *model.Job, updateRawArgs bool, jobListKeys ...JobListKeyType) error {
listKey := m.jobListKey
if len(jobListKeys) != 0 {
listKey = jobListKeys[0]
}
startTime := time.Now()
err := m.updateDDLJob(index, job, listKey, updateRawArgs)
metrics.MetaHistogram.WithLabelValues(metrics.UpdateDDLJob, metrics.RetLabel(err)).Observe(time.Since(startTime).Seconds())
return errors.Trace(err)
}
// DDLJobQueueLen returns the DDL job queue length.
// The length of jobListKeys can only be 1 or 0.
// If its length is 1, we need to replace m.jobListKey with jobListKeys[0].
// Otherwise, we use m.jobListKey directly.
func (m *Meta) DDLJobQueueLen(jobListKeys ...JobListKeyType) (int64, error) {
listKey := m.jobListKey
if len(jobListKeys) != 0 {
listKey = jobListKeys[0]
}
return m.txn.LLen(listKey)
}
// GetAllDDLJobsInQueue gets all DDL Jobs in the current queue.
// The length of jobListKeys can only be 1 or 0.
// If its length is 1, we need to replace m.jobListKey with jobListKeys[0].
// Otherwise, we use m.jobListKey directly.
func (m *Meta) GetAllDDLJobsInQueue(jobListKeys ...JobListKeyType) ([]*model.Job, error) {
listKey := m.jobListKey
if len(jobListKeys) != 0 {
listKey = jobListKeys[0]
}
values, err := m.txn.LGetAll(listKey)
if err != nil || values == nil {
return nil, errors.Trace(err)
}
jobs := make([]*model.Job, 0, len(values))
for _, val := range values {
job := &model.Job{}
err = job.Decode(val)
if err != nil {
return nil, errors.Trace(err)
}
jobs = append(jobs, job)
}
return jobs, nil
}
func (m *Meta) jobIDKey(id int64) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(id))
return b
}
func (m *Meta) reorgJobCurrentElement(id int64) []byte {
b := make([]byte, 0, 12)
b = append(b, m.jobIDKey(id)...)
b = append(b, "_ele"...)
return b
}
func (m *Meta) reorgJobStartHandle(id int64, element *Element) []byte {
b := make([]byte, 0, 16+len(element.TypeKey))
b = append(b, m.jobIDKey(id)...)
b = append(b, element.TypeKey...)
eID := make([]byte, 8)
binary.BigEndian.PutUint64(eID, uint64(element.ID))
b = append(b, eID...)
return b
}
func (m *Meta) reorgJobEndHandle(id int64, element *Element) []byte {
b := make([]byte, 8, 25)
binary.BigEndian.PutUint64(b, uint64(id))
b = append(b, element.TypeKey...)
eID := make([]byte, 8)
binary.BigEndian.PutUint64(eID, uint64(element.ID))
b = append(b, eID...)
b = append(b, "_end"...)
return b
}
func (m *Meta) reorgJobPhysicalTableID(id int64, element *Element) []byte {
b := make([]byte, 8, 25)
binary.BigEndian.PutUint64(b, uint64(id))
b = append(b, element.TypeKey...)
eID := make([]byte, 8)
binary.BigEndian.PutUint64(eID, uint64(element.ID))
b = append(b, eID...)
b = append(b, "_pid"...)
return b
}
func (m *Meta) addHistoryDDLJob(key []byte, job *model.Job, updateRawArgs bool) error {
b, err := job.Encode(updateRawArgs)
if err == nil {
err = m.txn.HSet(key, m.jobIDKey(job.ID), b)
}
return errors.Trace(err)
}
// AddHistoryDDLJob adds DDL job to history.
func (m *Meta) AddHistoryDDLJob(job *model.Job, updateRawArgs bool) error {
return m.addHistoryDDLJob(mDDLJobHistoryKey, job, updateRawArgs)
}
func (m *Meta) getHistoryDDLJob(key []byte, id int64) (*model.Job, error) {
value, err := m.txn.HGet(key, m.jobIDKey(id))
if err != nil || value == nil {
return nil, errors.Trace(err)
}
job := &model.Job{}
err = job.Decode(value)
return job, errors.Trace(err)
}
// GetHistoryDDLJob gets a history DDL job.
func (m *Meta) GetHistoryDDLJob(id int64) (*model.Job, error) {
startTime := time.Now()
job, err := m.getHistoryDDLJob(mDDLJobHistoryKey, id)
metrics.MetaHistogram.WithLabelValues(metrics.GetHistoryDDLJob, metrics.RetLabel(err)).Observe(time.Since(startTime).Seconds())
return job, errors.Trace(err)
}
// GetAllHistoryDDLJobs gets all history DDL jobs.
func (m *Meta) GetAllHistoryDDLJobs() ([]*model.Job, error) {
pairs, err := m.txn.HGetAll(mDDLJobHistoryKey)
if err != nil {
return nil, errors.Trace(err)
}
jobs, err := decodeJob(pairs)
if err != nil {
return nil, errors.Trace(err)
}
// sort job.
sorter := &jobsSorter{jobs: jobs}
sort.Sort(sorter)
return jobs, nil
}
// GetLastNHistoryDDLJobs gets latest N history ddl jobs.
func (m *Meta) GetLastNHistoryDDLJobs(num int) ([]*model.Job, error) {
pairs, err := m.txn.HGetLastN(mDDLJobHistoryKey, num)
if err != nil {
return nil, errors.Trace(err)
}
return decodeJob(pairs)
}
// LastJobIterator is the iterator for gets latest history.
type LastJobIterator struct {
iter *structure.ReverseHashIterator
}
// GetLastHistoryDDLJobsIterator gets latest N history ddl jobs iterator.
func (m *Meta) GetLastHistoryDDLJobsIterator() (*LastJobIterator, error) {
iter, err := structure.NewHashReverseIter(m.txn, mDDLJobHistoryKey)
if err != nil {
return nil, err
}
return &LastJobIterator{
iter: iter,
}, nil
}
// GetLastJobs gets last several jobs.
func (i *LastJobIterator) GetLastJobs(num int, jobs []*model.Job) ([]*model.Job, error) {
if len(jobs) < num {
jobs = make([]*model.Job, 0, num)
}
jobs = jobs[:0]
iter := i.iter
for iter.Valid() && len(jobs) < num {
job := &model.Job{}
err := job.Decode(iter.Value())
if err != nil {
return nil, errors.Trace(err)
}
jobs = append(jobs, job)
err = iter.Next()
if err != nil {
return nil, errors.Trace(err)
}
}
return jobs, nil
}
func decodeJob(jobPairs []structure.HashPair) ([]*model.Job, error) {
jobs := make([]*model.Job, 0, len(jobPairs))
for _, pair := range jobPairs {
job := &model.Job{}
err := job.Decode(pair.Value)
if err != nil {
return nil, errors.Trace(err)
}
jobs = append(jobs, job)
}
return jobs, nil
}
// jobsSorter implements the sort.Interface interface.
type jobsSorter struct {
jobs []*model.Job
}
func (s *jobsSorter) Swap(i, j int) {
s.jobs[i], s.jobs[j] = s.jobs[j], s.jobs[i]
}
func (s *jobsSorter) Len() int {
return len(s.jobs)
}
func (s *jobsSorter) Less(i, j int) bool {
return s.jobs[i].ID < s.jobs[j].ID
}
// GetBootstrapVersion returns the version of the server which bootstrap the store.
// If the store is not bootstraped, the version will be zero.
func (m *Meta) GetBootstrapVersion() (int64, error) {
value, err := m.txn.GetInt64(mBootstrapKey)
return value, errors.Trace(err)
}
// FinishBootstrap finishes bootstrap.
func (m *Meta) FinishBootstrap(version int64) error {
err := m.txn.Set(mBootstrapKey, []byte(fmt.Sprintf("%d", version)))
return errors.Trace(err)
}
// ElementKeyType is a key type of the element.
type ElementKeyType []byte
var (
// ColumnElementKey is the key for column element.
ColumnElementKey ElementKeyType = []byte("_col_")
// IndexElementKey is the key for index element.
IndexElementKey ElementKeyType = []byte("_idx_")
)
const elementKeyLen = 5
// Element has the information of the backfill job's type and ID.
type Element struct {
ID int64
TypeKey []byte
}
// String defines a Stringer function for debugging and pretty printing.
func (e *Element) String() string {
return "ID:" + strconv.FormatInt(e.ID, 10) + "," +
"TypeKey:" + string(e.TypeKey)
}
// EncodeElement encodes an Element into a byte slice.
// It's exported for testing.
func (e *Element) EncodeElement() []byte {
b := make([]byte, 13)
copy(b[:elementKeyLen], e.TypeKey)
binary.BigEndian.PutUint64(b[elementKeyLen:], uint64(e.ID))
return b
}
// DecodeElement decodes values from a byte slice generated with an element.
// It's exported for testing.
func DecodeElement(b []byte) (*Element, error) {
if len(b) < elementKeyLen+8 {
return nil, errors.Errorf("invalid encoded element %q length %d", b, len(b))
}
var tp []byte
prefix := b[:elementKeyLen]
b = b[elementKeyLen:]
switch string(prefix) {
case string(IndexElementKey):
tp = IndexElementKey
case string(ColumnElementKey):
tp = ColumnElementKey
default:
return nil, errors.Errorf("invalid encoded element key prefix %q", prefix)
}
id := binary.BigEndian.Uint64(b)
return &Element{ID: int64(id), TypeKey: tp}, nil
}
// UpdateDDLReorgStartHandle saves the job reorganization latest processed element and start handle for later resuming.
func (m *Meta) UpdateDDLReorgStartHandle(job *model.Job, element *Element, startKey kv.Key) error {
err := m.txn.HSet(mDDLJobReorgKey, m.reorgJobCurrentElement(job.ID), element.EncodeElement())
if err != nil {
return errors.Trace(err)
}
if startKey != nil {
err = m.txn.HSet(mDDLJobReorgKey, m.reorgJobStartHandle(job.ID, element), startKey)
if err != nil {
return errors.Trace(err)
}
}
return nil
}
// UpdateDDLReorgHandle saves the job reorganization latest processed information for later resuming.
func (m *Meta) UpdateDDLReorgHandle(job *model.Job, startKey, endKey kv.Key, physicalTableID int64, element *Element) error {
err := m.txn.HSet(mDDLJobReorgKey, m.reorgJobCurrentElement(job.ID), element.EncodeElement())
if err != nil {
return errors.Trace(err)
}
if startKey != nil {
err = m.txn.HSet(mDDLJobReorgKey, m.reorgJobStartHandle(job.ID, element), startKey)
if err != nil {
return errors.Trace(err)
}
}
if endKey != nil {
err = m.txn.HSet(mDDLJobReorgKey, m.reorgJobEndHandle(job.ID, element), endKey)
if err != nil {
return errors.Trace(err)
}
}
err = m.txn.HSet(mDDLJobReorgKey, m.reorgJobPhysicalTableID(job.ID, element), []byte(strconv.FormatInt(physicalTableID, 10)))
return errors.Trace(err)
}
// RemoveReorgElement removes the element of the reorganization information.
// It's used for testing.