From 221877d424db768cca77bee40351cf219f75eb01 Mon Sep 17 00:00:00 2001 From: Ryan Leung Date: Wed, 18 Dec 2024 16:50:51 +0800 Subject: [PATCH] *: unify the error definition (#8902) ref tikv/pd#8922 Signed-off-by: Ryan Leung --- errors.toml | 155 +++++++++++++++++++++++ pkg/cgroup/cgroup_cpu.go | 6 +- pkg/cgroup/cgroup_cpu_test.go | 4 +- pkg/errs/errno.go | 75 ++++++++++- pkg/gc/safepoint_v2.go | 3 +- pkg/keyspace/keyspace.go | 43 ++++--- pkg/keyspace/tso_keyspace_group.go | 99 ++++++++------- pkg/keyspace/tso_keyspace_group_test.go | 39 +++--- pkg/keyspace/util.go | 57 --------- pkg/ratelimit/runner.go | 10 +- pkg/schedule/checker/rule_checker.go | 22 +--- pkg/schedule/scatter/region_scatterer.go | 10 +- server/apiv2/handlers/keyspace.go | 2 +- server/keyspace_service.go | 6 +- 14 files changed, 346 insertions(+), 185 deletions(-) diff --git a/errors.toml b/errors.toml index 9bfd4a79190..26b15c38077 100644 --- a/errors.toml +++ b/errors.toml @@ -61,6 +61,11 @@ error = ''' unsupported metrics type %v ''' +["PD:cgroup:ErrNoCPUControllerDetected"] +error = ''' +no cpu controller detected +''' + ["PD:checker:ErrCheckerMergeAgain"] error = ''' region will be merged again, %s @@ -71,6 +76,36 @@ error = ''' checker not found ''' +["PD:checker:ErrNoNewLeader"] +error = ''' +no new leader +''' + +["PD:checker:ErrNoStoreToAdd"] +error = ''' +no store to add peer +''' + +["PD:checker:ErrNoStoreToReplace"] +error = ''' +no store to replace peer +''' + +["PD:checker:ErrPeerCannotBeLeader"] +error = ''' +peer cannot be leader +''' + +["PD:checker:ErrPeerCannotBeWitness"] +error = ''' +peer cannot be witness +''' + +["PD:checker:ErrRegionNoLeader"] +error = ''' +region no leader +''' + ["PD:client:ErrClientCreateTSOStream"] error = ''' create TSO stream failed, %s @@ -491,6 +526,116 @@ error = ''' failed to unmarshal json ''' +["PD:keyspace:ErrExceedMaxEtcdTxnOps"] +error = ''' +exceed max etcd txn operations +''' + +["PD:keyspace:ErrIllegalOperation"] +error = ''' +unknown operation +''' + +["PD:keyspace:ErrKeyspaceExists"] +error = ''' +keyspace already exists +''' + +["PD:keyspace:ErrKeyspaceGroupExists"] +error = ''' +keyspace group already exists +''' + +["PD:keyspace:ErrKeyspaceGroupInMerging"] +error = ''' +keyspace group %v is in merging state +''' + +["PD:keyspace:ErrKeyspaceGroupInSplit"] +error = ''' +keyspace group %v is in split state +''' + +["PD:keyspace:ErrKeyspaceGroupNotEnoughReplicas"] +error = ''' +not enough replicas in the keyspace group +''' + +["PD:keyspace:ErrKeyspaceGroupNotExists"] +error = ''' +keyspace group %v does not exist +''' + +["PD:keyspace:ErrKeyspaceGroupNotInMerging"] +error = ''' +keyspace group %v is not in merging state +''' + +["PD:keyspace:ErrKeyspaceGroupNotInSplit"] +error = ''' +keyspace group %v is not in split state +''' + +["PD:keyspace:ErrKeyspaceGroupPrimaryNotFound"] +error = ''' +primary of keyspace group does not exist +''' + +["PD:keyspace:ErrKeyspaceGroupWithEmptyKeyspace"] +error = ''' +keyspace group with empty keyspace +''' + +["PD:keyspace:ErrKeyspaceNotFound"] +error = ''' +keyspace does not exist +''' + +["PD:keyspace:ErrKeyspaceNotInAnyKeyspaceGroup"] +error = ''' +keyspace is not in any keyspace group +''' + +["PD:keyspace:ErrKeyspaceNotInKeyspaceGroup"] +error = ''' +keyspace is not in this keyspace group +''' + +["PD:keyspace:ErrModifyDefaultKeyspace"] +error = ''' +cannot modify default keyspace's state +''' + +["PD:keyspace:ErrModifyDefaultKeyspaceGroup"] +error = ''' +default keyspace group cannot be modified +''' + +["PD:keyspace:ErrNoAvailableNode"] +error = ''' +no available node +''' + +["PD:keyspace:ErrNodeNotInKeyspaceGroup"] +error = ''' +the tso node is not in this keyspace group +''' + +["PD:keyspace:ErrRegionSplitFailed"] +error = ''' +region split failed +''' + +["PD:keyspace:ErrRegionSplitTimeout"] +error = ''' +region split timeout +''' + +["PD:keyspace:ErrUnsupportedOperationInKeyspace"] +error = ''' +it's a unsupported operation +''' + ["PD:leveldb:ErrLevelDBClose"] error = ''' close leveldb error @@ -646,6 +791,11 @@ error = ''' failed to unmarshal proto ''' +["PD:ratelimit:ErrMaxWaitingTasksExceeded"] +error = ''' +max waiting tasks exceeded +''' + ["PD:region:ErrRegionAbnormalPeer"] error = ''' region %v has abnormal peer @@ -691,6 +841,11 @@ error = ''' invalid group settings, please check the group name, priority and the number of resources ''' +["PD:scatter:ErrEmptyRegion"] +error = ''' +empty region +''' + ["PD:schedule:ErrCreateOperator"] error = ''' unable to create operator, %s diff --git a/pkg/cgroup/cgroup_cpu.go b/pkg/cgroup/cgroup_cpu.go index 67eace5363c..e696e36fad5 100644 --- a/pkg/cgroup/cgroup_cpu.go +++ b/pkg/cgroup/cgroup_cpu.go @@ -19,9 +19,9 @@ import ( "path/filepath" "github.com/pingcap/errors" -) -var errNoCPUControllerDetected = errors.New("no cpu controller detected") + "github.com/tikv/pd/pkg/errs" +) // Helper function for getCgroupCPU. Root is always "/", except in tests. func getCgroupCPUHelper(root string) (CPUUsage, error) { @@ -32,7 +32,7 @@ func getCgroupCPUHelper(root string) (CPUUsage, error) { // No CPU controller detected if path == "" { - return CPUUsage{}, errNoCPUControllerDetected + return CPUUsage{}, errs.ErrNoCPUControllerDetected } mount, ver, err := getCgroupDetails(filepath.Join(root, procPathMountInfo), path, "cpu,cpuacct") diff --git a/pkg/cgroup/cgroup_cpu_test.go b/pkg/cgroup/cgroup_cpu_test.go index 265291163c3..441c2192e79 100644 --- a/pkg/cgroup/cgroup_cpu_test.go +++ b/pkg/cgroup/cgroup_cpu_test.go @@ -26,6 +26,8 @@ import ( "testing" "github.com/stretchr/testify/require" + + "github.com/tikv/pd/pkg/errs" ) func checkKernelVersionNewerThan(re *require.Assertions, t *testing.T, major, minor int) bool { @@ -82,7 +84,7 @@ func TestGetCgroupCPU(t *testing.T) { }() } cpu, err := GetCgroupCPU() - if err == errNoCPUControllerDetected { + if err == errs.ErrNoCPUControllerDetected { // for more information, please refer https://github.com/pingcap/tidb/pull/41347 if checkKernelVersionNewerThan(re, t, 4, 7) { re.NoError(err, "linux version > v4.7 and err still happens") diff --git a/pkg/errs/errno.go b/pkg/errs/errno.go index e5c23cffde2..fd9ff3c95ff 100644 --- a/pkg/errs/errno.go +++ b/pkg/errs/errno.go @@ -140,8 +140,69 @@ var ( // checker errors var ( - ErrCheckerNotFound = errors.Normalize("checker not found", errors.RFCCodeText("PD:checker:ErrCheckerNotFound")) - ErrCheckerMergeAgain = errors.Normalize("region will be merged again, %s", errors.RFCCodeText("PD:checker:ErrCheckerMergeAgain")) + ErrCheckerNotFound = errors.Normalize("checker not found", errors.RFCCodeText("PD:checker:ErrCheckerNotFound")) + ErrCheckerMergeAgain = errors.Normalize("region will be merged again, %s", errors.RFCCodeText("PD:checker:ErrCheckerMergeAgain")) + ErrNoStoreToAdd = errors.Normalize("no store to add peer", errors.RFCCodeText("PD:checker:ErrNoStoreToAdd")) + ErrNoStoreToReplace = errors.Normalize("no store to replace peer", errors.RFCCodeText("PD:checker:ErrNoStoreToReplace")) + ErrPeerCannotBeLeader = errors.Normalize("peer cannot be leader", errors.RFCCodeText("PD:checker:ErrPeerCannotBeLeader")) + ErrPeerCannotBeWitness = errors.Normalize("peer cannot be witness", errors.RFCCodeText("PD:checker:ErrPeerCannotBeWitness")) + ErrNoNewLeader = errors.Normalize("no new leader", errors.RFCCodeText("PD:checker:ErrNoNewLeader")) + ErrRegionNoLeader = errors.Normalize("region no leader", errors.RFCCodeText("PD:checker:ErrRegionNoLeader")) +) + +// scatter errors +var ( + ErrEmptyRegion = errors.Normalize("empty region", errors.RFCCodeText("PD:scatter:ErrEmptyRegion")) +) + +// keyspace errors +var ( + // ErrKeyspaceNotFound is used to indicate target keyspace does not exist. + ErrKeyspaceNotFound = errors.Normalize("keyspace does not exist", errors.RFCCodeText("PD:keyspace:ErrKeyspaceNotFound")) + // ErrRegionSplitTimeout indices to split region timeout + ErrRegionSplitTimeout = errors.Normalize("region split timeout", errors.RFCCodeText("PD:keyspace:ErrRegionSplitTimeout")) + // ErrRegionSplitFailed indices to split region failed + ErrRegionSplitFailed = errors.Normalize("region split failed", errors.RFCCodeText("PD:keyspace:ErrRegionSplitFailed")) + // ErrKeyspaceExists indicates target keyspace already exists. + // It's used when creating a new keyspace. + ErrKeyspaceExists = errors.Normalize("keyspace already exists", errors.RFCCodeText("PD:keyspace:ErrKeyspaceExists")) + // ErrKeyspaceGroupExists indicates target keyspace group already exists. + ErrKeyspaceGroupExists = errors.Normalize("keyspace group already exists", errors.RFCCodeText("PD:keyspace:ErrKeyspaceGroupExists")) + // ErrKeyspaceNotInKeyspaceGroup is used to indicate target keyspace is not in this keyspace group. + ErrKeyspaceNotInKeyspaceGroup = errors.Normalize("keyspace is not in this keyspace group", errors.RFCCodeText("PD:keyspace:ErrKeyspaceNotInKeyspaceGroup")) + // ErrKeyspaceNotInAnyKeyspaceGroup is used to indicate target keyspace is not in any keyspace group. + ErrKeyspaceNotInAnyKeyspaceGroup = errors.Normalize("keyspace is not in any keyspace group", errors.RFCCodeText("PD:keyspace:ErrKeyspaceNotInAnyKeyspaceGroup")) + // ErrNodeNotInKeyspaceGroup is used to indicate the tso node is not in this keyspace group. + ErrNodeNotInKeyspaceGroup = errors.Normalize("the tso node is not in this keyspace group", errors.RFCCodeText("PD:keyspace:ErrNodeNotInKeyspaceGroup")) + // ErrKeyspaceGroupNotEnoughReplicas is used to indicate not enough replicas in the keyspace group. + ErrKeyspaceGroupNotEnoughReplicas = errors.Normalize("not enough replicas in the keyspace group", errors.RFCCodeText("PD:keyspace:ErrKeyspaceGroupNotEnoughReplicas")) + // ErrKeyspaceGroupWithEmptyKeyspace is used to indicate keyspace group with empty keyspace. + ErrKeyspaceGroupWithEmptyKeyspace = errors.Normalize("keyspace group with empty keyspace", errors.RFCCodeText("PD:keyspace:ErrKeyspaceGroupWithEmptyKeyspace")) + // ErrModifyDefaultKeyspaceGroup is used to indicate that default keyspace group cannot be modified. + ErrModifyDefaultKeyspaceGroup = errors.Normalize("default keyspace group cannot be modified", errors.RFCCodeText("PD:keyspace:ErrModifyDefaultKeyspaceGroup")) + // ErrNoAvailableNode is used to indicate no available node in the keyspace group. + ErrNoAvailableNode = errors.Normalize("no available node", errors.RFCCodeText("PD:keyspace:ErrNoAvailableNode")) + // ErrExceedMaxEtcdTxnOps is used to indicate the number of etcd txn operations exceeds the limit. + ErrExceedMaxEtcdTxnOps = errors.Normalize("exceed max etcd txn operations", errors.RFCCodeText("PD:keyspace:ErrExceedMaxEtcdTxnOps")) + // ErrModifyDefaultKeyspace is used to indicate that default keyspace cannot be modified. + ErrModifyDefaultKeyspace = errors.Normalize("cannot modify default keyspace's state", errors.RFCCodeText("PD:keyspace:ErrModifyDefaultKeyspace")) + // ErrIllegalOperation is used to indicate this is an illegal operation. + ErrIllegalOperation = errors.Normalize("unknown operation", errors.RFCCodeText("PD:keyspace:ErrIllegalOperation")) + // ErrUnsupportedOperationInKeyspace is used to indicate this is an unsupported operation. + ErrUnsupportedOperationInKeyspace = errors.Normalize("it's a unsupported operation", errors.RFCCodeText("PD:keyspace:ErrUnsupportedOperationInKeyspace")) + // ErrKeyspaceGroupPrimaryNotFound is used to indicate primary of target keyspace group does not exist. + ErrKeyspaceGroupPrimaryNotFound = errors.Normalize("primary of keyspace group does not exist", errors.RFCCodeText("PD:keyspace:ErrKeyspaceGroupPrimaryNotFound")) + // ErrKeyspaceGroupNotExists is used to indicate target keyspace group does not exist. + ErrKeyspaceGroupNotExists = errors.Normalize("keyspace group %v does not exist", errors.RFCCodeText("PD:keyspace:ErrKeyspaceGroupNotExists")) + // ErrKeyspaceGroupInSplit is used to indicate target keyspace group is in split state. + ErrKeyspaceGroupInSplit = errors.Normalize("keyspace group %v is in split state", errors.RFCCodeText("PD:keyspace:ErrKeyspaceGroupInSplit")) + // ErrKeyspaceGroupNotInSplit is used to indicate target keyspace group is not in split state. + ErrKeyspaceGroupNotInSplit = errors.Normalize("keyspace group %v is not in split state", errors.RFCCodeText("PD:keyspace:ErrKeyspaceGroupNotInSplit")) + // ErrKeyspaceGroupInMerging is used to indicate target keyspace group is in merging state. + ErrKeyspaceGroupInMerging = errors.Normalize("keyspace group %v is in merging state", errors.RFCCodeText("PD:keyspace:ErrKeyspaceGroupInMerging")) + // ErrKeyspaceGroupNotInMerging is used to indicate target keyspace group is not in merging state. + ErrKeyspaceGroupNotInMerging = errors.Normalize("keyspace group %v is not in merging state", errors.RFCCodeText("PD:keyspace:ErrKeyspaceGroupNotInMerging")) + // errKeyspaceGroupNotInMerging is used to indicate target keyspace group is not in merging state. ) // diagnostic errors @@ -229,6 +290,16 @@ var ( ErrBytesToUint64 = errors.Normalize("invalid data, must 8 bytes, but %d", errors.RFCCodeText("PD:typeutil:ErrBytesToUint64")) ) +// cgroup errors +var ( + ErrNoCPUControllerDetected = errors.Normalize("no cpu controller detected", errors.RFCCodeText("PD:cgroup:ErrNoCPUControllerDetected")) +) + +// ratelimit errors +var ( + ErrMaxWaitingTasksExceeded = errors.Normalize("max waiting tasks exceeded", errors.RFCCodeText("PD:ratelimit:ErrMaxWaitingTasksExceeded")) +) + // The third-party project error. // url errors var ( diff --git a/pkg/gc/safepoint_v2.go b/pkg/gc/safepoint_v2.go index 449be8f3d59..acdd4e6eef8 100644 --- a/pkg/gc/safepoint_v2.go +++ b/pkg/gc/safepoint_v2.go @@ -25,6 +25,7 @@ import ( "github.com/pingcap/kvproto/pkg/keyspacepb" "github.com/pingcap/log" + "github.com/tikv/pd/pkg/errs" "github.com/tikv/pd/pkg/keyspace" "github.com/tikv/pd/pkg/slice" "github.com/tikv/pd/pkg/storage/endpoint" @@ -101,7 +102,7 @@ func (manager *SafePointV2Manager) checkKeyspace(keyspaceID uint32, updateReques } // If a keyspace does not exist, then loading its gc safe point is prohibited. if meta == nil { - return keyspace.ErrKeyspaceNotFound + return errs.ErrKeyspaceNotFound } // If keyspace's state does not permit updating safe point, we return error. if updateRequest && !slice.Contains(allowUpdateSafePoint, meta.GetState()) { diff --git a/pkg/keyspace/keyspace.go b/pkg/keyspace/keyspace.go index 4a50f36169f..c9e390df47a 100644 --- a/pkg/keyspace/keyspace.go +++ b/pkg/keyspace/keyspace.go @@ -27,6 +27,7 @@ import ( "github.com/pingcap/kvproto/pkg/keyspacepb" "github.com/pingcap/log" + "github.com/tikv/pd/pkg/errs" "github.com/tikv/pd/pkg/id" "github.com/tikv/pd/pkg/mcs/utils/constant" "github.com/tikv/pd/pkg/schedule/core" @@ -153,7 +154,7 @@ func (manager *Manager) Bootstrap() error { err = manager.saveNewKeyspace(defaultKeyspaceMeta) // It's possible that default keyspace already exists in the storage (e.g. PD restart/recover), // so we ignore the keyspaceExists error. - if err != nil && err != ErrKeyspaceExists { + if err != nil && err != errs.ErrKeyspaceExists { return err } if err := manager.kgm.UpdateKeyspaceForGroup(endpoint.Basic, config[TSOKeyspaceGroupIDKey], defaultKeyspaceMeta.GetId(), opAdd); err != nil { @@ -174,7 +175,7 @@ func (manager *Manager) Bootstrap() error { } keyspace, err := manager.CreateKeyspace(req) // Ignore the keyspaceExists error for the same reason as saving default keyspace. - if err != nil && err != ErrKeyspaceExists { + if err != nil && err != errs.ErrKeyspaceExists { return err } if err := manager.kgm.UpdateKeyspaceForGroup(endpoint.Basic, config[TSOKeyspaceGroupIDKey], keyspace.GetId(), opAdd); err != nil { @@ -288,7 +289,7 @@ func (manager *Manager) saveNewKeyspace(keyspace *keyspacepb.KeyspaceMeta) error return err } if nameExists { - return ErrKeyspaceExists + return errs.ErrKeyspaceExists } err = manager.store.SaveKeyspaceID(txn, keyspace.Id, keyspace.Name) if err != nil { @@ -301,7 +302,7 @@ func (manager *Manager) saveNewKeyspace(keyspace *keyspacepb.KeyspaceMeta) error return err } if loadedMeta != nil { - return ErrKeyspaceExists + return errs.ErrKeyspaceExists } return manager.store.SaveKeyspaceMeta(txn, keyspace) }) @@ -343,7 +344,7 @@ func (manager *Manager) splitKeyspaceRegion(id uint32, waitRegionSplit bool) (er ranges := keyspaceRule.Data.([]*labeler.KeyRangeRule) if len(ranges) < 2 { log.Warn("[keyspace] failed to split keyspace region with insufficient range", logutil.ZapRedactString("label-rule", keyspaceRule.String())) - return ErrRegionSplitFailed + return errs.ErrRegionSplitFailed } rawLeftBound, rawRightBound := ranges[0].StartKey, ranges[0].EndKey txnLeftBound, txnRightBound := ranges[1].StartKey, ranges[1].EndKey @@ -381,7 +382,7 @@ func (manager *Manager) splitKeyspaceRegion(id uint32, waitRegionSplit bool) (er zap.Uint32("keyspace-id", id), zap.Error(err), ) - err = ErrRegionSplitTimeout + err = errs.ErrRegionSplitTimeout return } log.Info("[keyspace] wait region split successfully", zap.Uint32("keyspace-id", id)) @@ -407,14 +408,14 @@ func (manager *Manager) LoadKeyspace(name string) (*keyspacepb.KeyspaceMeta, err return err } if !loaded { - return ErrKeyspaceNotFound + return errs.ErrKeyspaceNotFound } meta, err = manager.store.LoadKeyspaceMeta(txn, id) if err != nil { return err } if meta == nil { - return ErrKeyspaceNotFound + return errs.ErrKeyspaceNotFound } return nil }) @@ -434,7 +435,7 @@ func (manager *Manager) LoadKeyspaceByID(spaceID uint32) (*keyspacepb.KeyspaceMe return err } if meta == nil { - return ErrKeyspaceNotFound + return errs.ErrKeyspaceNotFound } return nil }) @@ -474,7 +475,7 @@ func (manager *Manager) UpdateKeyspaceConfig(name string, mutations []*Mutation) return err } if !loaded { - return ErrKeyspaceNotFound + return errs.ErrKeyspaceNotFound } manager.metaLock.Lock(id) defer manager.metaLock.Unlock(id) @@ -484,7 +485,7 @@ func (manager *Manager) UpdateKeyspaceConfig(name string, mutations []*Mutation) return err } if meta == nil { - return ErrKeyspaceNotFound + return errs.ErrKeyspaceNotFound } // Only keyspace with state listed in allowChangeConfig are allowed to change their config. if !slice.Contains(allowChangeConfig, meta.GetState()) { @@ -505,7 +506,7 @@ func (manager *Manager) UpdateKeyspaceConfig(name string, mutations []*Mutation) case OpDel: delete(meta.Config, mutation.Key) default: - return errIllegalOperation + return errs.ErrIllegalOperation } } newConfig := meta.GetConfig() @@ -553,9 +554,9 @@ func (manager *Manager) UpdateKeyspaceState(name string, newState keyspacepb.Key // Changing the state of default keyspace is not allowed. if name == constant.DefaultKeyspaceName { log.Warn("[keyspace] failed to update keyspace config", - zap.Error(ErrModifyDefaultKeyspace), + errs.ZapError(errs.ErrModifyDefaultKeyspace), ) - return nil, ErrModifyDefaultKeyspace + return nil, errs.ErrModifyDefaultKeyspace } var meta *keyspacepb.KeyspaceMeta err := manager.store.RunInTxn(manager.ctx, func(txn kv.Txn) error { @@ -565,7 +566,7 @@ func (manager *Manager) UpdateKeyspaceState(name string, newState keyspacepb.Key return err } if !loaded { - return ErrKeyspaceNotFound + return errs.ErrKeyspaceNotFound } manager.metaLock.Lock(id) defer manager.metaLock.Unlock(id) @@ -575,7 +576,7 @@ func (manager *Manager) UpdateKeyspaceState(name string, newState keyspacepb.Key return err } if meta == nil { - return ErrKeyspaceNotFound + return errs.ErrKeyspaceNotFound } // Update keyspace meta. if err = updateKeyspaceState(meta, newState, now); err != nil { @@ -605,9 +606,9 @@ func (manager *Manager) UpdateKeyspaceStateByID(id uint32, newState keyspacepb.K // Changing the state of default keyspace is not allowed. if id == constant.DefaultKeyspaceID { log.Warn("[keyspace] failed to update keyspace config", - zap.Error(ErrModifyDefaultKeyspace), + errs.ZapError(errs.ErrModifyDefaultKeyspace), ) - return nil, ErrModifyDefaultKeyspace + return nil, errs.ErrModifyDefaultKeyspace } var meta *keyspacepb.KeyspaceMeta var err error @@ -620,7 +621,7 @@ func (manager *Manager) UpdateKeyspaceStateByID(id uint32, newState keyspacepb.K return err } if meta == nil { - return ErrKeyspaceNotFound + return errs.ErrKeyspaceNotFound } // Update keyspace meta. if err = updateKeyspaceState(meta, newState, now); err != nil { @@ -740,10 +741,10 @@ func (manager *Manager) PatrolKeyspaceAssignment(startKeyspaceID, endKeyspaceID return errors.Errorf("default keyspace group %d not found", constant.DefaultKeyspaceGroupID) } if defaultKeyspaceGroup.IsSplitting() { - return ErrKeyspaceGroupInSplit(constant.DefaultKeyspaceGroupID) + return errs.ErrKeyspaceGroupInSplit.FastGenByArgs(constant.DefaultKeyspaceGroupID) } if defaultKeyspaceGroup.IsMerging() { - return ErrKeyspaceGroupInMerging(constant.DefaultKeyspaceGroupID) + return errs.ErrKeyspaceGroupInMerging.FastGenByArgs(constant.DefaultKeyspaceGroupID) } keyspaces, err := manager.store.LoadRangeKeyspace(txn, manager.nextPatrolStartID, etcdutil.MaxEtcdTxnOps) if err != nil { diff --git a/pkg/keyspace/tso_keyspace_group.go b/pkg/keyspace/tso_keyspace_group.go index dc414cfad3a..a6068ffc2bb 100644 --- a/pkg/keyspace/tso_keyspace_group.go +++ b/pkg/keyspace/tso_keyspace_group.go @@ -33,6 +33,7 @@ import ( "github.com/pingcap/log" "github.com/tikv/pd/pkg/balancer" + "github.com/tikv/pd/pkg/errs" "github.com/tikv/pd/pkg/mcs/discovery" "github.com/tikv/pd/pkg/mcs/utils/constant" "github.com/tikv/pd/pkg/slice" @@ -129,7 +130,7 @@ func (m *GroupManager) Bootstrap(ctx context.Context) error { // Ignore the error if default keyspace group already exists in the storage (e.g. PD restart/recover). err := m.saveKeyspaceGroups([]*endpoint.KeyspaceGroup{defaultKeyspaceGroup}, false) - if err != nil && err != ErrKeyspaceGroupExists { + if err != nil && err != errs.ErrKeyspaceGroupExists { return err } @@ -322,7 +323,7 @@ func (m *GroupManager) DeleteKeyspaceGroupByID(id uint32) (*endpoint.KeyspaceGro return nil } if kg.IsSplitting() { - return ErrKeyspaceGroupInSplit(id) + return errs.ErrKeyspaceGroupInSplit.FastGenByArgs(id) } return m.store.DeleteKeyspaceGroup(txn, id) }); err != nil { @@ -348,13 +349,13 @@ func (m *GroupManager) saveKeyspaceGroups(keyspaceGroups []*endpoint.KeyspaceGro return err } if oldKG != nil && !overwrite { - return ErrKeyspaceGroupExists + return errs.ErrKeyspaceGroupExists } if oldKG.IsSplitting() && overwrite { - return ErrKeyspaceGroupInSplit(keyspaceGroup.ID) + return errs.ErrKeyspaceGroupInSplit.FastGenByArgs(keyspaceGroup.ID) } if oldKG.IsMerging() && overwrite { - return ErrKeyspaceGroupInMerging(keyspaceGroup.ID) + return errs.ErrKeyspaceGroupInMerging.FastGenByArgs(keyspaceGroup.ID) } newKG := &endpoint.KeyspaceGroup{ ID: keyspaceGroup.ID, @@ -410,7 +411,7 @@ func (m *GroupManager) GetGroupByKeyspaceID(id uint32) (uint32, error) { } } } - return 0, ErrKeyspaceNotInAnyKeyspaceGroup + return 0, errs.ErrKeyspaceNotInAnyKeyspaceGroup } var failpointOnce sync.Once @@ -440,13 +441,13 @@ func (m *GroupManager) UpdateKeyspaceForGroup(userKind endpoint.UserKind, groupI func (m *GroupManager) updateKeyspaceForGroupLocked(userKind endpoint.UserKind, groupID uint64, keyspaceID uint32, mutation int) error { kg := m.groups[userKind].Get(uint32(groupID)) if kg == nil { - return ErrKeyspaceGroupNotExists(uint32(groupID)) + return errs.ErrKeyspaceGroupNotExists.FastGenByArgs(uint32(groupID)) } if kg.IsSplitting() { - return ErrKeyspaceGroupInSplit(uint32(groupID)) + return errs.ErrKeyspaceGroupInSplit.FastGenByArgs(uint32(groupID)) } if kg.IsMerging() { - return ErrKeyspaceGroupInMerging(uint32(groupID)) + return errs.ErrKeyspaceGroupInMerging.FastGenByArgs(uint32(groupID)) } changed := false @@ -500,13 +501,13 @@ func (m *GroupManager) UpdateKeyspaceGroup(oldGroupID, newGroupID string, oldUse return errors.Errorf("keyspace group %s not found in %s group", newGroupID, newUserKind) } if oldKG.IsSplitting() { - return ErrKeyspaceGroupInSplit(uint32(oldID)) + return errs.ErrKeyspaceGroupInSplit.FastGenByArgs(uint32(oldID)) } else if newKG.IsSplitting() { - return ErrKeyspaceGroupInSplit(uint32(newID)) + return errs.ErrKeyspaceGroupInSplit.FastGenByArgs(uint32(newID)) } else if oldKG.IsMerging() { - return ErrKeyspaceGroupInMerging(uint32(oldID)) + return errs.ErrKeyspaceGroupInMerging.FastGenByArgs(uint32(oldID)) } else if newKG.IsMerging() { - return ErrKeyspaceGroupInMerging(uint32(newID)) + return errs.ErrKeyspaceGroupInMerging.FastGenByArgs(uint32(newID)) } var updateOld, updateNew bool @@ -552,15 +553,15 @@ func (m *GroupManager) SplitKeyspaceGroupByID( return err } if splitSourceKg == nil { - return ErrKeyspaceGroupNotExists(splitSourceID) + return errs.ErrKeyspaceGroupNotExists.FastGenByArgs(splitSourceID) } // A keyspace group can not take part in multiple split processes. if splitSourceKg.IsSplitting() { - return ErrKeyspaceGroupInSplit(splitSourceID) + return errs.ErrKeyspaceGroupInSplit.FastGenByArgs(splitSourceID) } // A keyspace group can not be split when it is in merging. if splitSourceKg.IsMerging() { - return ErrKeyspaceGroupInMerging(splitSourceID) + return errs.ErrKeyspaceGroupInMerging.FastGenByArgs(splitSourceID) } // Build the new keyspace groups for split source and target. var startKeyspaceID, endKeyspaceID uint32 @@ -574,7 +575,7 @@ func (m *GroupManager) SplitKeyspaceGroupByID( } // Check if the source keyspace group has enough replicas. if len(splitSourceKg.Members) < constant.DefaultKeyspaceGroupReplicaCount { - return ErrKeyspaceGroupNotEnoughReplicas + return errs.ErrKeyspaceGroupNotEnoughReplicas } // Check if the new keyspace group already exists. splitTargetKg, err = m.store.LoadKeyspaceGroup(txn, splitTargetID) @@ -582,7 +583,7 @@ func (m *GroupManager) SplitKeyspaceGroupByID( return err } if splitTargetKg != nil { - return ErrKeyspaceGroupExists + return errs.ErrKeyspaceGroupExists } // Update the old keyspace group. splitSourceKg.Keyspaces = splitSourceKeyspaces @@ -623,7 +624,7 @@ func buildSplitKeyspaces( // Split according to the new keyspace list. if newNum != 0 { if newNum > oldNum { - return nil, nil, ErrKeyspaceNotInKeyspaceGroup + return nil, nil, errs.ErrKeyspaceNotInKeyspaceGroup } var ( oldKeyspaceMap = make(map[uint32]struct{}, oldNum) @@ -634,10 +635,10 @@ func buildSplitKeyspaces( } for _, keyspace := range new { if keyspace == constant.DefaultKeyspaceID { - return nil, nil, ErrModifyDefaultKeyspace + return nil, nil, errs.ErrModifyDefaultKeyspace } if _, ok := oldKeyspaceMap[keyspace]; !ok { - return nil, nil, ErrKeyspaceNotInKeyspaceGroup + return nil, nil, errs.ErrKeyspaceNotInKeyspaceGroup } newKeyspaceMap[keyspace] = struct{}{} } @@ -662,7 +663,7 @@ func buildSplitKeyspaces( } // Split according to the start and end keyspace ID. if startKeyspaceID == 0 && endKeyspaceID == 0 { - return nil, nil, ErrKeyspaceNotInKeyspaceGroup + return nil, nil, errs.ErrKeyspaceNotInKeyspaceGroup } var ( newSplit = make([]uint32, 0, oldNum) @@ -681,7 +682,7 @@ func buildSplitKeyspaces( } // Check if the new keyspace list is empty. if len(newSplit) == 0 { - return nil, nil, ErrKeyspaceGroupWithEmptyKeyspace + return nil, nil, errs.ErrKeyspaceGroupWithEmptyKeyspace } // Get the split keyspace list for the old keyspace group. oldSplit := make([]uint32, 0, oldNum-len(newSplit)) @@ -705,11 +706,11 @@ func (m *GroupManager) FinishSplitKeyspaceByID(splitTargetID uint32) error { return err } if splitTargetKg == nil { - return ErrKeyspaceGroupNotExists(splitTargetID) + return errs.ErrKeyspaceGroupNotExists.FastGenByArgs(splitTargetID) } // Check if it's in the split state. if !splitTargetKg.IsSplitTarget() { - return ErrKeyspaceGroupNotInSplit(splitTargetID) + return errs.ErrKeyspaceGroupNotInSplit.FastGenByArgs(splitTargetID) } // Load the split source keyspace group then. splitSourceKg, err = m.store.LoadKeyspaceGroup(txn, splitTargetKg.SplitSource()) @@ -717,10 +718,10 @@ func (m *GroupManager) FinishSplitKeyspaceByID(splitTargetID uint32) error { return err } if splitSourceKg == nil { - return ErrKeyspaceGroupNotExists(splitTargetKg.SplitSource()) + return errs.ErrKeyspaceGroupNotExists.FastGenByArgs(splitTargetKg.SplitSource()) } if !splitSourceKg.IsSplitSource() { - return ErrKeyspaceGroupNotInSplit(splitTargetKg.SplitSource()) + return errs.ErrKeyspaceGroupNotInSplit.FastGenByArgs(splitTargetKg.SplitSource()) } splitTargetKg.SplitState = nil splitSourceKg.SplitState = nil @@ -765,13 +766,13 @@ func (m *GroupManager) AllocNodesForKeyspaceGroup(id uint32, existMembers map[st return err } if kg == nil { - return ErrKeyspaceGroupNotExists(id) + return errs.ErrKeyspaceGroupNotExists.FastGenByArgs(id) } if kg.IsSplitting() { - return ErrKeyspaceGroupInSplit(id) + return errs.ErrKeyspaceGroupInSplit.FastGenByArgs(id) } if kg.IsMerging() { - return ErrKeyspaceGroupInMerging(id) + return errs.ErrKeyspaceGroupInMerging.FastGenByArgs(id) } for addr := range existMembers { @@ -788,14 +789,14 @@ func (m *GroupManager) AllocNodesForKeyspaceGroup(id uint32, existMembers map[st case <-ticker.C: } if m.GetNodesCount() == 0 { // double check - return ErrNoAvailableNode + return errs.ErrNoAvailableNode } if len(existMembers) == m.GetNodesCount() { break } addr := m.nodesBalancer.Next() if addr == "" { - return ErrNoAvailableNode + return errs.ErrNoAvailableNode } if _, ok := existMembers[addr]; ok { continue @@ -831,13 +832,13 @@ func (m *GroupManager) SetNodesForKeyspaceGroup(id uint32, nodes []string) error return err } if kg == nil { - return ErrKeyspaceGroupNotExists(id) + return errs.ErrKeyspaceGroupNotExists.FastGenByArgs(id) } if kg.IsSplitting() { - return ErrKeyspaceGroupInSplit(id) + return errs.ErrKeyspaceGroupInSplit.FastGenByArgs(id) } if kg.IsMerging() { - return ErrKeyspaceGroupInMerging(id) + return errs.ErrKeyspaceGroupInMerging.FastGenByArgs(id) } members := make([]endpoint.KeyspaceGroupMember, 0, len(nodes)) for _, node := range nodes { @@ -868,13 +869,13 @@ func (m *GroupManager) SetPriorityForKeyspaceGroup(id uint32, node string, prior return err } if kg == nil { - return ErrKeyspaceGroupNotExists(id) + return errs.ErrKeyspaceGroupNotExists.FastGenByArgs(id) } if kg.IsSplitting() { - return ErrKeyspaceGroupInSplit(id) + return errs.ErrKeyspaceGroupInSplit.FastGenByArgs(id) } if kg.IsMerging() { - return ErrKeyspaceGroupInMerging(id) + return errs.ErrKeyspaceGroupInMerging.FastGenByArgs(id) } inKeyspaceGroup := false members := make([]endpoint.KeyspaceGroupMember, 0, len(kg.Members)) @@ -886,7 +887,7 @@ func (m *GroupManager) SetPriorityForKeyspaceGroup(id uint32, node string, prior members = append(members, member) } if !inKeyspaceGroup { - return ErrNodeNotInKeyspaceGroup + return errs.ErrNodeNotInKeyspaceGroup } kg.Members = members return m.store.SaveKeyspaceGroup(txn, kg) @@ -920,10 +921,10 @@ func (m *GroupManager) MergeKeyspaceGroups(mergeTargetID uint32, mergeList []uin // - Load and update the target keyspace group. // So we pre-check the number of operations to avoid exceeding the maximum number of etcd transaction. if (mergeListNum+1)*2 > etcdutil.MaxEtcdTxnOps { - return ErrExceedMaxEtcdTxnOps + return errs.ErrExceedMaxEtcdTxnOps } if slice.Contains(mergeList, constant.DefaultKeyspaceGroupID) { - return ErrModifyDefaultKeyspaceGroup + return errs.ErrModifyDefaultKeyspaceGroup } var ( groups = make(map[uint32]*endpoint.KeyspaceGroup, mergeListNum+1) @@ -939,15 +940,15 @@ func (m *GroupManager) MergeKeyspaceGroups(mergeTargetID uint32, mergeList []uin return err } if kg == nil { - return ErrKeyspaceGroupNotExists(kgID) + return errs.ErrKeyspaceGroupNotExists.FastGenByArgs(kgID) } // A keyspace group can not be merged if it's in splitting. if kg.IsSplitting() { - return ErrKeyspaceGroupInSplit(kgID) + return errs.ErrKeyspaceGroupInSplit.FastGenByArgs(kgID) } // A keyspace group can not be split when it is in merging. if kg.IsMerging() { - return ErrKeyspaceGroupInMerging(kgID) + return errs.ErrKeyspaceGroupInMerging.FastGenByArgs(kgID) } groups[kgID] = kg } @@ -1013,11 +1014,11 @@ func (m *GroupManager) FinishMergeKeyspaceByID(mergeTargetID uint32) error { return err } if mergeTargetKg == nil { - return ErrKeyspaceGroupNotExists(mergeTargetID) + return errs.ErrKeyspaceGroupNotExists.FastGenByArgs(mergeTargetID) } // Check if it's in the merging state. if !mergeTargetKg.IsMergeTarget() { - return ErrKeyspaceGroupNotInMerging(mergeTargetID) + return errs.ErrKeyspaceGroupNotInMerging.FastGenByArgs(mergeTargetID) } // Make sure all merging keyspace groups are deleted. for _, kgID := range mergeTargetKg.MergeState.MergeList { @@ -1026,7 +1027,7 @@ func (m *GroupManager) FinishMergeKeyspaceByID(mergeTargetID uint32) error { return err } if kg != nil { - return ErrKeyspaceGroupNotInMerging(kgID) + return errs.ErrKeyspaceGroupNotInMerging.FastGenByArgs(kgID) } } mergeList = mergeTargetKg.MergeState.MergeList @@ -1150,7 +1151,7 @@ func (m *GroupManager) GetKeyspaceGroupPrimaryByID(id uint32) (string, error) { return "", err } if kg == nil { - return "", ErrKeyspaceGroupNotExists(id) + return "", errs.ErrKeyspaceGroupNotExists.FastGenByArgs(id) } primaryPath := keypath.LeaderPath(&keypath.MsParam{ @@ -1163,7 +1164,7 @@ func (m *GroupManager) GetKeyspaceGroupPrimaryByID(id uint32) (string, error) { return "", err } if !ok { - return "", ErrKeyspaceGroupPrimaryNotFound + return "", errs.ErrKeyspaceGroupPrimaryNotFound } // The format of leader name is address-groupID. contents := strings.Split(leader.GetName(), "-") diff --git a/pkg/keyspace/tso_keyspace_group_test.go b/pkg/keyspace/tso_keyspace_group_test.go index c615627be71..68461855c6f 100644 --- a/pkg/keyspace/tso_keyspace_group_test.go +++ b/pkg/keyspace/tso_keyspace_group_test.go @@ -23,6 +23,7 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + "github.com/tikv/pd/pkg/errs" "github.com/tikv/pd/pkg/mcs/utils/constant" "github.com/tikv/pd/pkg/mock/mockcluster" "github.com/tikv/pd/pkg/mock/mockconfig" @@ -256,13 +257,13 @@ func (suite *keyspaceGroupTestSuite) TestKeyspaceGroupSplit() { re.NoError(err) // split the default keyspace err = suite.kgm.SplitKeyspaceGroupByID(0, 4, []uint32{constant.DefaultKeyspaceID}) - re.ErrorIs(err, ErrModifyDefaultKeyspace) + re.ErrorIs(err, errs.ErrModifyDefaultKeyspace) // split the keyspace group 1 to 4 err = suite.kgm.SplitKeyspaceGroupByID(1, 4, []uint32{444}) - re.ErrorIs(err, ErrKeyspaceGroupNotEnoughReplicas) + re.ErrorIs(err, errs.ErrKeyspaceGroupNotEnoughReplicas) // split the keyspace group 2 to 4 without giving any keyspace err = suite.kgm.SplitKeyspaceGroupByID(2, 4, []uint32{}) - re.ErrorIs(err, ErrKeyspaceNotInKeyspaceGroup) + re.ErrorIs(err, errs.ErrKeyspaceNotInKeyspaceGroup) // split the keyspace group 2 to 4 err = suite.kgm.SplitKeyspaceGroupByID(2, 4, []uint32{333}) re.NoError(err) @@ -283,25 +284,25 @@ func (suite *keyspaceGroupTestSuite) TestKeyspaceGroupSplit() { // finish the split of the keyspace group 2 err = suite.kgm.FinishSplitKeyspaceByID(2) - re.ErrorContains(err, ErrKeyspaceGroupNotInSplit(2).Error()) + re.ErrorContains(err, errs.ErrKeyspaceGroupNotInSplit.FastGenByArgs(2).Error()) // finish the split of a non-existing keyspace group err = suite.kgm.FinishSplitKeyspaceByID(5) - re.ErrorContains(err, ErrKeyspaceGroupNotExists(5).Error()) + re.ErrorContains(err, errs.ErrKeyspaceGroupNotExists.FastGenByArgs(5).Error()) // split the in-split keyspace group err = suite.kgm.SplitKeyspaceGroupByID(2, 4, []uint32{333}) - re.ErrorContains(err, ErrKeyspaceGroupInSplit(2).Error()) + re.ErrorContains(err, errs.ErrKeyspaceGroupInSplit.FastGenByArgs(2).Error()) // remove the in-split keyspace group kg2, err = suite.kgm.DeleteKeyspaceGroupByID(2) re.Nil(kg2) - re.ErrorContains(err, ErrKeyspaceGroupInSplit(2).Error()) + re.ErrorContains(err, errs.ErrKeyspaceGroupInSplit.FastGenByArgs(2).Error()) kg4, err = suite.kgm.DeleteKeyspaceGroupByID(4) re.Nil(kg4) - re.ErrorContains(err, ErrKeyspaceGroupInSplit(4).Error()) + re.ErrorContains(err, errs.ErrKeyspaceGroupInSplit.FastGenByArgs(4).Error()) // update the in-split keyspace group err = suite.kg.kgm.UpdateKeyspaceForGroup(endpoint.Standard, "2", 444, opAdd) - re.ErrorContains(err, ErrKeyspaceGroupInSplit(2).Error()) + re.ErrorContains(err, errs.ErrKeyspaceGroupInSplit.FastGenByArgs(2).Error()) err = suite.kg.kgm.UpdateKeyspaceForGroup(endpoint.Standard, "4", 444, opAdd) - re.ErrorContains(err, ErrKeyspaceGroupInSplit(4).Error()) + re.ErrorContains(err, errs.ErrKeyspaceGroupInSplit.FastGenByArgs(4).Error()) // finish the split of keyspace group 4 err = suite.kgm.FinishSplitKeyspaceByID(4) @@ -321,13 +322,13 @@ func (suite *keyspaceGroupTestSuite) TestKeyspaceGroupSplit() { // split a non-existing keyspace group err = suite.kgm.SplitKeyspaceGroupByID(3, 5, nil) - re.ErrorContains(err, ErrKeyspaceGroupNotExists(3).Error()) + re.ErrorContains(err, errs.ErrKeyspaceGroupNotExists.FastGenByArgs(3).Error()) // split into an existing keyspace group err = suite.kgm.SplitKeyspaceGroupByID(2, 4, []uint32{111}) - re.ErrorIs(err, ErrKeyspaceGroupExists) + re.ErrorIs(err, errs.ErrKeyspaceGroupExists) // split with the wrong keyspaces. err = suite.kgm.SplitKeyspaceGroupByID(2, 5, []uint32{111, 222, 444}) - re.ErrorIs(err, ErrKeyspaceNotInKeyspaceGroup) + re.ErrorIs(err, errs.ErrKeyspaceNotInKeyspaceGroup) } func (suite *keyspaceGroupTestSuite) TestKeyspaceGroupSplitRange() { @@ -449,13 +450,13 @@ func (suite *keyspaceGroupTestSuite) TestKeyspaceGroupMerge() { // merge a non-existing keyspace group err = suite.kgm.MergeKeyspaceGroups(4, []uint32{5}) - re.ErrorContains(err, ErrKeyspaceGroupNotExists(5).Error()) + re.ErrorContains(err, errs.ErrKeyspaceGroupNotExists.FastGenByArgs(5).Error()) // merge with the number of keyspace groups exceeds the limit err = suite.kgm.MergeKeyspaceGroups(1, make([]uint32, etcdutil.MaxEtcdTxnOps/2)) - re.ErrorIs(err, ErrExceedMaxEtcdTxnOps) + re.ErrorIs(err, errs.ErrExceedMaxEtcdTxnOps) // merge the default keyspace group err = suite.kgm.MergeKeyspaceGroups(1, []uint32{constant.DefaultKeyspaceGroupID}) - re.ErrorIs(err, ErrModifyDefaultKeyspaceGroup) + re.ErrorIs(err, errs.ErrModifyDefaultKeyspaceGroup) } func TestBuildSplitKeyspaces(t *testing.T) { @@ -484,7 +485,7 @@ func TestBuildSplitKeyspaces(t *testing.T) { { old: []uint32{1, 2, 3, 4, 5}, new: []uint32{6}, - err: ErrKeyspaceNotInKeyspaceGroup, + err: errs.ErrKeyspaceNotInKeyspaceGroup, }, { old: []uint32{1, 2}, @@ -545,11 +546,11 @@ func TestBuildSplitKeyspaces(t *testing.T) { old: []uint32{1, 2, 3, 4, 5}, startKeyspaceID: 7, endKeyspaceID: 10, - err: ErrKeyspaceGroupWithEmptyKeyspace, + err: errs.ErrKeyspaceGroupWithEmptyKeyspace, }, { old: []uint32{1, 2, 3, 4, 5}, - err: ErrKeyspaceNotInKeyspaceGroup, + err: errs.ErrKeyspaceNotInKeyspaceGroup, }, } for idx, testCase := range testCases { diff --git a/pkg/keyspace/util.go b/pkg/keyspace/util.go index 95b3162eed0..e68a8fa60e8 100644 --- a/pkg/keyspace/util.go +++ b/pkg/keyspace/util.go @@ -38,60 +38,6 @@ const ( ) var ( - // ErrKeyspaceNotFound is used to indicate target keyspace does not exist. - ErrKeyspaceNotFound = errors.New("keyspace does not exist") - // ErrRegionSplitTimeout indices to split region timeout - ErrRegionSplitTimeout = errors.New("region split timeout") - // ErrRegionSplitFailed indices to split region failed - ErrRegionSplitFailed = errors.New("region split failed") - // ErrKeyspaceExists indicates target keyspace already exists. - // It's used when creating a new keyspace. - ErrKeyspaceExists = errors.New("keyspace already exists") - // ErrKeyspaceGroupExists indicates target keyspace group already exists. - ErrKeyspaceGroupExists = errors.New("keyspace group already exists") - // ErrKeyspaceGroupNotExists is used to indicate target keyspace group does not exist. - ErrKeyspaceGroupNotExists = func(groupID uint32) error { - return errors.Errorf("keyspace group %v does not exist", groupID) - } - // ErrKeyspaceGroupInSplit is used to indicate target keyspace group is in split state. - ErrKeyspaceGroupInSplit = func(groupID uint32) error { - return errors.Errorf("keyspace group %v is in split state", groupID) - } - // ErrKeyspaceGroupNotInSplit is used to indicate target keyspace group is not in split state. - ErrKeyspaceGroupNotInSplit = func(groupID uint32) error { - return errors.Errorf("keyspace group %v is not in split state", groupID) - } - // ErrKeyspaceGroupInMerging is used to indicate target keyspace group is in merging state. - ErrKeyspaceGroupInMerging = func(groupID uint32) error { - return errors.Errorf("keyspace group %v is in merging state", groupID) - } - // ErrKeyspaceGroupNotInMerging is used to indicate target keyspace group is not in merging state. - ErrKeyspaceGroupNotInMerging = func(groupID uint32) error { - return errors.Errorf("keyspace group %v is not in merging state", groupID) - } - // ErrKeyspaceNotInKeyspaceGroup is used to indicate target keyspace is not in this keyspace group. - ErrKeyspaceNotInKeyspaceGroup = errors.New("keyspace is not in this keyspace group") - // ErrKeyspaceNotInAnyKeyspaceGroup is used to indicate target keyspace is not in any keyspace group. - ErrKeyspaceNotInAnyKeyspaceGroup = errors.New("keyspace is not in any keyspace group") - // ErrNodeNotInKeyspaceGroup is used to indicate the tso node is not in this keyspace group. - ErrNodeNotInKeyspaceGroup = errors.New("the tso node is not in this keyspace group") - // ErrKeyspaceGroupNotEnoughReplicas is used to indicate not enough replicas in the keyspace group. - ErrKeyspaceGroupNotEnoughReplicas = errors.New("not enough replicas in the keyspace group") - // ErrKeyspaceGroupWithEmptyKeyspace is used to indicate keyspace group with empty keyspace. - ErrKeyspaceGroupWithEmptyKeyspace = errors.New("keyspace group with empty keyspace") - // ErrModifyDefaultKeyspaceGroup is used to indicate that default keyspace group cannot be modified. - ErrModifyDefaultKeyspaceGroup = errors.New("default keyspace group cannot be modified") - // ErrNoAvailableNode is used to indicate no available node in the keyspace group. - ErrNoAvailableNode = errors.New("no available node") - // ErrExceedMaxEtcdTxnOps is used to indicate the number of etcd txn operations exceeds the limit. - ErrExceedMaxEtcdTxnOps = errors.New("exceed max etcd txn operations") - // ErrModifyDefaultKeyspace is used to indicate that default keyspace cannot be modified. - ErrModifyDefaultKeyspace = errors.New("cannot modify default keyspace's state") - errIllegalOperation = errors.New("unknown operation") - - // ErrUnsupportedOperationInKeyspace is used to indicate this is an unsupported operation. - ErrUnsupportedOperationInKeyspace = errors.New("it's a unsupported operation") - // stateTransitionTable lists all allowed next state for the given current state. // Note that transit from any state to itself is allowed for idempotence. stateTransitionTable = map[keyspacepb.KeyspaceState][]keyspacepb.KeyspaceState{ @@ -102,9 +48,6 @@ var ( } // Only keyspaces in the state specified by allowChangeConfig are allowed to change their config. allowChangeConfig = []keyspacepb.KeyspaceState{keyspacepb.KeyspaceState_ENABLED, keyspacepb.KeyspaceState_DISABLED} - - // ErrKeyspaceGroupPrimaryNotFound is used to indicate primary of target keyspace group does not exist. - ErrKeyspaceGroupPrimaryNotFound = errors.New("primary of keyspace group does not exist") ) // validateID check if keyspace falls within the acceptable range. diff --git a/pkg/ratelimit/runner.go b/pkg/ratelimit/runner.go index 211a4f71be1..2a121d17c00 100644 --- a/pkg/ratelimit/runner.go +++ b/pkg/ratelimit/runner.go @@ -16,7 +16,6 @@ package ratelimit import ( "context" - "errors" "sync" "time" @@ -24,6 +23,8 @@ import ( "go.uber.org/zap" "github.com/pingcap/log" + + "github.com/tikv/pd/pkg/errs" ) // RegionHeartbeatStageName is the name of the stage of the region heartbeat. @@ -58,9 +59,6 @@ type Task struct { retained bool } -// ErrMaxWaitingTasksExceeded is returned when the number of waiting tasks exceeds the maximum. -var ErrMaxWaitingTasksExceeded = errors.New("max waiting tasks exceeded") - type taskID struct { id uint64 name string @@ -217,12 +215,12 @@ func (cr *ConcurrentRunner) RunTask(id uint64, name string, f func(context.Conte maxWait := time.Since(cr.pendingTasks[0].submittedAt) if maxWait > cr.maxPendingDuration { runnerFailedTasks.WithLabelValues(cr.name, task.name).Inc() - return ErrMaxWaitingTasksExceeded + return errs.ErrMaxWaitingTasksExceeded } } if pendingTaskNum > maxPendingTaskNum { runnerFailedTasks.WithLabelValues(cr.name, task.name).Inc() - return ErrMaxWaitingTasksExceeded + return errs.ErrMaxWaitingTasksExceeded } } cr.pendingTasks = append(cr.pendingTasks, task) diff --git a/pkg/schedule/checker/rule_checker.go b/pkg/schedule/checker/rule_checker.go index 28d5988ce1c..7350d92cf58 100644 --- a/pkg/schedule/checker/rule_checker.go +++ b/pkg/schedule/checker/rule_checker.go @@ -16,7 +16,6 @@ package checker import ( "context" - "errors" "math" "math/rand" "time" @@ -42,15 +41,6 @@ import ( const maxPendingListLen = 100000 -var ( - errNoStoreToAdd = errors.New("no store to add peer") - errNoStoreToReplace = errors.New("no store to replace peer") - errPeerCannotBeLeader = errors.New("peer cannot be leader") - errPeerCannotBeWitness = errors.New("peer cannot be witness") - errNoNewLeader = errors.New("no new leader") - errRegionNoLeader = errors.New("region no leader") -) - // RuleChecker fix/improve region by placement rules. type RuleChecker struct { PauseController @@ -103,7 +93,7 @@ func (c *RuleChecker) CheckWithFit(region *core.RegionInfo, fit *placement.Regio // skip no leader region if region.GetLeader() == nil { ruleCheckerRegionNoLeaderCounter.Inc() - log.Debug("fail to check region", zap.Uint64("region-id", region.GetID()), zap.Error(errRegionNoLeader)) + log.Debug("fail to check region", zap.Uint64("region-id", region.GetID()), errs.ZapError(errs.ErrRegionNoLeader)) return } @@ -230,7 +220,7 @@ func (c *RuleChecker) addRulePeer(region *core.RegionInfo, fit *placement.Region } } } - return nil, errNoStoreToAdd + return nil, errs.ErrNoStoreToAdd } peer := &metapb.Peer{StoreId: store, Role: rf.Rule.Role.MetaPeerRole(), IsWitness: isWitness} op, err := operator.CreateAddPeerOperator("add-rule-peer", c.cluster, region, peer, operator.OpReplica) @@ -262,7 +252,7 @@ func (c *RuleChecker) replaceUnexpectedRulePeer(region *core.RegionInfo, rf *pla if store == 0 { ruleCheckerNoStoreReplaceCounter.Inc() c.handleFilterState(region, filterByTempState) - return nil, errNoStoreToReplace + return nil, errs.ErrNoStoreToReplace } newPeer := &metapb.Peer{StoreId: store, Role: rf.Rule.Role.MetaPeerRole(), IsWitness: fastFailover} // pick the smallest leader store to avoid the Offline store be snapshot generator bottleneck. @@ -325,7 +315,7 @@ func (c *RuleChecker) fixLooseMatchPeer(region *core.RegionInfo, fit *placement. return operator.CreateTransferLeaderOperator("fix-leader-role", c.cluster, region, peer.GetStoreId(), []uint64{}, 0) } ruleCheckerNotAllowLeaderCounter.Inc() - return nil, errPeerCannotBeLeader + return nil, errs.ErrPeerCannotBeLeader } if region.GetLeader().GetId() == peer.GetId() && rf.Rule.Role == placement.Follower { ruleCheckerFixFollowerRoleCounter.Inc() @@ -335,14 +325,14 @@ func (c *RuleChecker) fixLooseMatchPeer(region *core.RegionInfo, fit *placement. } } ruleCheckerNoNewLeaderCounter.Inc() - return nil, errNoNewLeader + return nil, errs.ErrNoNewLeader } if core.IsVoter(peer) && rf.Rule.Role == placement.Learner { ruleCheckerDemoteVoterRoleCounter.Inc() return operator.CreateDemoteVoterOperator("fix-demote-voter", c.cluster, region, peer) } if region.GetLeader().GetId() == peer.GetId() && rf.Rule.IsWitness { - return nil, errPeerCannotBeWitness + return nil, errs.ErrPeerCannotBeWitness } if !core.IsWitness(peer) && rf.Rule.IsWitness && c.isWitnessEnabled() { c.switchWitnessCache.UpdateTTL(c.cluster.GetCheckerConfig().GetSwitchWitnessInterval()) diff --git a/pkg/schedule/scatter/region_scatterer.go b/pkg/schedule/scatter/region_scatterer.go index fdcbd705398..0e4dd43ecb2 100644 --- a/pkg/schedule/scatter/region_scatterer.go +++ b/pkg/schedule/scatter/region_scatterer.go @@ -55,8 +55,6 @@ var ( scatterUnnecessaryCounter = scatterCounter.WithLabelValues("unnecessary", "") scatterFailCounter = scatterCounter.WithLabelValues("fail", "") scatterSuccessCounter = scatterCounter.WithLabelValues("success", "") - errRegionNotFound = errors.New("region not found") - errEmptyRegion = errors.New("empty region") ) const ( @@ -169,7 +167,7 @@ func (r *RegionScatterer) ScatterRegionsByRange(startKey, endKey []byte, group s regions := r.cluster.ScanRegions(startKey, endKey, -1) if len(regions) < 1 { scatterSkipEmptyRegionCounter.Inc() - return 0, nil, errEmptyRegion + return 0, nil, errs.ErrEmptyRegion } failures := make(map[uint64]error, len(regions)) regionMap := make(map[uint64]*core.RegionInfo, len(regions)) @@ -188,13 +186,13 @@ func (r *RegionScatterer) ScatterRegionsByRange(startKey, endKey []byte, group s func (r *RegionScatterer) ScatterRegionsByID(regionsID []uint64, group string, retryLimit int, skipStoreLimit bool) (int, map[uint64]error, error) { if len(regionsID) < 1 { scatterSkipEmptyRegionCounter.Inc() - return 0, nil, errEmptyRegion + return 0, nil, errs.ErrEmptyRegion } if len(regionsID) == 1 { region := r.cluster.GetRegion(regionsID[0]) if region == nil { scatterSkipNoRegionCounter.Inc() - return 0, nil, errRegionNotFound + return 0, nil, errs.ErrRegionNotFound } } failures := make(map[uint64]error, len(regionsID)) @@ -230,7 +228,7 @@ func (r *RegionScatterer) ScatterRegionsByID(regionsID []uint64, group string, r func (r *RegionScatterer) scatterRegions(regions map[uint64]*core.RegionInfo, failures map[uint64]error, group string, retryLimit int, skipStoreLimit bool) (int, error) { if len(regions) < 1 { scatterSkipEmptyRegionCounter.Inc() - return 0, errEmptyRegion + return 0, errs.ErrEmptyRegion } if retryLimit > maxRetryLimit { retryLimit = maxRetryLimit diff --git a/server/apiv2/handlers/keyspace.go b/server/apiv2/handlers/keyspace.go index 0245016734c..969113bb17e 100644 --- a/server/apiv2/handlers/keyspace.go +++ b/server/apiv2/handlers/keyspace.go @@ -300,7 +300,7 @@ func UpdateKeyspaceConfig(c *gin.Context) { // Check if the update is supported. for _, mutation := range mutations { if mutation.Key == keyspace.GCManagementType && mutation.Value == keyspace.KeyspaceLevelGC { - err = keyspace.ErrUnsupportedOperationInKeyspace + err = errs.ErrUnsupportedOperationInKeyspace c.AbortWithStatusJSON(http.StatusInternalServerError, err.Error()) return } diff --git a/server/keyspace_service.go b/server/keyspace_service.go index e110742aa45..eeca31bc942 100644 --- a/server/keyspace_service.go +++ b/server/keyspace_service.go @@ -26,7 +26,7 @@ import ( "github.com/pingcap/kvproto/pkg/keyspacepb" "github.com/pingcap/kvproto/pkg/pdpb" - "github.com/tikv/pd/pkg/keyspace" + "github.com/tikv/pd/pkg/errs" "github.com/tikv/pd/pkg/utils/etcdutil" "github.com/tikv/pd/pkg/utils/keypath" ) @@ -39,9 +39,9 @@ type KeyspaceServer struct { // getErrorHeader returns corresponding ResponseHeader based on err. func getErrorHeader(err error) *pdpb.ResponseHeader { switch err { - case keyspace.ErrKeyspaceExists: + case errs.ErrKeyspaceExists: return wrapErrorToHeader(pdpb.ErrorType_DUPLICATED_ENTRY, err.Error()) - case keyspace.ErrKeyspaceNotFound: + case errs.ErrKeyspaceNotFound: return wrapErrorToHeader(pdpb.ErrorType_ENTRY_NOT_FOUND, err.Error()) default: return wrapErrorToHeader(pdpb.ErrorType_UNKNOWN, err.Error())