-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
meta.go
1791 lines (1556 loc) · 51.5 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,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package meta
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"fmt"
"math"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
rmpb "github.com/pingcap/kvproto/pkg/resource_manager"
"github.com/pingcap/tidb/pkg/errno"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/meta/model"
"github.com/pingcap/tidb/pkg/metrics"
pmodel "github.com/pingcap/tidb/pkg/parser/model"
"github.com/pingcap/tidb/pkg/parser/mysql"
"github.com/pingcap/tidb/pkg/resourcegroup"
"github.com/pingcap/tidb/pkg/structure"
"github.com/pingcap/tidb/pkg/util/dbterror"
"github.com/pingcap/tidb/pkg/util/hack"
"github.com/pingcap/tidb/pkg/util/partialjson"
"github.com/pingcap/tidb/pkg/util/set"
)
var (
globalIDMutex sync.Mutex
policyIDMutex 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
// }
//
// DDL version 2
// Names -> {
// Name:DBname\x00tablename -> tableID
// }
var (
mMetaPrefix = []byte("m")
// the value inside it is actually the max current used ID, not next id.
mNextGlobalIDKey = []byte("NextGlobalID")
mSchemaVersionKey = []byte("SchemaVersionKey")
mDBs = []byte("DBs")
mDBPrefix = "DB"
mTablePrefix = "Table"
mSequencePrefix = "SID"
mSeqCyclePrefix = "SequenceCycle"
mTableIDPrefix = "TID"
mIncIDPrefix = "IID"
mRandomIDPrefix = "TARID"
mBootstrapKey = []byte("BootstrapKey")
mSchemaDiffPrefix = "Diff"
mPolicies = []byte("Policies")
mPolicyPrefix = "Policy"
mResourceGroups = []byte("ResourceGroups")
mResourceGroupPrefix = "RG"
mPolicyGlobalID = []byte("PolicyGlobalID")
mPolicyMagicByte = CurrentMagicByteVer
mDDLTableVersion = []byte("DDLTableVersion")
mBDRRole = []byte("BDRRole")
mMetaDataLock = []byte("metadataLock")
mSchemaCacheSize = []byte("SchemaCacheSize")
mRequestUnitStats = []byte("RequestUnitStats")
// the id for 'default' group, the internal ddl can ensure
// user created resource group won't duplicate with this id.
defaultGroupID = int64(1)
// the default meta of the `default` group
defaultRGroupMeta = &model.ResourceGroupInfo{
ResourceGroupSettings: &model.ResourceGroupSettings{
RURate: math.MaxInt32,
BurstLimit: -1,
Priority: pmodel.MediumPriorityValue,
},
ID: defaultGroupID,
Name: pmodel.NewCIStr(resourcegroup.DefaultResourceGroupName),
State: model.StatePublic,
}
)
const (
// CurrentMagicByteVer is the current magic byte version, used for future meta compatibility.
CurrentMagicByteVer byte = 0x00
// PolicyMagicByte handler
// 0x00 - 0x3F: Json Handler
// 0x40 - 0x7F: Reserved
// 0x80 - 0xBF: Reserved
// 0xC0 - 0xFF: Reserved
// type means how to handle the serialized data.
typeUnknown int = 0
typeJSON int = 1
// todo: customized handler.
// MaxInt48 is the max value of int48.
MaxInt48 = 0x0000FFFFFFFFFFFF
// MaxGlobalID reserves 1000 IDs. Use MaxInt48 to reserves the high 2 bytes to compatible with Multi-tenancy.
MaxGlobalID = MaxInt48 - 1000
)
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)
// ErrPolicyExists is the error for policy exists.
ErrPolicyExists = dbterror.ClassMeta.NewStd(errno.ErrPlacementPolicyExists)
// ErrPolicyNotExists is the error for policy not exists.
ErrPolicyNotExists = dbterror.ClassMeta.NewStd(errno.ErrPlacementPolicyNotExists)
// ErrResourceGroupExists is the error for resource group exists.
ErrResourceGroupExists = dbterror.ClassMeta.NewStd(errno.ErrResourceGroupExists)
// ErrResourceGroupNotExists is the error for resource group not exists.
ErrResourceGroupNotExists = dbterror.ClassMeta.NewStd(errno.ErrResourceGroupNotExists)
// 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)
// ErrInvalidString is the error for invalid string to parse
ErrInvalidString = dbterror.ClassMeta.NewStd(errno.ErrInvalidCharacterString)
)
// DDLTableVersion is to display ddl related table versions
type DDLTableVersion int
const (
// InitDDLTableVersion is the original version.
InitDDLTableVersion DDLTableVersion = 0
// BaseDDLTableVersion is for support concurrent DDL, it added tidb_ddl_job, tidb_ddl_reorg and tidb_ddl_history.
BaseDDLTableVersion DDLTableVersion = 1
// MDLTableVersion is for support MDL tables.
MDLTableVersion DDLTableVersion = 2
// BackfillTableVersion is for support distributed reorg stage, it added tidb_background_subtask, tidb_background_subtask_history.
BackfillTableVersion DDLTableVersion = 3
// DDLNotifierTableVersion is for support ddl notifier, it added tidb_ddl_notifier.
DDLNotifierTableVersion DDLTableVersion = 4
)
// Bytes returns the byte slice.
func (ver DDLTableVersion) Bytes() []byte {
return []byte(strconv.Itoa(int(ver)))
}
// Option is for Mutator option.
type Option func(m *Mutator)
// Mutator is for handling meta information in a transaction.
type Mutator struct {
txn *structure.TxStructure
StartTS uint64 // StartTS is the txn's start TS.
}
var _ Reader = (*Mutator)(nil)
// NewMutator creates a meta Mutator in transaction txn.
// If the current Mutator needs to handle a job, jobListKey is the type of the job's list.
func NewMutator(txn kv.Transaction, options ...Option) *Mutator {
txn.SetOption(kv.Priority, kv.PriorityHigh)
txn.SetDiskFullOpt(kvrpcpb.DiskFullOpt_AllowedOnAlmostFull)
t := structure.NewStructure(txn, txn, mMetaPrefix)
m := &Mutator{txn: t,
StartTS: txn.StartTS(),
}
for _, opt := range options {
opt(m)
}
return m
}
// GenGlobalID generates next id globally.
func (m *Mutator) GenGlobalID() (int64, error) {
globalIDMutex.Lock()
defer globalIDMutex.Unlock()
newID, err := m.txn.Inc(mNextGlobalIDKey, 1)
if err != nil {
return 0, errors.Trace(err)
}
if newID > MaxGlobalID {
return 0, errors.Errorf("global id:%d exceeds the limit:%d", newID, MaxGlobalID)
}
return newID, err
}
// AdvanceGlobalIDs advances the global ID by n.
// return the old global ID.
func (m *Mutator) AdvanceGlobalIDs(n int) (int64, error) {
globalIDMutex.Lock()
defer globalIDMutex.Unlock()
newID, err := m.txn.Inc(mNextGlobalIDKey, int64(n))
if err != nil {
return 0, err
}
if newID > MaxGlobalID {
return 0, errors.Errorf("global id:%d exceeds the limit:%d", newID, MaxGlobalID)
}
origID := newID - int64(n)
return origID, nil
}
// GenGlobalIDs generates the next n global IDs.
func (m *Mutator) GenGlobalIDs(n int) ([]int64, error) {
globalIDMutex.Lock()
defer globalIDMutex.Unlock()
newID, err := m.txn.Inc(mNextGlobalIDKey, int64(n))
if err != nil {
return nil, err
}
if newID > MaxGlobalID {
return nil, errors.Errorf("global id:%d exceeds the limit:%d", newID, MaxGlobalID)
}
origID := newID - int64(n)
ids := make([]int64, 0, n)
for i := origID + 1; i <= newID; i++ {
ids = append(ids, i)
}
return ids, nil
}
// GlobalIDKey returns the key for the global ID.
func (m *Mutator) GlobalIDKey() []byte {
return m.txn.EncodeStringDataKey(mNextGlobalIDKey)
}
// GenPlacementPolicyID generates next placement policy id globally.
func (m *Mutator) GenPlacementPolicyID() (int64, error) {
policyIDMutex.Lock()
defer policyIDMutex.Unlock()
return m.txn.Inc(mPolicyGlobalID, 1)
}
// GetGlobalID gets current global id.
func (m *Mutator) GetGlobalID() (int64, error) {
return m.txn.GetInt64(mNextGlobalIDKey)
}
// GetPolicyID gets current policy global id.
func (m *Mutator) GetPolicyID() (int64, error) {
return m.txn.GetInt64(mPolicyGlobalID)
}
func (*Mutator) policyKey(policyID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mPolicyPrefix, policyID))
}
func (*Mutator) resourceGroupKey(groupID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mResourceGroupPrefix, groupID))
}
func (*Mutator) dbKey(dbID int64) []byte {
return DBkey(dbID)
}
// DBkey encodes the dbID into dbKey.
func DBkey(dbID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mDBPrefix, dbID))
}
// ParseDBKey decodes the dbkey to get dbID.
func ParseDBKey(dbkey []byte) (int64, error) {
if !IsDBkey(dbkey) {
return 0, ErrInvalidString.GenWithStack("fail to parse dbKey")
}
dbID := strings.TrimPrefix(string(dbkey), mDBPrefix+":")
id, err := strconv.Atoi(dbID)
return int64(id), errors.Trace(err)
}
// IsDBkey checks whether the dbKey comes from DBKey().
func IsDBkey(dbKey []byte) bool {
return strings.HasPrefix(string(dbKey), mDBPrefix+":")
}
func (*Mutator) autoTableIDKey(tableID int64) []byte {
return AutoTableIDKey(tableID)
}
// AutoTableIDKey decodes the auto tableID key.
func AutoTableIDKey(tableID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mTableIDPrefix, tableID))
}
// IsAutoTableIDKey checks whether the key is auto tableID key.
func IsAutoTableIDKey(key []byte) bool {
return strings.HasPrefix(string(key), mTableIDPrefix+":")
}
// ParseAutoTableIDKey decodes the tableID from the auto tableID key.
func ParseAutoTableIDKey(key []byte) (int64, error) {
if !IsAutoTableIDKey(key) {
return 0, ErrInvalidString.GenWithStack("fail to parse autoTableKey")
}
tableID := strings.TrimPrefix(string(key), mTableIDPrefix+":")
id, err := strconv.Atoi(tableID)
return int64(id), err
}
func (*Mutator) autoIncrementIDKey(tableID int64) []byte {
return AutoIncrementIDKey(tableID)
}
// AutoIncrementIDKey decodes the auto inc table key.
func AutoIncrementIDKey(tableID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mIncIDPrefix, tableID))
}
// IsAutoIncrementIDKey checks whether the key is auto increment key.
func IsAutoIncrementIDKey(key []byte) bool {
return strings.HasPrefix(string(key), mIncIDPrefix+":")
}
// ParseAutoIncrementIDKey decodes the tableID from the auto tableID key.
func ParseAutoIncrementIDKey(key []byte) (int64, error) {
if !IsAutoIncrementIDKey(key) {
return 0, ErrInvalidString.GenWithStack("fail to parse autoIncrementKey")
}
tableID := strings.TrimPrefix(string(key), mIncIDPrefix+":")
id, err := strconv.Atoi(tableID)
return int64(id), err
}
func (*Mutator) autoRandomTableIDKey(tableID int64) []byte {
return AutoRandomTableIDKey(tableID)
}
// AutoRandomTableIDKey encodes the auto random tableID key.
func AutoRandomTableIDKey(tableID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mRandomIDPrefix, tableID))
}
// IsAutoRandomTableIDKey checks whether the key is auto random tableID key.
func IsAutoRandomTableIDKey(key []byte) bool {
return strings.HasPrefix(string(key), mRandomIDPrefix+":")
}
// ParseAutoRandomTableIDKey decodes the tableID from the auto random tableID key.
func ParseAutoRandomTableIDKey(key []byte) (int64, error) {
if !IsAutoRandomTableIDKey(key) {
return 0, ErrInvalidString.GenWithStack("fail to parse AutoRandomTableIDKey")
}
tableID := strings.TrimPrefix(string(key), mRandomIDPrefix+":")
id, err := strconv.Atoi(tableID)
return int64(id), err
}
func (*Mutator) tableKey(tableID int64) []byte {
return TableKey(tableID)
}
// TableKey encodes the tableID into tableKey.
func TableKey(tableID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mTablePrefix, tableID))
}
// IsTableKey checks whether the tableKey comes from TableKey().
func IsTableKey(tableKey []byte) bool {
return strings.HasPrefix(string(tableKey), mTablePrefix+":")
}
// ParseTableKey decodes the tableKey to get tableID.
func ParseTableKey(tableKey []byte) (int64, error) {
if !strings.HasPrefix(string(tableKey), mTablePrefix) {
return 0, ErrInvalidString.GenWithStack("fail to parse tableKey")
}
tableID := strings.TrimPrefix(string(tableKey), mTablePrefix+":")
id, err := strconv.Atoi(tableID)
return int64(id), errors.Trace(err)
}
func (*Mutator) sequenceKey(sequenceID int64) []byte {
return SequenceKey(sequenceID)
}
// SequenceKey encodes the sequence key.
func SequenceKey(sequenceID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mSequencePrefix, sequenceID))
}
// IsSequenceKey checks whether the key is sequence key.
func IsSequenceKey(key []byte) bool {
return strings.HasPrefix(string(key), mSequencePrefix+":")
}
// ParseSequenceKey decodes the tableID from the sequence key.
func ParseSequenceKey(key []byte) (int64, error) {
if !IsSequenceKey(key) {
return 0, ErrInvalidString.GenWithStack("fail to parse sequence key")
}
sequenceID := strings.TrimPrefix(string(key), mSequencePrefix+":")
id, err := strconv.Atoi(sequenceID)
return int64(id), errors.Trace(err)
}
func (*Mutator) sequenceCycleKey(sequenceID int64) []byte {
return []byte(fmt.Sprintf("%s:%d", mSeqCyclePrefix, sequenceID))
}
// DDLJobHistoryKey is only used for testing.
func DDLJobHistoryKey(m *Mutator, 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 *Mutator) GenAutoTableIDKeyValue(dbID, tableID, autoID int64) (key, value []byte) {
dbKey := m.dbKey(dbID)
autoTableIDKey := m.autoTableIDKey(tableID)
return m.txn.EncodeHashAutoIDKeyValue(dbKey, autoTableIDKey, autoID)
}
// GetAutoIDAccessors gets the controller for auto IDs.
func (m *Mutator) GetAutoIDAccessors(dbID, tableID int64) AutoIDAccessors {
return NewAutoIDAccessors(m, dbID, tableID)
}
// GetSchemaVersionWithNonEmptyDiff gets current global schema version, if diff is nil, we should return version - 1.
// Consider the following scenario:
/*
// t1 t2 t3 t4
// | | |
// update schema version | set diff
// stale read ts
*/
// At the first time, t2 reads the schema version v10, but the v10's diff is not set yet, so it loads v9 infoSchema.
// But at t4 moment, v10's diff has been set and been cached in the memory, so stale read on t2 will get v10 schema from cache,
// and inconsistency happen.
// To solve this problem, we always check the schema diff at first, if the diff is empty, we know at t2 moment we can only see the v9 schema,
// so make neededSchemaVersion = neededSchemaVersion - 1.
// For `Reload`, we can also do this: if the newest version's diff is not set yet, it is ok to load the previous version's infoSchema, and wait for the next reload.
// if there are multiple consecutive jobs failed or cancelled after the schema version
// increased, the returned 'version - 1' might still not have diff.
func (m *Mutator) GetSchemaVersionWithNonEmptyDiff() (int64, error) {
v, err := m.txn.GetInt64(mSchemaVersionKey)
if err != nil {
return 0, err
}
diff, err := m.GetSchemaDiff(v)
if err != nil {
return 0, err
}
if diff == nil && v > 0 {
// Although the diff of v is undetermined, the last version's diff is deterministic(this is guaranteed by schemaVersionManager).
v--
}
return v, err
}
// EncodeSchemaDiffKey returns the raw kv key for a schema diff
func (m *Mutator) EncodeSchemaDiffKey(schemaVersion int64) kv.Key {
diffKey := m.schemaDiffKey(schemaVersion)
return m.txn.EncodeStringDataKey(diffKey)
}
// GetSchemaVersion gets current global schema version.
func (m *Mutator) GetSchemaVersion() (int64, error) {
return m.txn.GetInt64(mSchemaVersionKey)
}
// GenSchemaVersion generates next schema version.
func (m *Mutator) GenSchemaVersion() (int64, error) {
return m.txn.Inc(mSchemaVersionKey, 1)
}
// GenSchemaVersions increases the schema version.
func (m *Mutator) GenSchemaVersions(count int64) (int64, error) {
return m.txn.Inc(mSchemaVersionKey, count)
}
func (m *Mutator) checkPolicyExists(policyKey []byte) error {
v, err := m.txn.HGet(mPolicies, policyKey)
if err == nil && v == nil {
err = ErrPolicyNotExists.GenWithStack("policy doesn't exist")
}
return errors.Trace(err)
}
func (m *Mutator) checkPolicyNotExists(policyKey []byte) error {
v, err := m.txn.HGet(mPolicies, policyKey)
if err == nil && v != nil {
err = ErrPolicyExists.GenWithStack("policy already exists")
}
return errors.Trace(err)
}
func (m *Mutator) checkResourceGroupNotExists(groupKey []byte) error {
v, err := m.txn.HGet(mResourceGroups, groupKey)
if err == nil && v != nil {
err = ErrResourceGroupExists.GenWithStack("group already exists")
}
return errors.Trace(err)
}
func (m *Mutator) checkResourceGroupExists(groupKey []byte) error {
v, err := m.txn.HGet(mResourceGroups, groupKey)
if err == nil && v == nil {
err = ErrResourceGroupNotExists.GenWithStack("group doesn't exist")
}
return errors.Trace(err)
}
func (m *Mutator) 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 *Mutator) 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 *Mutator) 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 *Mutator) 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)
}
// CreatePolicy creates a policy.
func (m *Mutator) CreatePolicy(policy *model.PolicyInfo) error {
if policy.ID == 0 {
return errors.New("policy.ID is invalid")
}
policyKey := m.policyKey(policy.ID)
if err := m.checkPolicyNotExists(policyKey); err != nil {
return errors.Trace(err)
}
data, err := json.Marshal(policy)
if err != nil {
return errors.Trace(err)
}
return m.txn.HSet(mPolicies, policyKey, attachMagicByte(data))
}
// UpdatePolicy updates a policy.
func (m *Mutator) UpdatePolicy(policy *model.PolicyInfo) error {
policyKey := m.policyKey(policy.ID)
if err := m.checkPolicyExists(policyKey); err != nil {
return errors.Trace(err)
}
data, err := json.Marshal(policy)
if err != nil {
return errors.Trace(err)
}
return m.txn.HSet(mPolicies, policyKey, attachMagicByte(data))
}
// AddResourceGroup creates a resource group.
func (m *Mutator) AddResourceGroup(group *model.ResourceGroupInfo) error {
if group.ID == 0 {
return errors.New("group.ID is invalid")
}
groupKey := m.resourceGroupKey(group.ID)
if err := m.checkResourceGroupNotExists(groupKey); err != nil {
return errors.Trace(err)
}
data, err := json.Marshal(group)
if err != nil {
return errors.Trace(err)
}
return m.txn.HSet(mResourceGroups, groupKey, attachMagicByte(data))
}
// UpdateResourceGroup updates a resource group.
func (m *Mutator) UpdateResourceGroup(group *model.ResourceGroupInfo) error {
groupKey := m.resourceGroupKey(group.ID)
// do not check the default because it may not be persisted.
if group.ID != defaultGroupID {
if err := m.checkResourceGroupExists(groupKey); err != nil {
return errors.Trace(err)
}
}
data, err := json.Marshal(group)
if err != nil {
return errors.Trace(err)
}
return m.txn.HSet(mResourceGroups, groupKey, attachMagicByte(data))
}
// DropResourceGroup drops a resource group.
func (m *Mutator) DropResourceGroup(groupID int64) error {
// Check if group exists.
groupKey := m.resourceGroupKey(groupID)
if err := m.txn.HDel(mResourceGroups, groupKey); err != nil {
return errors.Trace(err)
}
return nil
}
// CreateDatabase creates a database with db info.
func (m *Mutator) 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)
}
if err := m.txn.HSet(mDBs, dbKey, data); err != nil {
return errors.Trace(err)
}
return nil
}
// UpdateDatabase updates a database with db info.
func (m *Mutator) 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 *Mutator) 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)
}
if err := m.txn.HSet(dbKey, tableKey, data); err != nil {
return errors.Trace(err)
}
return nil
}
// SetBDRRole write BDR role into storage.
func (m *Mutator) SetBDRRole(role string) error {
return errors.Trace(m.txn.Set(mBDRRole, []byte(role)))
}
// GetBDRRole get BDR role from storage.
func (m *Mutator) GetBDRRole() (string, error) {
v, err := m.txn.Get(mBDRRole)
if err != nil {
return "", errors.Trace(err)
}
return string(v), nil
}
// ClearBDRRole clear BDR role from storage.
func (m *Mutator) ClearBDRRole() error {
return errors.Trace(m.txn.Clear(mBDRRole))
}
// SetDDLTables write a key into storage.
func (m *Mutator) SetDDLTables(ddlTableVersion DDLTableVersion) error {
return errors.Trace(m.txn.Set(mDDLTableVersion, ddlTableVersion.Bytes()))
}
// CheckDDLTableVersion check if the tables related to concurrent DDL exists.
func (m *Mutator) CheckDDLTableVersion() (DDLTableVersion, error) {
v, err := m.txn.Get(mDDLTableVersion)
if err != nil {
return -1, errors.Trace(err)
}
if string(v) == "" {
return InitDDLTableVersion, nil
}
ver, err := strconv.Atoi(string(v))
if err != nil {
return -1, errors.Trace(err)
}
return DDLTableVersion(ver), nil
}
// CreateMySQLDatabaseIfNotExists creates mysql schema and return its DB ID.
func (m *Mutator) CreateMySQLDatabaseIfNotExists() (int64, error) {
id, err := m.GetSystemDBID()
if id != 0 || err != nil {
return id, err
}
id, err = m.GenGlobalID()
if err != nil {
return 0, errors.Trace(err)
}
db := model.DBInfo{
ID: id,
Name: pmodel.NewCIStr(mysql.SystemDB),
Charset: mysql.UTF8MB4Charset,
Collate: mysql.UTF8MB4DefaultCollation,
State: model.StatePublic,
}
err = m.CreateDatabase(&db)
return db.ID, err
}
// GetSystemDBID gets the system DB ID. return (0, nil) indicates that the system DB does not exist.
func (m *Mutator) GetSystemDBID() (int64, error) {
dbs, err := m.ListDatabases()
if err != nil {
return 0, err
}
for _, db := range dbs {
if db.Name.L == mysql.SystemDB {
return db.ID, nil
}
}
return 0, nil
}
// SetMetadataLock sets the metadata lock.
func (m *Mutator) SetMetadataLock(b bool) error {
var data []byte
if b {
data = []byte("1")
} else {
data = []byte("0")
}
return errors.Trace(m.txn.Set(mMetaDataLock, data))
}
// GetMetadataLock gets the metadata lock.
func (m *Mutator) GetMetadataLock() (enable bool, isNull bool, err error) {
val, err := m.txn.Get(mMetaDataLock)
if err != nil {
return false, false, errors.Trace(err)
}
if len(val) == 0 {
return false, true, nil
}
return bytes.Equal(val, []byte("1")), false, nil
}
// SetSchemaCacheSize sets the schema cache size.
func (m *Mutator) SetSchemaCacheSize(size uint64) error {
return errors.Trace(m.txn.Set(mSchemaCacheSize, []byte(strconv.FormatUint(size, 10))))
}
// GetSchemaCacheSize gets the schema cache size.
func (m *Mutator) GetSchemaCacheSize() (size uint64, isNull bool, err error) {
val, err := m.txn.Get(mSchemaCacheSize)
if err != nil {
return 0, false, errors.Trace(err)
}
if len(val) == 0 {
return 0, true, nil
}
size, err = strconv.ParseUint(string(val), 10, 64)
return size, false, errors.Trace(err)
}
// CreateTableAndSetAutoID creates a table with tableInfo in database,
// and rebases the table autoID.
func (m *Mutator) CreateTableAndSetAutoID(dbID int64, tableInfo *model.TableInfo, autoIDs model.AutoIDGroup) error {
err := m.CreateTableOrView(dbID, tableInfo)
if err != nil {
return errors.Trace(err)
}
_, err = m.txn.HInc(m.dbKey(dbID), m.autoTableIDKey(tableInfo.ID), autoIDs.RowID)
if err != nil {
return errors.Trace(err)
}
if tableInfo.AutoRandomBits > 0 {
_, err = m.txn.HInc(m.dbKey(dbID), m.autoRandomTableIDKey(tableInfo.ID), autoIDs.RandomID)
if err != nil {
return errors.Trace(err)
}
}
if tableInfo.SepAutoInc() && tableInfo.GetAutoIncrementColInfo() != nil {
_, err = m.txn.HInc(m.dbKey(dbID), m.autoIncrementIDKey(tableInfo.ID), autoIDs.IncrementID)
if err != nil {
return errors.Trace(err)
}
}
return nil
}
// CreateSequenceAndSetSeqValue creates sequence with tableInfo in database, and rebase the sequence seqValue.
func (m *Mutator) 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 *Mutator) 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))))
}
// DropPolicy drops the specified policy.
func (m *Mutator) DropPolicy(policyID int64) error {
// Check if policy exists.
policyKey := m.policyKey(policyID)
if err := m.txn.HClear(policyKey); err != nil {
return errors.Trace(err)
}
if err := m.txn.HDel(mPolicies, policyKey); err != nil {
return errors.Trace(err)
}
return nil
}
// DropDatabase drops whole database.
func (m *Mutator) 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 *Mutator) DropSequence(dbID int64, tblID int64) error {
err := m.DropTableOrView(dbID, tblID)
if err != nil {
return err
}
err = m.GetAutoIDAccessors(dbID, tblID).Del()
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 *Mutator) DropTableOrView(dbID int64, tblID 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(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)
}
return nil
}
// UpdateTable updates the table with table info.
func (m *Mutator) 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)
}
tableInfo.Revision++
data, err := json.Marshal(tableInfo)
if err != nil {
return errors.Trace(err)
}
err = m.txn.HSet(dbKey, tableKey, data)
return errors.Trace(err)
}
// IterTables iterates all the table at once, in order to avoid oom.
func (m *Mutator) IterTables(dbID int64, fn func(info *model.TableInfo) error) error {
dbKey := m.dbKey(dbID)
if err := m.checkDBExists(dbKey); err != nil {
return errors.Trace(err)
}
err := m.txn.HGetIter(dbKey, func(r structure.HashPair) error {
// only handle table meta
tableKey := string(r.Field)
if !strings.HasPrefix(tableKey, mTablePrefix) {
return nil
}
tbInfo := &model.TableInfo{}
err := json.Unmarshal(r.Value, tbInfo)
if err != nil {
return errors.Trace(err)
}
tbInfo.DBID = dbID
err = fn(tbInfo)
return errors.Trace(err)
})
return errors.Trace(err)
}
// GetMetasByDBID return all meta information of a database.
// Note(dongmen): This method is used by TiCDC to reduce the time of changefeed initialization.
// Ref: https://github.com/pingcap/tiflow/issues/11109