|
| 1 | +// Copyright 2025 PingCAP, Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package ddl |
| 16 | + |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + |
| 20 | + "github.com/pingcap/errors" |
| 21 | + "github.com/pingcap/tidb/pkg/ddl/logutil" |
| 22 | + "github.com/pingcap/tidb/pkg/domain/affinity" |
| 23 | + "github.com/pingcap/tidb/pkg/meta/model" |
| 24 | + "github.com/pingcap/tidb/pkg/parser/ast" |
| 25 | + "github.com/pingcap/tidb/pkg/tablecodec" |
| 26 | + tikv "github.com/tikv/client-go/v2/tikv" |
| 27 | + pdhttp "github.com/tikv/pd/client/http" |
| 28 | + "go.uber.org/zap" |
| 29 | +) |
| 30 | + |
| 31 | +// GetTableAffinityGroupID returns the affinity group ID for a table. |
| 32 | +// Format: "_tidb_t_{tableID}" |
| 33 | +func GetTableAffinityGroupID(tableID int64) string { |
| 34 | + return fmt.Sprintf("_tidb_t_%d", tableID) |
| 35 | +} |
| 36 | + |
| 37 | +// GetPartitionAffinityGroupID returns the affinity group ID for a partition. |
| 38 | +// Format: "_tidb_pt_{tableID}_p{partitionID}" |
| 39 | +func GetPartitionAffinityGroupID(tableID, partitionID int64) string { |
| 40 | + return fmt.Sprintf("_tidb_pt_%d_p%d", tableID, partitionID) |
| 41 | +} |
| 42 | + |
| 43 | +func buildAffinityGroupKeyRange(codec tikv.Codec, physicalID int64) pdhttp.AffinityGroupKeyRange { |
| 44 | + startKey := tablecodec.EncodeTablePrefix(physicalID) |
| 45 | + endKey := tablecodec.EncodeTablePrefix(physicalID + 1) |
| 46 | + if codec != nil { |
| 47 | + startKey, endKey = codec.EncodeRegionRange(startKey, endKey) |
| 48 | + } |
| 49 | + return pdhttp.AffinityGroupKeyRange{ |
| 50 | + StartKey: startKey, |
| 51 | + EndKey: endKey, |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +// buildAffinityGroupDefinitions constructs affinity group definitions based on table's affinity configuration. |
| 56 | +// It generates affinity group IDs in two different formats depending on the affinity level: |
| 57 | +// - Table-level affinity: "_tidb_t_{tableID}" - one group for the entire table |
| 58 | +// - Partition-level affinity: "_tidb_pt_{tableID}_p{partitionID}" - one group per partition |
| 59 | +func buildAffinityGroupDefinitions(codec tikv.Codec, tblInfo *model.TableInfo, partitionDefs []model.PartitionDefinition) (map[string][]pdhttp.AffinityGroupKeyRange, error) { |
| 60 | + if tblInfo == nil || tblInfo.Affinity == nil { |
| 61 | + return nil, nil |
| 62 | + } |
| 63 | + |
| 64 | + switch tblInfo.Affinity.Level { |
| 65 | + case ast.TableAffinityLevelTable: |
| 66 | + groupID := GetTableAffinityGroupID(tblInfo.ID) |
| 67 | + return map[string][]pdhttp.AffinityGroupKeyRange{ |
| 68 | + groupID: {buildAffinityGroupKeyRange(codec, tblInfo.ID)}, |
| 69 | + }, nil |
| 70 | + case ast.TableAffinityLevelPartition: |
| 71 | + definitions := partitionDefs |
| 72 | + if definitions == nil && tblInfo.GetPartitionInfo() != nil { |
| 73 | + definitions = tblInfo.GetPartitionInfo().Definitions |
| 74 | + } |
| 75 | + if len(definitions) == 0 { |
| 76 | + return nil, errors.Errorf("partition affinity requires partition definitions for table %s (ID: %d), table metadata may be corrupted", tblInfo.Name.O, tblInfo.ID) |
| 77 | + } |
| 78 | + |
| 79 | + groups := make(map[string][]pdhttp.AffinityGroupKeyRange, len(definitions)) |
| 80 | + for _, def := range definitions { |
| 81 | + groupID := GetPartitionAffinityGroupID(tblInfo.ID, def.ID) |
| 82 | + groups[groupID] = []pdhttp.AffinityGroupKeyRange{buildAffinityGroupKeyRange(codec, def.ID)} |
| 83 | + } |
| 84 | + return groups, nil |
| 85 | + default: |
| 86 | + return nil, errors.Errorf("invalid affinity level: %s for table %s (ID: %d)", tblInfo.Affinity.Level, tblInfo.Name.O, tblInfo.ID) |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +func collectAffinityGroupIDs(groups map[string][]pdhttp.AffinityGroupKeyRange) []string { |
| 91 | + if len(groups) == 0 { |
| 92 | + return nil |
| 93 | + } |
| 94 | + ids := make([]string, 0, len(groups)) |
| 95 | + for id := range groups { |
| 96 | + ids = append(ids, id) |
| 97 | + } |
| 98 | + return ids |
| 99 | +} |
| 100 | + |
| 101 | +// createTableAffinityGroupsInPD creates affinity groups for a table in PD. |
| 102 | +// This is a critical operation. If it fails, the DDL should fail. |
| 103 | +// Used by: CREATE TABLE, ALTER TABLE AFFINITY = 'xxx', TRUNCATE TABLE, TRUNCATE PARTITION. |
| 104 | +func createTableAffinityGroupsInPD(jobCtx *jobContext, tblInfo *model.TableInfo) error { |
| 105 | + if tblInfo == nil || tblInfo.Affinity == nil { |
| 106 | + return nil |
| 107 | + } |
| 108 | + |
| 109 | + ctx := jobCtx.stepCtx |
| 110 | + codec := jobCtx.store.GetCodec() |
| 111 | + |
| 112 | + groups, err := buildAffinityGroupDefinitions(codec, tblInfo, nil) |
| 113 | + if err != nil { |
| 114 | + return errors.Trace(err) |
| 115 | + } |
| 116 | + |
| 117 | + if len(groups) == 0 { |
| 118 | + return nil |
| 119 | + } |
| 120 | + |
| 121 | + logutil.DDLLogger().Info("creating affinity groups in PD", |
| 122 | + zap.Int64("tableID", tblInfo.ID), |
| 123 | + zap.Strings("groupIDs", collectAffinityGroupIDs(groups))) |
| 124 | + if err := affinity.CreateGroupsIfNotExists(ctx, groups); err != nil { |
| 125 | + return errors.Trace(err) |
| 126 | + } |
| 127 | + |
| 128 | + return nil |
| 129 | +} |
| 130 | + |
| 131 | +// deleteTableAffinityGroupsInPD deletes affinity groups for a table in PD. |
| 132 | +// This is a best-effort cleanup operation. Failures are logged but the operation continues. |
| 133 | +// Used by: DROP TABLE, ALTER TABLE AFFINITY = ”, TRUNCATE TABLE, TRUNCATE PARTITION. |
| 134 | +// TODO: add gc for unused affinity groups, which is similar to the placement rules. |
| 135 | +func deleteTableAffinityGroupsInPD(jobCtx *jobContext, tblInfo *model.TableInfo, partitionDefs []model.PartitionDefinition) error { |
| 136 | + if tblInfo == nil || tblInfo.Affinity == nil { |
| 137 | + return nil |
| 138 | + } |
| 139 | + |
| 140 | + ctx := jobCtx.stepCtx |
| 141 | + codec := jobCtx.store.GetCodec() |
| 142 | + |
| 143 | + groups, err := buildAffinityGroupDefinitions(codec, tblInfo, partitionDefs) |
| 144 | + if err != nil { |
| 145 | + return errors.Trace(err) |
| 146 | + } |
| 147 | + |
| 148 | + if len(groups) == 0 { |
| 149 | + return nil |
| 150 | + } |
| 151 | + |
| 152 | + ids := collectAffinityGroupIDs(groups) |
| 153 | + return affinity.DeleteGroupsWithRetry(ctx, ids) |
| 154 | +} |
| 155 | + |
| 156 | +// batchDeleteTableAffinityGroups deletes affinity groups for multiple tables in PD. |
| 157 | +// This is used for DROP DATABASE to clean up all table affinity groups at once. |
| 158 | +// Returns error to let the caller decide whether to continue or fail. |
| 159 | +func batchDeleteTableAffinityGroups(jobCtx *jobContext, tables []*model.TableInfo) error { |
| 160 | + if len(tables) == 0 { |
| 161 | + return nil |
| 162 | + } |
| 163 | + |
| 164 | + ctx := jobCtx.stepCtx |
| 165 | + codec := jobCtx.store.GetCodec() |
| 166 | + |
| 167 | + groupIDs := make(map[string]struct{}) |
| 168 | + for _, tblInfo := range tables { |
| 169 | + groups, err := buildAffinityGroupDefinitions(codec, tblInfo, nil) |
| 170 | + if err != nil { |
| 171 | + return errors.Trace(err) |
| 172 | + } |
| 173 | + for id := range groups { |
| 174 | + groupIDs[id] = struct{}{} |
| 175 | + } |
| 176 | + } |
| 177 | + if len(groupIDs) == 0 { |
| 178 | + return nil |
| 179 | + } |
| 180 | + |
| 181 | + ids := make([]string, 0, len(groupIDs)) |
| 182 | + for id := range groupIDs { |
| 183 | + ids = append(ids, id) |
| 184 | + } |
| 185 | + |
| 186 | + logutil.DDLLogger().Info("deleting affinity groups for batch tables", zap.Strings("groupIDs", ids)) |
| 187 | + return affinity.DeleteGroupsWithRetry(ctx, ids) |
| 188 | +} |
| 189 | + |
| 190 | +// BuildAffinityGroupDefinitionsForTest is exported for testing. |
| 191 | +func BuildAffinityGroupDefinitionsForTest( |
| 192 | + codec tikv.Codec, |
| 193 | + tblInfo *model.TableInfo, |
| 194 | + partitionDefs []model.PartitionDefinition, |
| 195 | +) (map[string][]pdhttp.AffinityGroupKeyRange, error) { |
| 196 | + return buildAffinityGroupDefinitions(codec, tblInfo, partitionDefs) |
| 197 | +} |
0 commit comments