diff --git a/.golangci.yml b/.golangci.yml index 9843142b4ab..e8acff6fa55 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -12,6 +12,7 @@ linters: - gosec - bodyclose - testifylint + - gofmt disable: - errcheck linters-settings: @@ -41,3 +42,10 @@ linters-settings: - require-error - suite-dont-use-pkg - suite-extra-assert-call + gofmt: + # https://golangci-lint.run/usage/linters/#gofmt + # disable for faster check + simplify: false + rewrite-rules: + - pattern: 'interface{}' + replacement: 'any' diff --git a/Makefile b/Makefile index 7c31cb7d684..5d22d522d45 100644 --- a/Makefile +++ b/Makefile @@ -186,6 +186,11 @@ static: install-tools pre-build @ for mod in $(SUBMODULES); do cd $$mod && $(MAKE) static && cd $(ROOT_PATH) > /dev/null; done +# Because CI downloads the dashboard code and runs gofmt, we can't add this check into static now. +fmt: + @ echo "gofmt ..." + @ gofmt -s -l -w -r 'interface{} -> any' -d $(PACKAGE_DIRECTORIES) 2>&1 | awk '{ print } END { if (NR > 0) { exit 1 } }' + tidy: @ go mod tidy git diff go.mod go.sum | cat diff --git a/client/client.go b/client/client.go index 604adb3f578..ba7ac7fd075 100644 --- a/client/client.go +++ b/client/client.go @@ -134,7 +134,7 @@ type Client interface { // WatchGlobalConfig returns a stream with all global config and updates WatchGlobalConfig(ctx context.Context, configPath string, revision int64) (chan []GlobalConfigItem, error) // UpdateOption updates the client option. - UpdateOption(option DynamicOption, value interface{}) error + UpdateOption(option DynamicOption, value any) error // GetExternalTimestamp returns external timestamp GetExternalTimestamp(ctx context.Context) (uint64, error) @@ -691,7 +691,7 @@ func (c *client) GetServiceDiscovery() ServiceDiscovery { } // UpdateOption updates the client option. -func (c *client) UpdateOption(option DynamicOption, value interface{}) error { +func (c *client) UpdateOption(option DynamicOption, value any) error { switch option { case MaxTSOBatchWaitInterval: interval, ok := value.(time.Duration) diff --git a/client/http/client.go b/client/http/client.go index cb02d16d0ef..389c5ee5bef 100644 --- a/client/http/client.go +++ b/client/http/client.go @@ -47,7 +47,7 @@ const ( ) // respHandleFunc is the function to handle the HTTP response. -type respHandleFunc func(resp *http.Response, res interface{}) error +type respHandleFunc func(resp *http.Response, res any) error // clientInner is the inner implementation of the PD HTTP client, which contains some fundamental fields. // It is wrapped by the `client` struct to make sure the inner implementation won't be exposed and could @@ -328,7 +328,7 @@ func (c *client) WithCallerID(callerID string) Client { // WithRespHandler sets and returns a new client with the given HTTP response handler. func (c *client) WithRespHandler( - handler func(resp *http.Response, res interface{}) error, + handler func(resp *http.Response, res any) error, ) Client { newClient := *c newClient.respHandler = handler diff --git a/client/http/interface.go b/client/http/interface.go index 7510ea31fcf..c9b212f565f 100644 --- a/client/http/interface.go +++ b/client/http/interface.go @@ -50,14 +50,14 @@ type Client interface { GetStore(context.Context, uint64) (*StoreInfo, error) SetStoreLabels(context.Context, int64, map[string]string) error /* Config-related interfaces */ - GetConfig(context.Context) (map[string]interface{}, error) - SetConfig(context.Context, map[string]interface{}, ...float64) error - GetScheduleConfig(context.Context) (map[string]interface{}, error) - SetScheduleConfig(context.Context, map[string]interface{}) error + GetConfig(context.Context) (map[string]any, error) + SetConfig(context.Context, map[string]any, ...float64) error + GetScheduleConfig(context.Context) (map[string]any, error) + SetScheduleConfig(context.Context, map[string]any) error GetClusterVersion(context.Context) (string, error) GetCluster(context.Context) (*metapb.Cluster, error) GetClusterStatus(context.Context) (*ClusterState, error) - GetReplicateConfig(context.Context) (map[string]interface{}, error) + GetReplicateConfig(context.Context) (map[string]any, error) /* Scheduler-related interfaces */ GetSchedulers(context.Context) ([]string, error) CreateScheduler(ctx context.Context, name string, storeID uint64) error @@ -100,7 +100,7 @@ type Client interface { // This allows the caller to customize how the response is handled, including error handling logic. // Additionally, it is important for the caller to handle the content of the response body properly // in order to ensure that it can be read and marshaled correctly into `res`. - WithRespHandler(func(resp *http.Response, res interface{}) error) Client + WithRespHandler(func(resp *http.Response, res any) error) Client // WithBackoffer sets and returns a new client with the given backoffer. WithBackoffer(*retry.Backoffer) Client // Close gracefully closes the HTTP client. @@ -323,8 +323,8 @@ func (c *client) SetStoreLabels(ctx context.Context, storeID int64, storeLabels } // GetConfig gets the configurations. -func (c *client) GetConfig(ctx context.Context) (map[string]interface{}, error) { - var config map[string]interface{} +func (c *client) GetConfig(ctx context.Context) (map[string]any, error) { + var config map[string]any err := c.request(ctx, newRequestInfo(). WithName(getConfigName). WithURI(Config). @@ -337,7 +337,7 @@ func (c *client) GetConfig(ctx context.Context) (map[string]interface{}, error) } // SetConfig sets the configurations. ttlSecond is optional. -func (c *client) SetConfig(ctx context.Context, config map[string]interface{}, ttlSecond ...float64) error { +func (c *client) SetConfig(ctx context.Context, config map[string]any, ttlSecond ...float64) error { configJSON, err := json.Marshal(config) if err != nil { return errors.Trace(err) @@ -356,8 +356,8 @@ func (c *client) SetConfig(ctx context.Context, config map[string]interface{}, t } // GetScheduleConfig gets the schedule configurations. -func (c *client) GetScheduleConfig(ctx context.Context) (map[string]interface{}, error) { - var config map[string]interface{} +func (c *client) GetScheduleConfig(ctx context.Context) (map[string]any, error) { + var config map[string]any err := c.request(ctx, newRequestInfo(). WithName(getScheduleConfigName). WithURI(ScheduleConfig). @@ -370,7 +370,7 @@ func (c *client) GetScheduleConfig(ctx context.Context) (map[string]interface{}, } // SetScheduleConfig sets the schedule configurations. -func (c *client) SetScheduleConfig(ctx context.Context, config map[string]interface{}) error { +func (c *client) SetScheduleConfig(ctx context.Context, config map[string]any) error { configJSON, err := json.Marshal(config) if err != nil { return errors.Trace(err) @@ -453,8 +453,8 @@ func (c *client) GetClusterStatus(ctx context.Context) (*ClusterState, error) { } // GetReplicateConfig gets the replication configurations. -func (c *client) GetReplicateConfig(ctx context.Context) (map[string]interface{}, error) { - var config map[string]interface{} +func (c *client) GetReplicateConfig(ctx context.Context) (map[string]any, error) { + var config map[string]any err := c.request(ctx, newRequestInfo(). WithName(getReplicateConfigName). WithURI(ReplicateConfig). @@ -694,7 +694,7 @@ func (c *client) GetSchedulers(ctx context.Context) ([]string, error) { // CreateScheduler creates a scheduler to PD cluster. func (c *client) CreateScheduler(ctx context.Context, name string, storeID uint64) error { - inputJSON, err := json.Marshal(map[string]interface{}{ + inputJSON, err := json.Marshal(map[string]any{ "name": name, "store_id": storeID, }) diff --git a/client/http/request_info.go b/client/http/request_info.go index 404d1e657b5..132841ffb0b 100644 --- a/client/http/request_info.go +++ b/client/http/request_info.go @@ -83,7 +83,7 @@ type requestInfo struct { uri string method string body []byte - res interface{} + res any respHandler respHandleFunc bo *retry.Backoffer } @@ -124,7 +124,7 @@ func (ri *requestInfo) WithBody(body []byte) *requestInfo { } // WithResp sets the response struct of the request. -func (ri *requestInfo) WithResp(res interface{}) *requestInfo { +func (ri *requestInfo) WithResp(res any) *requestInfo { ri.res = res return ri } diff --git a/client/http/types.go b/client/http/types.go index 59f9077262b..aaf7e1c0027 100644 --- a/client/http/types.go +++ b/client/http/types.go @@ -575,7 +575,7 @@ type LabelRule struct { Index int `json:"index"` Labels []RegionLabel `json:"labels"` RuleType string `json:"rule_type"` - Data interface{} `json:"data"` + Data any `json:"data"` } // LabelRulePatch is the patch to update the label rules. diff --git a/client/pd_service_discovery.go b/client/pd_service_discovery.go index 0425f4d537c..bc446440215 100644 --- a/client/pd_service_discovery.go +++ b/client/pd_service_discovery.go @@ -662,7 +662,7 @@ func (c *pdServiceDiscovery) checkFollowerHealth(ctx context.Context) { func (c *pdServiceDiscovery) Close() { c.closeOnce.Do(func() { log.Info("[pd] close pd service discovery client") - c.clientConns.Range(func(key, cc interface{}) bool { + c.clientConns.Range(func(key, cc any) bool { if err := cc.(*grpc.ClientConn).Close(); err != nil { log.Error("[pd] failed to close grpc clientConn", errs.ZapError(errs.ErrCloseGRPCConn, err)) } diff --git a/client/tso_client.go b/client/tso_client.go index fc38ee8e5ba..465db1dbd5f 100644 --- a/client/tso_client.go +++ b/client/tso_client.go @@ -55,7 +55,7 @@ type tsoRequest struct { } var tsoReqPool = sync.Pool{ - New: func() interface{} { + New: func() any { return &tsoRequest{ done: make(chan error, 1), physical: 0, @@ -137,7 +137,7 @@ func (c *tsoClient) Close() { c.wg.Wait() log.Info("close tso client") - c.tsoDispatcher.Range(func(_, dispatcherInterface interface{}) bool { + c.tsoDispatcher.Range(func(_, dispatcherInterface any) bool { if dispatcherInterface != nil { dispatcher := dispatcherInterface.(*tsoDispatcher) tsoErr := errors.WithStack(errClosing) @@ -237,7 +237,7 @@ func (c *tsoClient) updateTSOGlobalServAddr(addr string) error { func (c *tsoClient) gcAllocatorServingAddr(curAllocatorMap map[string]string) { // Clean up the old TSO allocators - c.tsoAllocators.Range(func(dcLocationKey, _ interface{}) bool { + c.tsoAllocators.Range(func(dcLocationKey, _ any) bool { dcLocation := dcLocationKey.(string) // Skip the Global TSO Allocator if dcLocation == globalDCLocation { diff --git a/client/tso_dispatcher.go b/client/tso_dispatcher.go index 9510f7aadb6..cb4c243a56f 100644 --- a/client/tso_dispatcher.go +++ b/client/tso_dispatcher.go @@ -121,7 +121,7 @@ func (req *tsoRequest) Wait() (physical int64, logical int64, err error) { func (c *tsoClient) updateTSODispatcher() { // Set up the new TSO dispatcher and batch controller. - c.GetTSOAllocators().Range(func(dcLocationKey, _ interface{}) bool { + c.GetTSOAllocators().Range(func(dcLocationKey, _ any) bool { dcLocation := dcLocationKey.(string) if !c.checkTSODispatcher(dcLocation) { c.createTSODispatcher(dcLocation) @@ -129,7 +129,7 @@ func (c *tsoClient) updateTSODispatcher() { return true }) // Clean up the unused TSO dispatcher - c.tsoDispatcher.Range(func(dcLocationKey, dispatcher interface{}) bool { + c.tsoDispatcher.Range(func(dcLocationKey, dispatcher any) bool { dcLocation := dcLocationKey.(string) // Skip the Global TSO Allocator if dcLocation == globalDCLocation { @@ -173,7 +173,7 @@ func (c *tsoClient) tsCancelLoop() { defer ticker.Stop() for { // Watch every dc-location's tsDeadlineCh - c.GetTSOAllocators().Range(func(dcLocation, _ interface{}) bool { + c.GetTSOAllocators().Range(func(dcLocation, _ any) bool { c.watchTSDeadline(tsCancelLoopCtx, dcLocation.(string)) return true }) @@ -343,7 +343,7 @@ func (c *tsoClient) handleDispatcher( defer func() { log.Info("[tso] exit tso dispatcher", zap.String("dc-location", dc)) // Cancel all connections. - connectionCtxs.Range(func(_, cc interface{}) bool { + connectionCtxs.Range(func(_, cc any) bool { cc.(*tsoConnectionContext).cancel() return true }) @@ -532,7 +532,7 @@ func (c *tsoClient) allowTSOFollowerProxy(dc string) bool { // connectionCtxs will only have only one stream to choose when the TSO Follower Proxy is off. func (c *tsoClient) chooseStream(connectionCtxs *sync.Map) (connectionCtx *tsoConnectionContext) { idx := 0 - connectionCtxs.Range(func(_, cc interface{}) bool { + connectionCtxs.Range(func(_, cc any) bool { j := rand.Intn(idx + 1) if j < 1 { connectionCtx = cc.(*tsoConnectionContext) @@ -587,7 +587,7 @@ func (c *tsoClient) tryConnectToTSO( cc.(*tsoConnectionContext).cancel() connectionCtxs.Store(newAddr, connectionCtx) } - connectionCtxs.Range(func(addr, cc interface{}) bool { + connectionCtxs.Range(func(addr, cc any) bool { if addr.(string) != newAddr { cc.(*tsoConnectionContext).cancel() connectionCtxs.Delete(addr) @@ -700,7 +700,7 @@ func (c *tsoClient) tryConnectToTSOWithProxy(dispatcherCtx context.Context, dc s return errors.Errorf("cannot find the allocator leader in %s", dc) } // GC the stale one. - connectionCtxs.Range(func(addr, cc interface{}) bool { + connectionCtxs.Range(func(addr, cc any) bool { if _, ok := tsoStreamBuilders[addr.(string)]; !ok { cc.(*tsoConnectionContext).cancel() connectionCtxs.Delete(addr) diff --git a/client/tso_service_discovery.go b/client/tso_service_discovery.go index 3d7c0745f49..03638a1161c 100644 --- a/client/tso_service_discovery.go +++ b/client/tso_service_discovery.go @@ -231,7 +231,7 @@ func (c *tsoServiceDiscovery) Close() { c.cancel() c.wg.Wait() - c.clientConns.Range(func(key, cc interface{}) bool { + c.clientConns.Range(func(key, cc any) bool { if err := cc.(*grpc.ClientConn).Close(); err != nil { log.Error("[tso] failed to close gRPC clientConn", errs.ZapError(errs.ErrCloseGRPCConn, err)) } diff --git a/pkg/autoscaling/calculation_test.go b/pkg/autoscaling/calculation_test.go index 85f723b562c..05a348af59d 100644 --- a/pkg/autoscaling/calculation_test.go +++ b/pkg/autoscaling/calculation_test.go @@ -70,7 +70,7 @@ func TestGetScaledTiKVGroups(t *testing.T) { informer core.StoreSetInformer healthyInstances []instance expectedPlan []*Plan - errorChecker func(err error, msgAndArgs ...interface{}) + errorChecker func(err error, msgAndArgs ...any) }{ { name: "no scaled tikv group", diff --git a/pkg/autoscaling/prometheus_test.go b/pkg/autoscaling/prometheus_test.go index 2efdc348ead..b4cf9aefd91 100644 --- a/pkg/autoscaling/prometheus_test.go +++ b/pkg/autoscaling/prometheus_test.go @@ -86,8 +86,8 @@ type data struct { } type result struct { - Metric metric `json:"metric"` - Value []interface{} `json:"value"` + Metric metric `json:"metric"` + Value []any `json:"value"` } type metric struct { @@ -121,7 +121,7 @@ func (c *normalClient) buildCPUMockData(component ComponentType) { var results []result for i := 0; i < instanceCount; i++ { results = append(results, result{ - Value: []interface{}{time.Now().Unix(), fmt.Sprintf("%f", mockResultValue)}, + Value: []any{time.Now().Unix(), fmt.Sprintf("%f", mockResultValue)}, Metric: metric{ Instance: pods[i], Cluster: mockClusterName, diff --git a/pkg/btree/btree_generic_test.go b/pkg/btree/btree_generic_test.go index 751fb2744e9..9aa118fb8ad 100644 --- a/pkg/btree/btree_generic_test.go +++ b/pkg/btree/btree_generic_test.go @@ -82,7 +82,7 @@ func allrev[T Item[T]](t *BTreeG[T]) (out []T) { return } -func assertEq(t *testing.T, desc string, got, need interface{}) { +func assertEq(t *testing.T, desc string, got, need any) { if !reflect.DeepEqual(need, got) { t.Fatalf("%s failed: need %T %v, but got %T %v", desc, need, need, got, got) } diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go index eb1d314dd60..3aa7297201a 100644 --- a/pkg/cache/cache.go +++ b/pkg/cache/cache.go @@ -19,11 +19,11 @@ import "github.com/tikv/pd/pkg/utils/syncutil" // Cache is an interface for cache system type Cache interface { // Put puts an item into cache. - Put(key uint64, value interface{}) + Put(key uint64, value any) // Get retrieves an item from cache. - Get(key uint64) (interface{}, bool) + Get(key uint64) (any, bool) // Peek reads an item from cache. The action is no considered 'Use'. - Peek(key uint64) (interface{}, bool) + Peek(key uint64) (any, bool) // Remove eliminates an item from cache. Remove(key uint64) // Elems return all items in cache. @@ -59,7 +59,7 @@ func newThreadSafeCache(cache Cache) Cache { } // Put puts an item into cache. -func (c *threadSafeCache) Put(key uint64, value interface{}) { +func (c *threadSafeCache) Put(key uint64, value any) { c.lock.Lock() defer c.lock.Unlock() c.cache.Put(key, value) @@ -68,14 +68,14 @@ func (c *threadSafeCache) Put(key uint64, value interface{}) { // Get retrieves an item from cache. // When Get method called, LRU and TwoQueue cache will rearrange entries // so we must use write lock. -func (c *threadSafeCache) Get(key uint64) (interface{}, bool) { +func (c *threadSafeCache) Get(key uint64) (any, bool) { c.lock.Lock() defer c.lock.Unlock() return c.cache.Get(key) } // Peek reads an item from cache. The action is no considered 'Use'. -func (c *threadSafeCache) Peek(key uint64) (interface{}, bool) { +func (c *threadSafeCache) Peek(key uint64) (any, bool) { c.lock.RLock() defer c.lock.RUnlock() return c.cache.Peek(key) diff --git a/pkg/cache/cache_test.go b/pkg/cache/cache_test.go index 904da1afb62..dbef41d2754 100644 --- a/pkg/cache/cache_test.go +++ b/pkg/cache/cache_test.go @@ -238,7 +238,7 @@ func TestFifoFromLastSameElems(t *testing.T) { cache.Put(1, &testStruct{value: "3"}) fun := func() []*Item { return cache.FromLastSameElems( - func(i interface{}) (bool, string) { + func(i any) (bool, string) { result, ok := i.(*testStruct) if result == nil { return ok, "" diff --git a/pkg/cache/fifo.go b/pkg/cache/fifo.go index fc1b02ac0c9..03bc6631eab 100644 --- a/pkg/cache/fifo.go +++ b/pkg/cache/fifo.go @@ -40,7 +40,7 @@ func NewFIFO(maxCount int) *FIFO { } // Put puts an item into cache. -func (c *FIFO) Put(key uint64, value interface{}) { +func (c *FIFO) Put(key uint64, value any) { c.Lock() defer c.Unlock() @@ -90,12 +90,12 @@ func (c *FIFO) FromElems(key uint64) []*Item { } // FromLastSameElems returns continuous items that have the same comparable attribute with the the lastest one. -func (c *FIFO) FromLastSameElems(checkFunc func(interface{}) (bool, string)) []*Item { +func (c *FIFO) FromLastSameElems(checkFunc func(any) (bool, string)) []*Item { c.RLock() defer c.RUnlock() elems := make([]*Item, 0, c.ll.Len()) - var lastItem interface{} + var lastItem any for ele := c.ll.Front(); ele != nil; ele = ele.Next() { kv := ele.Value.(*Item) if lastItem == nil { diff --git a/pkg/cache/lru.go b/pkg/cache/lru.go index db750bbb9bd..66751b01eee 100644 --- a/pkg/cache/lru.go +++ b/pkg/cache/lru.go @@ -21,7 +21,7 @@ import ( // Item is the cache entry. type Item struct { Key uint64 - Value interface{} + Value any } // LRU is 'Least-Recently-Used' cache. @@ -45,7 +45,7 @@ func newLRU(maxCount int) *LRU { } // Put puts an item into cache. -func (c *LRU) Put(key uint64, value interface{}) { +func (c *LRU) Put(key uint64, value any) { if ele, ok := c.cache[key]; ok { c.ll.MoveToFront(ele) ele.Value.(*Item).Value = value @@ -61,7 +61,7 @@ func (c *LRU) Put(key uint64, value interface{}) { } // Get retrieves an item from cache. -func (c *LRU) Get(key uint64) (interface{}, bool) { +func (c *LRU) Get(key uint64) (any, bool) { if ele, ok := c.cache[key]; ok { c.ll.MoveToFront(ele) return ele.Value.(*Item).Value, true @@ -71,7 +71,7 @@ func (c *LRU) Get(key uint64) (interface{}, bool) { } // Peek reads an item from cache. The action is no considered 'Use'. -func (c *LRU) Peek(key uint64) (interface{}, bool) { +func (c *LRU) Peek(key uint64) (any, bool) { if ele, ok := c.cache[key]; ok { return ele.Value.(*Item).Value, true } @@ -104,7 +104,7 @@ func (c *LRU) removeOldest() { } } -func (c *LRU) getAndRemoveOldest() (uint64, interface{}, bool) { +func (c *LRU) getAndRemoveOldest() (uint64, any, bool) { ele := c.ll.Back() if ele != nil { c.removeElement(ele) diff --git a/pkg/cache/ttl.go b/pkg/cache/ttl.go index 14adf072dad..2aa39f6c6fd 100644 --- a/pkg/cache/ttl.go +++ b/pkg/cache/ttl.go @@ -25,7 +25,7 @@ import ( ) type ttlCacheItem struct { - value interface{} + value any expire time.Time } @@ -34,7 +34,7 @@ type ttlCache struct { syncutil.RWMutex ctx context.Context - items map[interface{}]ttlCacheItem + items map[any]ttlCacheItem ttl time.Duration gcInterval time.Duration } @@ -43,7 +43,7 @@ type ttlCache struct { func newTTL(ctx context.Context, gcInterval time.Duration, duration time.Duration) *ttlCache { c := &ttlCache{ ctx: ctx, - items: make(map[interface{}]ttlCacheItem), + items: make(map[any]ttlCacheItem), ttl: duration, gcInterval: gcInterval, } @@ -53,12 +53,12 @@ func newTTL(ctx context.Context, gcInterval time.Duration, duration time.Duratio } // Put puts an item into cache. -func (c *ttlCache) put(key interface{}, value interface{}) { +func (c *ttlCache) put(key any, value any) { c.putWithTTL(key, value, c.ttl) } // PutWithTTL puts an item into cache with specified TTL. -func (c *ttlCache) putWithTTL(key interface{}, value interface{}, ttl time.Duration) { +func (c *ttlCache) putWithTTL(key any, value any, ttl time.Duration) { c.Lock() defer c.Unlock() @@ -69,7 +69,7 @@ func (c *ttlCache) putWithTTL(key interface{}, value interface{}, ttl time.Durat } // Get retrieves an item from cache. -func (c *ttlCache) get(key interface{}) (interface{}, bool) { +func (c *ttlCache) get(key any) (any, bool) { c.RLock() defer c.RUnlock() @@ -86,11 +86,11 @@ func (c *ttlCache) get(key interface{}) (interface{}, bool) { } // GetKeys returns all keys that are not expired. -func (c *ttlCache) getKeys() []interface{} { +func (c *ttlCache) getKeys() []any { c.RLock() defer c.RUnlock() - var keys []interface{} + var keys []any now := time.Now() for key, item := range c.items { @@ -102,7 +102,7 @@ func (c *ttlCache) getKeys() []interface{} { } // Remove eliminates an item from cache. -func (c *ttlCache) remove(key interface{}) { +func (c *ttlCache) remove(key any) { c.Lock() defer c.Unlock() @@ -110,7 +110,7 @@ func (c *ttlCache) remove(key interface{}) { } // pop one key/value that is not expired. If boolean is false, it means that it didn't find the valid one. -func (c *ttlCache) pop() (interface{}, interface{}, bool) { +func (c *ttlCache) pop() (key, value any, exist bool) { c.Lock() defer c.Unlock() now := time.Now() @@ -199,12 +199,12 @@ func NewIDTTL(ctx context.Context, gcInterval, ttl time.Duration) *TTLUint64 { } // Get return the value by key id -func (c *TTLUint64) Get(id uint64) (interface{}, bool) { +func (c *TTLUint64) Get(id uint64) (any, bool) { return c.ttlCache.get(id) } // Put saves an ID in cache. -func (c *TTLUint64) Put(id uint64, value interface{}) { +func (c *TTLUint64) Put(id uint64, value any) { c.ttlCache.put(id, value) } @@ -233,7 +233,7 @@ func (c *TTLUint64) Remove(key uint64) { } // PutWithTTL puts an item into cache with specified TTL. -func (c *TTLUint64) PutWithTTL(key uint64, value interface{}, ttl time.Duration) { +func (c *TTLUint64) PutWithTTL(key uint64, value any, ttl time.Duration) { c.ttlCache.putWithTTL(key, value, ttl) } @@ -250,17 +250,17 @@ func NewStringTTL(ctx context.Context, gcInterval, ttl time.Duration) *TTLString } // Put put the string key with the value -func (c *TTLString) Put(key string, value interface{}) { +func (c *TTLString) Put(key string, value any) { c.ttlCache.put(key, value) } // PutWithTTL puts an item into cache with specified TTL. -func (c *TTLString) PutWithTTL(key string, value interface{}, ttl time.Duration) { +func (c *TTLString) PutWithTTL(key string, value any, ttl time.Duration) { c.ttlCache.putWithTTL(key, value, ttl) } // Pop one key/value that is not expired -func (c *TTLString) Pop() (string, interface{}, bool) { +func (c *TTLString) Pop() (string, any, bool) { k, v, success := c.ttlCache.pop() if !success { return "", nil, false @@ -273,7 +273,7 @@ func (c *TTLString) Pop() (string, interface{}, bool) { } // Get return the value by key id -func (c *TTLString) Get(id string) (interface{}, bool) { +func (c *TTLString) Get(id string) (any, bool) { return c.ttlCache.get(id) } diff --git a/pkg/cache/two_queue.go b/pkg/cache/two_queue.go index 0e41d855387..c2e0c4b32f7 100644 --- a/pkg/cache/two_queue.go +++ b/pkg/cache/two_queue.go @@ -62,7 +62,7 @@ func newTwoQueueParams(size int, recentRatio, ghostRatio float64) *TwoQueue { } // Put puts an item into cache. -func (c *TwoQueue) Put(key uint64, value interface{}) { +func (c *TwoQueue) Put(key uint64, value any) { // Check if value is in frequent list, // then just update it if c.frequent.contains(key) { @@ -111,7 +111,7 @@ func (c *TwoQueue) ensureSpace(ghost bool) { } // Get retrieves an item from cache. -func (c *TwoQueue) Get(key uint64) (interface{}, bool) { +func (c *TwoQueue) Get(key uint64) (any, bool) { // Check in frequent list if val, ok := c.frequent.Get(key); ok { return val, ok @@ -128,7 +128,7 @@ func (c *TwoQueue) Get(key uint64) (interface{}, bool) { } // Peek reads an item from cache. The action is no considered 'Use'. -func (c *TwoQueue) Peek(key uint64) (interface{}, bool) { +func (c *TwoQueue) Peek(key uint64) (any, bool) { if val, ok := c.frequent.Peek(key); ok { return val, ok } diff --git a/pkg/keyspace/util.go b/pkg/keyspace/util.go index e3586ee35d4..a3d9f6345e3 100644 --- a/pkg/keyspace/util.go +++ b/pkg/keyspace/util.go @@ -176,14 +176,14 @@ func MakeRegionBound(id uint32) *RegionBound { } // MakeKeyRanges encodes keyspace ID to correct LabelRule data. -func MakeKeyRanges(id uint32) []interface{} { +func MakeKeyRanges(id uint32) []any { regionBound := MakeRegionBound(id) - return []interface{}{ - map[string]interface{}{ + return []any{ + map[string]any{ "start_key": hex.EncodeToString(regionBound.RawLeftBound), "end_key": hex.EncodeToString(regionBound.RawRightBound), }, - map[string]interface{}{ + map[string]any{ "start_key": hex.EncodeToString(regionBound.TxnLeftBound), "end_key": hex.EncodeToString(regionBound.TxnRightBound), }, @@ -246,14 +246,14 @@ func (hp *indexedHeap) Swap(i, j int) { } // Implementing heap.Interface. -func (hp *indexedHeap) Push(x interface{}) { +func (hp *indexedHeap) Push(x any) { item := x.(*endpoint.KeyspaceGroup) hp.index[item.ID] = hp.Len() hp.items = append(hp.items, item) } // Implementing heap.Interface. -func (hp *indexedHeap) Pop() interface{} { +func (hp *indexedHeap) Pop() any { l := hp.Len() item := hp.items[l-1] hp.items = hp.items[:l-1] diff --git a/pkg/keyspace/util_test.go b/pkg/keyspace/util_test.go index 3f9396d6989..48500fcd535 100644 --- a/pkg/keyspace/util_test.go +++ b/pkg/keyspace/util_test.go @@ -83,12 +83,12 @@ func TestMakeLabelRule(t *testing.T) { }, }, RuleType: "key-range", - Data: []interface{}{ - map[string]interface{}{ + Data: []any{ + map[string]any{ "start_key": hex.EncodeToString(codec.EncodeBytes([]byte{'r', 0, 0, 0})), "end_key": hex.EncodeToString(codec.EncodeBytes([]byte{'r', 0, 0, 1})), }, - map[string]interface{}{ + map[string]any{ "start_key": hex.EncodeToString(codec.EncodeBytes([]byte{'x', 0, 0, 0})), "end_key": hex.EncodeToString(codec.EncodeBytes([]byte{'x', 0, 0, 1})), }, @@ -107,12 +107,12 @@ func TestMakeLabelRule(t *testing.T) { }, }, RuleType: "key-range", - Data: []interface{}{ - map[string]interface{}{ + Data: []any{ + map[string]any{ "start_key": hex.EncodeToString(codec.EncodeBytes([]byte{'r', 0, 0x10, 0x92})), "end_key": hex.EncodeToString(codec.EncodeBytes([]byte{'r', 0, 0x10, 0x93})), }, - map[string]interface{}{ + map[string]any{ "start_key": hex.EncodeToString(codec.EncodeBytes([]byte{'x', 0, 0x10, 0x92})), "end_key": hex.EncodeToString(codec.EncodeBytes([]byte{'x', 0, 0x10, 0x93})), }, diff --git a/pkg/mcs/resourcemanager/server/apis/v1/api.go b/pkg/mcs/resourcemanager/server/apis/v1/api.go index fee648a5595..0c6b35cc06f 100644 --- a/pkg/mcs/resourcemanager/server/apis/v1/api.go +++ b/pkg/mcs/resourcemanager/server/apis/v1/api.go @@ -249,7 +249,7 @@ func (s *Service) getControllerConfig(c *gin.Context) { // @Failure 400 {string} error // @Router /config/controller [POST] func (s *Service) setControllerConfig(c *gin.Context) { - conf := make(map[string]interface{}) + conf := make(map[string]any) if err := c.ShouldBindJSON(&conf); err != nil { c.String(http.StatusBadRequest, err.Error()) return diff --git a/pkg/mcs/resourcemanager/server/manager.go b/pkg/mcs/resourcemanager/server/manager.go index 61c1463d3c0..ea67bb847ef 100644 --- a/pkg/mcs/resourcemanager/server/manager.go +++ b/pkg/mcs/resourcemanager/server/manager.go @@ -184,13 +184,13 @@ func (m *Manager) Init(ctx context.Context) error { } // UpdateControllerConfigItem updates the controller config item. -func (m *Manager) UpdateControllerConfigItem(key string, value interface{}) error { +func (m *Manager) UpdateControllerConfigItem(key string, value any) error { kp := strings.Split(key, ".") if len(kp) == 0 { return errors.Errorf("invalid key %s", key) } m.Lock() - var config interface{} + var config any switch kp[0] { case "request-unit": config = &m.controllerConfig.RequestUnit diff --git a/pkg/mcs/resourcemanager/server/resource_group_test.go b/pkg/mcs/resourcemanager/server/resource_group_test.go index da5f5c4f0e4..87ff6da2632 100644 --- a/pkg/mcs/resourcemanager/server/resource_group_test.go +++ b/pkg/mcs/resourcemanager/server/resource_group_test.go @@ -37,7 +37,7 @@ func TestPatchResourceGroup(t *testing.T) { } } -func resetSizeCache(obj interface{}) { +func resetSizeCache(obj any) { resetSizeCacheRecursive(reflect.ValueOf(obj)) } diff --git a/pkg/mcs/scheduling/server/apis/v1/api.go b/pkg/mcs/scheduling/server/apis/v1/api.go index d6dc8bb5987..5e8d1244867 100644 --- a/pkg/mcs/scheduling/server/apis/v1/api.go +++ b/pkg/mcs/scheduling/server/apis/v1/api.go @@ -434,7 +434,7 @@ func getOperatorRecords(c *gin.Context) { // @Router /operators [post] func createOperator(c *gin.Context) { handler := c.MustGet(handlerKey).(*handler.Handler) - var input map[string]interface{} + var input map[string]any if err := c.BindJSON(&input); err != nil { c.String(http.StatusBadRequest, err.Error()) return @@ -530,7 +530,7 @@ func getSchedulers(c *gin.Context) { // @Tags schedulers // @Summary List all scheduler configs. // @Produce json -// @Success 200 {object} map[string]interface{} +// @Success 200 {object} map[string]any // @Failure 500 {string} string "PD server failed to proceed the request." // @Router /schedulers/config/ [get] func getSchedulerConfig(c *gin.Context) { @@ -551,7 +551,7 @@ func getSchedulerConfig(c *gin.Context) { // @Tags schedulers // @Summary List scheduler config by name. // @Produce json -// @Success 200 {object} map[string]interface{} +// @Success 200 {object} map[string]any // @Failure 404 {string} string scheduler not found // @Failure 500 {string} string "PD server failed to proceed the request." // @Router /schedulers/config/{name}/list [get] @@ -1171,7 +1171,7 @@ func getRegionLabelRuleByID(c *gin.Context) { func accelerateRegionsScheduleInRange(c *gin.Context) { handler := c.MustGet(handlerKey).(*handler.Handler) - var input map[string]interface{} + var input map[string]any if err := c.BindJSON(&input); err != nil { c.String(http.StatusBadRequest, err.Error()) return @@ -1211,7 +1211,7 @@ func accelerateRegionsScheduleInRange(c *gin.Context) { func accelerateRegionsScheduleInRanges(c *gin.Context) { handler := c.MustGet(handlerKey).(*handler.Handler) - var input []map[string]interface{} + var input []map[string]any if err := c.BindJSON(&input); err != nil { c.String(http.StatusBadRequest, err.Error()) return @@ -1262,7 +1262,7 @@ func accelerateRegionsScheduleInRanges(c *gin.Context) { func scatterRegions(c *gin.Context) { handler := c.MustGet(handlerKey).(*handler.Handler) - var input map[string]interface{} + var input map[string]any if err := c.BindJSON(&input); err != nil { c.String(http.StatusBadRequest, err.Error()) return @@ -1305,7 +1305,7 @@ func scatterRegions(c *gin.Context) { func splitRegions(c *gin.Context) { handler := c.MustGet(handlerKey).(*handler.Handler) - var input map[string]interface{} + var input map[string]any if err := c.BindJSON(&input); err != nil { c.String(http.StatusBadRequest, err.Error()) return @@ -1315,7 +1315,7 @@ func splitRegions(c *gin.Context) { c.String(http.StatusBadRequest, "split_keys should be provided.") return } - rawSplitKeys := s.([]interface{}) + rawSplitKeys := s.([]any) if len(rawSplitKeys) < 1 { c.String(http.StatusBadRequest, "empty split keys.") return diff --git a/pkg/mcs/scheduling/server/grpc_service.go b/pkg/mcs/scheduling/server/grpc_service.go index b865e917d75..cda8faf9f44 100644 --- a/pkg/mcs/scheduling/server/grpc_service.go +++ b/pkg/mcs/scheduling/server/grpc_service.go @@ -58,7 +58,7 @@ func (d dummyRestService) ServeHTTP(w http.ResponseWriter, r *http.Request) { // ConfigProvider is used to get scheduling config from the given // `bs.server` without modifying its interface. -type ConfigProvider interface{} +type ConfigProvider any // Service is the scheduling grpc service. type Service struct { diff --git a/pkg/mcs/tso/server/grpc_service.go b/pkg/mcs/tso/server/grpc_service.go index 9006faf49da..31a74f2a688 100644 --- a/pkg/mcs/tso/server/grpc_service.go +++ b/pkg/mcs/tso/server/grpc_service.go @@ -55,7 +55,7 @@ func (d dummyRestService) ServeHTTP(w http.ResponseWriter, r *http.Request) { // ConfigProvider is used to get tso config from the given // `bs.server` without modifying its interface. -type ConfigProvider interface{} +type ConfigProvider any // Service is the TSO grpc service. type Service struct { diff --git a/pkg/member/member.go b/pkg/member/member.go index 8d0eb978c50..1bdc737bfdb 100644 --- a/pkg/member/member.go +++ b/pkg/member/member.go @@ -85,7 +85,7 @@ func (m *EmbeddedEtcdMember) Name() string { } // GetMember returns the member. -func (m *EmbeddedEtcdMember) GetMember() interface{} { +func (m *EmbeddedEtcdMember) GetMember() any { return m.member } diff --git a/pkg/member/participant.go b/pkg/member/participant.go index 189da7b96c9..0bf3bcc547e 100644 --- a/pkg/member/participant.go +++ b/pkg/member/participant.go @@ -104,7 +104,7 @@ func (m *Participant) Name() string { } // GetMember returns the member. -func (m *Participant) GetMember() interface{} { +func (m *Participant) GetMember() any { return m.member } diff --git a/pkg/response/region_test.go b/pkg/response/region_test.go index fb29e7dbe21..de6daa2c2fe 100644 --- a/pkg/response/region_test.go +++ b/pkg/response/region_test.go @@ -32,7 +32,7 @@ func TestPeer(t *testing.T) { {Id: 4, StoreId: 40, Role: metapb.PeerRole_DemotingVoter}, } // float64 is the default numeric type for JSON - expected := []map[string]interface{}{ + expected := []map[string]any{ {"id": float64(1), "store_id": float64(10), "role_name": "Voter"}, {"id": float64(2), "store_id": float64(20), "role": float64(1), "role_name": "Learner", "is_learner": true}, {"id": float64(3), "store_id": float64(30), "role": float64(2), "role_name": "IncomingVoter"}, @@ -41,7 +41,7 @@ func TestPeer(t *testing.T) { data, err := json.Marshal(fromPeerSlice(peers)) re.NoError(err) - var ret []map[string]interface{} + var ret []map[string]any re.NoError(json.Unmarshal(data, &ret)) re.Equal(expected, ret) } @@ -55,16 +55,16 @@ func TestPeerStats(t *testing.T) { {Peer: &metapb.Peer{Id: 4, StoreId: 40, Role: metapb.PeerRole_DemotingVoter}, DownSeconds: 3}, } // float64 is the default numeric type for JSON - expected := []map[string]interface{}{ - {"peer": map[string]interface{}{"id": float64(1), "store_id": float64(10), "role_name": "Voter"}}, - {"peer": map[string]interface{}{"id": float64(2), "store_id": float64(20), "role": float64(1), "role_name": "Learner", "is_learner": true}, "down_seconds": float64(1)}, - {"peer": map[string]interface{}{"id": float64(3), "store_id": float64(30), "role": float64(2), "role_name": "IncomingVoter"}, "down_seconds": float64(2)}, - {"peer": map[string]interface{}{"id": float64(4), "store_id": float64(40), "role": float64(3), "role_name": "DemotingVoter"}, "down_seconds": float64(3)}, + expected := []map[string]any{ + {"peer": map[string]any{"id": float64(1), "store_id": float64(10), "role_name": "Voter"}}, + {"peer": map[string]any{"id": float64(2), "store_id": float64(20), "role": float64(1), "role_name": "Learner", "is_learner": true}, "down_seconds": float64(1)}, + {"peer": map[string]any{"id": float64(3), "store_id": float64(30), "role": float64(2), "role_name": "IncomingVoter"}, "down_seconds": float64(2)}, + {"peer": map[string]any{"id": float64(4), "store_id": float64(40), "role": float64(3), "role_name": "DemotingVoter"}, "down_seconds": float64(3)}, } data, err := json.Marshal(fromPeerStatsSlice(peers)) re.NoError(err) - var ret []map[string]interface{} + var ret []map[string]any re.NoError(json.Unmarshal(data, &ret)) re.Equal(expected, ret) } diff --git a/pkg/schedule/checker/merge_checker_test.go b/pkg/schedule/checker/merge_checker_test.go index 40466d33947..06e8d468de3 100644 --- a/pkg/schedule/checker/merge_checker_test.go +++ b/pkg/schedule/checker/merge_checker_test.go @@ -544,10 +544,10 @@ func (suite *mergeCheckerTestSuite) TestCache() { re.NotNil(ops) } -func makeKeyRanges(keys ...string) []interface{} { - var res []interface{} +func makeKeyRanges(keys ...string) []any { + var res []any for i := 0; i < len(keys); i += 2 { - res = append(res, map[string]interface{}{"start_key": keys[i], "end_key": keys[i+1]}) + res = append(res, map[string]any{"start_key": keys[i], "end_key": keys[i+1]}) } return res } diff --git a/pkg/schedule/config/config.go b/pkg/schedule/config/config.go index 8411a84bb1b..528f3a611c9 100644 --- a/pkg/schedule/config/config.go +++ b/pkg/schedule/config/config.go @@ -267,7 +267,7 @@ type ScheduleConfig struct { Schedulers SchedulerConfigs `toml:"schedulers" json:"schedulers-v2"` // json v2 is for the sake of compatible upgrade // Only used to display - SchedulersPayload map[string]interface{} `toml:"schedulers-payload" json:"schedulers-payload"` + SchedulersPayload map[string]any `toml:"schedulers-payload" json:"schedulers-payload"` // Controls the time interval between write hot regions info into leveldb. HotRegionsWriteInterval typeutil.Duration `toml:"hot-regions-write-interval" json:"hot-regions-write-interval"` diff --git a/pkg/schedule/handler/handler.go b/pkg/schedule/handler/handler.go index 346a7254284..017289c81af 100644 --- a/pkg/schedule/handler/handler.go +++ b/pkg/schedule/handler/handler.go @@ -229,7 +229,7 @@ func (h *Handler) GetRecords(from time.Time) ([]*operator.OpRecord, error) { // HandleOperatorCreation processes the request and creates an operator based on the provided input. // It supports various types of operators such as transfer-leader, transfer-region, add-peer, remove-peer, merge-region, split-region, scatter-region, and scatter-regions. // The function validates the input, performs the corresponding operation, and returns the HTTP status code, response body, and any error encountered during the process. -func (h *Handler) HandleOperatorCreation(input map[string]interface{}) (int, interface{}, error) { +func (h *Handler) HandleOperatorCreation(input map[string]any) (int, any, error) { name, ok := input["name"].(string) if !ok { return http.StatusBadRequest, nil, errors.Errorf("missing operator name") @@ -337,7 +337,7 @@ func (h *Handler) HandleOperatorCreation(input map[string]interface{}) (int, int } var keys []string if ks, ok := input["keys"]; ok { - for _, k := range ks.([]interface{}) { + for _, k := range ks.([]any) { key, ok := k.(string) if !ok { return http.StatusBadRequest, nil, errors.Errorf("bad format keys") @@ -729,8 +729,8 @@ func checkStoreState(c sche.SharedCluster, storeID uint64) error { return nil } -func parseStoreIDsAndPeerRole(ids interface{}, roles interface{}) (map[uint64]placement.PeerRoleType, bool) { - items, ok := ids.([]interface{}) +func parseStoreIDsAndPeerRole(ids any, roles any) (map[uint64]placement.PeerRoleType, bool) { + items, ok := ids.([]any) if !ok { return nil, false } @@ -745,7 +745,7 @@ func parseStoreIDsAndPeerRole(ids interface{}, roles interface{}) (map[uint64]pl storeIDToPeerRole[uint64(id)] = "" } - peerRoles, ok := roles.([]interface{}) + peerRoles, ok := roles.([]any) // only consider roles having the same length with ids as the valid case if ok && len(peerRoles) == len(storeIDs) { for i, v := range storeIDs { @@ -799,7 +799,7 @@ type schedulerPausedPeriod struct { } // GetSchedulerByStatus returns all names of schedulers by status. -func (h *Handler) GetSchedulerByStatus(status string, needTS bool) (interface{}, error) { +func (h *Handler) GetSchedulerByStatus(status string, needTS bool) (any, error) { sc, err := h.GetSchedulersController() if err != nil { return nil, err @@ -1221,7 +1221,7 @@ type SplitRegionsResponse struct { } // SplitRegions splits regions by split keys. -func (h *Handler) SplitRegions(ctx context.Context, rawSplitKeys []interface{}, retryLimit int) (*SplitRegionsResponse, error) { +func (h *Handler) SplitRegions(ctx context.Context, rawSplitKeys []any, retryLimit int) (*SplitRegionsResponse, error) { co := h.GetCoordinator() if co == nil { return nil, errs.ErrNotBootstrapped.GenWithStackByArgs() diff --git a/pkg/schedule/labeler/labeler.go b/pkg/schedule/labeler/labeler.go index aeb4ff7b2f9..2b2bf8abda7 100644 --- a/pkg/schedule/labeler/labeler.go +++ b/pkg/schedule/labeler/labeler.go @@ -382,10 +382,10 @@ func (l *RegionLabeler) GetRegionLabels(region *core.RegionInfo) []*RegionLabel } // MakeKeyRanges is a helper function to make key ranges. -func MakeKeyRanges(keys ...string) []interface{} { - var res []interface{} +func MakeKeyRanges(keys ...string) []any { + var res []any for i := 0; i < len(keys); i += 2 { - res = append(res, map[string]interface{}{"start_key": keys[i], "end_key": keys[i+1]}) + res = append(res, map[string]any{"start_key": keys[i], "end_key": keys[i+1]}) } return res } diff --git a/pkg/schedule/labeler/rules.go b/pkg/schedule/labeler/rules.go index 5726a9f904e..3462cb7c459 100644 --- a/pkg/schedule/labeler/rules.go +++ b/pkg/schedule/labeler/rules.go @@ -45,7 +45,7 @@ type LabelRule struct { Index int `json:"index"` Labels []RegionLabel `json:"labels"` RuleType string `json:"rule_type"` - Data interface{} `json:"data"` + Data any `json:"data"` minExpire *time.Time } @@ -183,8 +183,8 @@ func (rule *LabelRule) expireBefore(t time.Time) bool { } // initKeyRangeRulesFromLabelRuleData init and adjust []KeyRangeRule from `LabelRule.Data` -func initKeyRangeRulesFromLabelRuleData(data interface{}) ([]*KeyRangeRule, error) { - rules, ok := data.([]interface{}) +func initKeyRangeRulesFromLabelRuleData(data any) ([]*KeyRangeRule, error) { + rules, ok := data.([]any) if !ok { return nil, errs.ErrRegionRuleContent.FastGenByArgs(fmt.Sprintf("invalid rule type: %T", data)) } @@ -203,8 +203,8 @@ func initKeyRangeRulesFromLabelRuleData(data interface{}) ([]*KeyRangeRule, erro } // initAndAdjustKeyRangeRule inits and adjusts the KeyRangeRule from one item in `LabelRule.Data` -func initAndAdjustKeyRangeRule(rule interface{}) (*KeyRangeRule, error) { - data, ok := rule.(map[string]interface{}) +func initAndAdjustKeyRangeRule(rule any) (*KeyRangeRule, error) { + data, ok := rule.(map[string]any) if !ok { return nil, errs.ErrRegionRuleContent.FastGenByArgs(fmt.Sprintf("invalid rule type: %T", reflect.TypeOf(rule))) } diff --git a/pkg/schedule/operator/operator_controller_test.go b/pkg/schedule/operator/operator_controller_test.go index e47281a2c68..6369dea897c 100644 --- a/pkg/schedule/operator/operator_controller_test.go +++ b/pkg/schedule/operator/operator_controller_test.go @@ -803,7 +803,7 @@ func (suite *operatorControllerTestSuite) TestAddWaitingOperator() { ID: "schedulelabel", Labels: []labeler.RegionLabel{{Key: "schedule", Value: "deny"}}, RuleType: labeler.KeyRange, - Data: []interface{}{map[string]interface{}{"start_key": "1a", "end_key": "1b"}}, + Data: []any{map[string]any{"start_key": "1a", "end_key": "1b"}}, }) re.True(labelerManager.ScheduleDisabled(source)) diff --git a/pkg/schedule/operator/operator_queue.go b/pkg/schedule/operator/operator_queue.go index 7765427793f..0e7f34ecc51 100644 --- a/pkg/schedule/operator/operator_queue.go +++ b/pkg/schedule/operator/operator_queue.go @@ -35,12 +35,12 @@ func (opn operatorQueue) Swap(i, j int) { opn[i], opn[j] = opn[j], opn[i] } -func (opn *operatorQueue) Push(x interface{}) { +func (opn *operatorQueue) Push(x any) { item := x.(*operatorWithTime) *opn = append(*opn, item) } -func (opn *operatorQueue) Pop() interface{} { +func (opn *operatorQueue) Pop() any { old := *opn n := len(old) if n == 0 { diff --git a/pkg/schedule/operator/step_test.go b/pkg/schedule/operator/step_test.go index f362d988f89..014703d00f9 100644 --- a/pkg/schedule/operator/step_test.go +++ b/pkg/schedule/operator/step_test.go @@ -40,7 +40,7 @@ type testCase struct { Peers []*metapb.Peer // first is leader ConfVerChanged uint64 IsFinish bool - CheckInProgress func(err error, msgAndArgs ...interface{}) + CheckInProgress func(err error, msgAndArgs ...any) } func (suite *operatorStepTestSuite) SetupTest() { diff --git a/pkg/schedule/placement/config.go b/pkg/schedule/placement/config.go index 00c0f94b94e..53cb0636536 100644 --- a/pkg/schedule/placement/config.go +++ b/pkg/schedule/placement/config.go @@ -180,7 +180,7 @@ func (p *RuleConfigPatch) commit() { p.c.adjust() } -func jsonEquals(a, b interface{}) bool { +func jsonEquals(a, b any) bool { aa, _ := json.Marshal(a) bb, _ := json.Marshal(b) return bytes.Equal(aa, bb) diff --git a/pkg/schedule/placement/fit_test.go b/pkg/schedule/placement/fit_test.go index 286dbcdacd5..f3c1fe53058 100644 --- a/pkg/schedule/placement/fit_test.go +++ b/pkg/schedule/placement/fit_test.go @@ -215,7 +215,7 @@ func TestIsolationScore(t *testing.T) { as := assert.New(t) stores := makeStores() testCases := []struct { - checker func(interface{}, interface{}, ...interface{}) bool + checker func(any, any, ...any) bool peers1 []uint64 peers2 []uint64 }{ diff --git a/pkg/schedule/placement/rule_list.go b/pkg/schedule/placement/rule_list.go index 9c43bb91627..73b2f5271a1 100644 --- a/pkg/schedule/placement/rule_list.go +++ b/pkg/schedule/placement/rule_list.go @@ -66,7 +66,7 @@ type ruleContainer interface { // rules indicates the map (rule's GroupID, ID) => rule func buildRuleList(rules ruleContainer) (ruleList, error) { builder := rangelist.NewBuilder() - builder.SetCompareFunc(func(a, b interface{}) int { + builder.SetCompareFunc(func(a, b any) int { return compareRule(a.(*Rule), b.(*Rule)) }) rules.iterateRules(func(r *Rule) { diff --git a/pkg/schedule/plan/balance_plan.go b/pkg/schedule/plan/balance_plan.go index 819a00f94e7..57396ffc80d 100644 --- a/pkg/schedule/plan/balance_plan.go +++ b/pkg/schedule/plan/balance_plan.go @@ -51,7 +51,7 @@ func (p *BalanceSchedulerPlan) GetStep() int { } // SetResource is used to set resource for current step. -func (p *BalanceSchedulerPlan) SetResource(resource interface{}) { +func (p *BalanceSchedulerPlan) SetResource(resource any) { switch p.Step { // for balance-region/leader scheduler, the first step is selecting stores as source candidates. case pickSource: @@ -66,7 +66,7 @@ func (p *BalanceSchedulerPlan) SetResource(resource interface{}) { } // SetResourceWithStep is used to set resource for specific step. -func (p *BalanceSchedulerPlan) SetResourceWithStep(resource interface{}, step int) { +func (p *BalanceSchedulerPlan) SetResourceWithStep(resource any, step int) { p.Step = step p.SetResource(resource) } diff --git a/pkg/schedule/plan/plan.go b/pkg/schedule/plan/plan.go index fcd5102012c..8a389b9b9e8 100644 --- a/pkg/schedule/plan/plan.go +++ b/pkg/schedule/plan/plan.go @@ -22,11 +22,11 @@ type Plan interface { GetResource(int) uint64 Clone(ops ...Option) Plan // generate plan for clone option - SetResource(interface{}) + SetResource(any) // SetResourceWithStep is used to set resource for specific step. // The meaning of step is different for different plans. // Such as balancePlan, pickSource = 0, pickRegion = 1, pickTarget = 2 - SetResourceWithStep(resource interface{}, step int) + SetResourceWithStep(resource any, step int) SetStatus(*Status) } @@ -82,14 +82,14 @@ func SetStatus(status *Status) Option { } // SetResource is used to generate Resource for plan -func SetResource(resource interface{}) Option { +func SetResource(resource any) Option { return func(plan Plan) { plan.SetResource(resource) } } // SetResourceWithStep is used to generate Resource for plan -func SetResourceWithStep(resource interface{}, step int) Option { +func SetResourceWithStep(resource any, step int) Option { return func(plan Plan) { plan.SetResourceWithStep(resource, step) } diff --git a/pkg/schedule/rangelist/builder.go b/pkg/schedule/rangelist/builder.go index 92977d698e0..cb178585cb6 100644 --- a/pkg/schedule/rangelist/builder.go +++ b/pkg/schedule/rangelist/builder.go @@ -30,7 +30,7 @@ const ( type splitPoint struct { ty splitPointType key []byte - data interface{} + data any } // Builder is used to create key range list. @@ -45,12 +45,12 @@ func NewBuilder() *Builder { } // SetCompareFunc sets up the comparer to determine item order (ascending) for a key range. -func (b *Builder) SetCompareFunc(f func(a, b interface{}) int) { +func (b *Builder) SetCompareFunc(f func(a, b any) int) { b.compare = f } // AddItem pushes an item to key range list. -func (b *Builder) AddItem(start, end []byte, data interface{}) { +func (b *Builder) AddItem(start, end []byte, data any) { b.splitPoints = append(b.splitPoints, splitPoint{ty: tStart, key: start, data: data}) if len(end) > 0 { b.splitPoints = append(b.splitPoints, splitPoint{ty: tEnd, key: end, data: data}) @@ -59,10 +59,10 @@ func (b *Builder) AddItem(start, end []byte, data interface{}) { // An item slice that keeps items in ascending order. type sortedItems struct { - items []interface{} + items []any } -func (si *sortedItems) insertItem(item interface{}, comparer compareFunc) { +func (si *sortedItems) insertItem(item any, comparer compareFunc) { pos := len(si.items) if comparer != nil { pos = sort.Search(len(si.items), func(i int) bool { @@ -77,7 +77,7 @@ func (si *sortedItems) insertItem(item interface{}, comparer compareFunc) { si.items[pos] = item } -func (si *sortedItems) deleteItem(del interface{}) { +func (si *sortedItems) deleteItem(del any) { for i, item := range si.items { if item == del { si.items = append(si.items[:i], si.items[i+1:]...) diff --git a/pkg/schedule/rangelist/range_list.go b/pkg/schedule/rangelist/range_list.go index dce7d756f79..45e179520f3 100644 --- a/pkg/schedule/rangelist/range_list.go +++ b/pkg/schedule/rangelist/range_list.go @@ -19,11 +19,11 @@ import ( "sort" ) -type compareFunc func(a, b interface{}) int +type compareFunc func(a, b any) int type segment struct { startKey []byte - data []interface{} + data []any } // List manages a list of key ranges. @@ -37,12 +37,12 @@ func (l List) Len() int { } // Get returns key and items at the position. -func (l List) Get(i int) ([]byte, []interface{}) { +func (l List) Get(i int) ([]byte, []any) { return l.segments[i].startKey, l.segments[i].data } // GetDataByKey returns position and items by key. -func (l List) GetDataByKey(key []byte) (index int, data []interface{}) { +func (l List) GetDataByKey(key []byte) (index int, data []any) { i := sort.Search(len(l.segments), func(i int) bool { return bytes.Compare(l.segments[i].startKey, key) > 0 }) @@ -53,7 +53,7 @@ func (l List) GetDataByKey(key []byte) (index int, data []interface{}) { } // GetData returns position and items by key range. -func (l List) GetData(start, end []byte) (index int, data []interface{}) { +func (l List) GetData(start, end []byte) (index int, data []any) { i := sort.Search(len(l.segments), func(i int) bool { return bytes.Compare(l.segments[i].startKey, start) > 0 }) diff --git a/pkg/schedule/rangelist/range_list_test.go b/pkg/schedule/rangelist/range_list_test.go index d8517705153..5baa7f16f28 100644 --- a/pkg/schedule/rangelist/range_list_test.go +++ b/pkg/schedule/rangelist/range_list_test.go @@ -41,20 +41,20 @@ func TestRangeList(t *testing.T) { key, data := rl.Get(0) re.Nil(key) - re.Equal([]interface{}{1}, data) + re.Equal([]any{1}, data) i, data = rl.GetDataByKey([]byte("foo")) re.Equal(0, i) - re.Equal([]interface{}{1}, data) + re.Equal([]any{1}, data) i, data = rl.GetData([]byte("a"), []byte("b")) re.Equal(0, i) - re.Equal([]interface{}{1}, data) + re.Equal([]any{1}, data) re.Nil(rl.GetSplitKeys(nil, []byte("foo"))) } func TestRangeList2(t *testing.T) { re := require.New(t) b := NewBuilder() - b.SetCompareFunc(func(a, b interface{}) int { + b.SetCompareFunc(func(a, b any) int { if a.(int) > b.(int) { return 1 } @@ -80,7 +80,7 @@ func TestRangeList2(t *testing.T) { expectKeys := [][]byte{ {}, {'a'}, {'b'}, {'c'}, {'d'}, {'e'}, {'f'}, {'g'}, {'h'}, {'i'}, } - expectData := [][]interface{}{ + expectData := [][]any{ {2, 3}, {2, 3, 4}, {4}, {1, 4}, {4}, {}, {3}, {2, 3}, {2}, {}, } diff --git a/pkg/schedule/schedulers/balance_leader.go b/pkg/schedule/schedulers/balance_leader.go index eb94752944b..e11e8492765 100644 --- a/pkg/schedule/schedulers/balance_leader.go +++ b/pkg/schedule/schedulers/balance_leader.go @@ -74,7 +74,7 @@ type balanceLeaderSchedulerConfig struct { Batch int `json:"batch"` } -func (conf *balanceLeaderSchedulerConfig) Update(data []byte) (int, interface{}) { +func (conf *balanceLeaderSchedulerConfig) Update(data []byte) (int, any) { conf.Lock() defer conf.Unlock() @@ -93,7 +93,7 @@ func (conf *balanceLeaderSchedulerConfig) Update(data []byte) (int, interface{}) log.Info("balance-leader-scheduler config is updated", zap.ByteString("old", oldConfig), zap.ByteString("new", newConfig)) return http.StatusOK, "Config is updated." } - m := make(map[string]interface{}) + m := make(map[string]any) if err := json.Unmarshal(data, &m); err != nil { return http.StatusInternalServerError, err.Error() } diff --git a/pkg/schedule/schedulers/balance_witness.go b/pkg/schedule/schedulers/balance_witness.go index 9994866ac50..aee112c9dc1 100644 --- a/pkg/schedule/schedulers/balance_witness.go +++ b/pkg/schedule/schedulers/balance_witness.go @@ -60,7 +60,7 @@ type balanceWitnessSchedulerConfig struct { Batch int `json:"batch"` } -func (conf *balanceWitnessSchedulerConfig) Update(data []byte) (int, interface{}) { +func (conf *balanceWitnessSchedulerConfig) Update(data []byte) (int, any) { conf.Lock() defer conf.Unlock() @@ -79,7 +79,7 @@ func (conf *balanceWitnessSchedulerConfig) Update(data []byte) (int, interface{} log.Info("balance-witness-scheduler config is updated", zap.ByteString("old", oldc), zap.ByteString("new", newc)) return http.StatusOK, "Config is updated." } - m := make(map[string]interface{}) + m := make(map[string]any) if err := json.Unmarshal(data, &m); err != nil { return http.StatusInternalServerError, err.Error() } diff --git a/pkg/schedule/schedulers/diagnostic_recorder.go b/pkg/schedule/schedulers/diagnostic_recorder.go index b990bdc8f22..df57dbebe71 100644 --- a/pkg/schedule/schedulers/diagnostic_recorder.go +++ b/pkg/schedule/schedulers/diagnostic_recorder.go @@ -86,7 +86,7 @@ func (d *DiagnosticRecorder) GetLastResult() *DiagnosticResult { if d.results.Len() == 0 { return nil } - items := d.results.FromLastSameElems(func(i interface{}) (bool, string) { + items := d.results.FromLastSameElems(func(i any) (bool, string) { result, ok := i.(*DiagnosticResult) if result == nil { return ok, "" diff --git a/pkg/schedule/schedulers/evict_leader.go b/pkg/schedule/schedulers/evict_leader.go index d2759e47d98..3db8b44c925 100644 --- a/pkg/schedule/schedulers/evict_leader.go +++ b/pkg/schedule/schedulers/evict_leader.go @@ -356,7 +356,7 @@ type evictLeaderHandler struct { } func (handler *evictLeaderHandler) UpdateConfig(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(handler.rd, w, r.Body, &input); err != nil { return } @@ -408,7 +408,7 @@ func (handler *evictLeaderHandler) DeleteConfig(w http.ResponseWriter, r *http.R return } - var resp interface{} + var resp any keyRanges := handler.config.getKeyRangesByID(id) succ, last := handler.config.removeStore(id) if succ { diff --git a/pkg/schedule/schedulers/evict_slow_store.go b/pkg/schedule/schedulers/evict_slow_store.go index 79715a6fd44..aa48d0bc9e9 100644 --- a/pkg/schedule/schedulers/evict_slow_store.go +++ b/pkg/schedule/schedulers/evict_slow_store.go @@ -154,7 +154,7 @@ func newEvictSlowStoreHandler(config *evictSlowStoreSchedulerConfig) http.Handle } func (handler *evictSlowStoreHandler) UpdateConfig(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(handler.rd, w, r.Body, &input); err != nil { return } diff --git a/pkg/schedule/schedulers/evict_slow_trend.go b/pkg/schedule/schedulers/evict_slow_trend.go index 20c53219765..b75ff27bd9a 100644 --- a/pkg/schedule/schedulers/evict_slow_trend.go +++ b/pkg/schedule/schedulers/evict_slow_trend.go @@ -240,7 +240,7 @@ func newEvictSlowTrendHandler(config *evictSlowTrendSchedulerConfig) http.Handle } func (handler *evictSlowTrendHandler) UpdateConfig(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(handler.rd, w, r.Body, &input); err != nil { return } diff --git a/pkg/schedule/schedulers/grant_hot_region.go b/pkg/schedule/schedulers/grant_hot_region.go index 81399b58c58..37d1707339e 100644 --- a/pkg/schedule/schedulers/grant_hot_region.go +++ b/pkg/schedule/schedulers/grant_hot_region.go @@ -203,7 +203,7 @@ type grantHotRegionHandler struct { } func (handler *grantHotRegionHandler) UpdateConfig(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(handler.rd, w, r.Body, &input); err != nil { return } diff --git a/pkg/schedule/schedulers/grant_leader.go b/pkg/schedule/schedulers/grant_leader.go index 13f7c5e28d5..8d36a5ae1c3 100644 --- a/pkg/schedule/schedulers/grant_leader.go +++ b/pkg/schedule/schedulers/grant_leader.go @@ -267,7 +267,7 @@ type grantLeaderHandler struct { } func (handler *grantLeaderHandler) UpdateConfig(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(handler.rd, w, r.Body, &input); err != nil { return } @@ -319,7 +319,7 @@ func (handler *grantLeaderHandler) DeleteConfig(w http.ResponseWriter, r *http.R return } - var resp interface{} + var resp any keyRanges := handler.config.getKeyRangesByID(id) succ, last := handler.config.removeStore(id) if succ { diff --git a/pkg/schedule/schedulers/hot_region_config.go b/pkg/schedule/schedulers/hot_region_config.go index 3f9f8b8c669..adf6480bacf 100644 --- a/pkg/schedule/schedulers/hot_region_config.go +++ b/pkg/schedule/schedulers/hot_region_config.go @@ -426,7 +426,7 @@ func (conf *hotRegionSchedulerConfig) handleSetConfig(w http.ResponseWriter, r * return } - m := make(map[string]interface{}) + m := make(map[string]any) if err := json.Unmarshal(data, &m); err != nil { rd.JSON(w, http.StatusInternalServerError, err.Error()) return diff --git a/pkg/schedule/schedulers/hot_region_test.go b/pkg/schedule/schedulers/hot_region_test.go index 5b1bc3db4b4..ede4bbec034 100644 --- a/pkg/schedule/schedulers/hot_region_test.go +++ b/pkg/schedule/schedulers/hot_region_test.go @@ -2442,7 +2442,7 @@ func TestCompatibilityConfig(t *testing.T) { // from 4.0 or 5.0 or 5.1 cluster var data []byte storage := storage.NewStorageWithMemoryBackend() - data, err = EncodeConfig(map[string]interface{}{ + data, err = EncodeConfig(map[string]any{ "min-hot-byte-rate": 100, "min-hot-key-rate": 10, "max-zombie-rounds": 3, diff --git a/pkg/schedule/schedulers/init.go b/pkg/schedule/schedulers/init.go index 57eb4b90985..e22037703cc 100644 --- a/pkg/schedule/schedulers/init.go +++ b/pkg/schedule/schedulers/init.go @@ -37,7 +37,7 @@ func Register() { func schedulersRegister() { // balance leader RegisterSliceDecoderBuilder(BalanceLeaderType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { conf, ok := v.(*balanceLeaderSchedulerConfig) if !ok { return errs.ErrScheduleConfigNotExist.FastGenByArgs() @@ -65,7 +65,7 @@ func schedulersRegister() { // balance region RegisterSliceDecoderBuilder(BalanceRegionType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { conf, ok := v.(*balanceRegionSchedulerConfig) if !ok { return errs.ErrScheduleConfigNotExist.FastGenByArgs() @@ -90,7 +90,7 @@ func schedulersRegister() { // balance witness RegisterSliceDecoderBuilder(BalanceWitnessType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { conf, ok := v.(*balanceWitnessSchedulerConfig) if !ok { return errs.ErrScheduleConfigNotExist.FastGenByArgs() @@ -118,7 +118,7 @@ func schedulersRegister() { // evict leader RegisterSliceDecoderBuilder(EvictLeaderType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { if len(args) != 1 { return errs.ErrSchedulerConfig.FastGenByArgs("id") } @@ -153,7 +153,7 @@ func schedulersRegister() { // evict slow store RegisterSliceDecoderBuilder(EvictSlowStoreType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { return nil } }) @@ -169,7 +169,7 @@ func schedulersRegister() { // grant hot region RegisterSliceDecoderBuilder(GrantHotRegionType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { if len(args) != 2 { return errs.ErrSchedulerConfig.FastGenByArgs("id") } @@ -209,14 +209,14 @@ func schedulersRegister() { // hot region RegisterSliceDecoderBuilder(HotRegionType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { return nil } }) RegisterScheduler(HotRegionType, func(opController *operator.Controller, storage endpoint.ConfigStorage, decoder ConfigDecoder, removeSchedulerCb ...func(string) error) (Scheduler, error) { conf := initHotRegionScheduleConfig() - var data map[string]interface{} + var data map[string]any if err := decoder(&data); err != nil { return nil, err } @@ -236,7 +236,7 @@ func schedulersRegister() { // grant leader RegisterSliceDecoderBuilder(GrantLeaderType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { if len(args) != 1 { return errs.ErrSchedulerConfig.FastGenByArgs("id") } @@ -271,7 +271,7 @@ func schedulersRegister() { // label RegisterSliceDecoderBuilder(LabelType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { conf, ok := v.(*labelSchedulerConfig) if !ok { return errs.ErrScheduleConfigNotExist.FastGenByArgs() @@ -296,7 +296,7 @@ func schedulersRegister() { // random merge RegisterSliceDecoderBuilder(RandomMergeType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { conf, ok := v.(*randomMergeSchedulerConfig) if !ok { return errs.ErrScheduleConfigNotExist.FastGenByArgs() @@ -322,7 +322,7 @@ func schedulersRegister() { // scatter range // args: [start-key, end-key, range-name]. RegisterSliceDecoderBuilder(ScatterRangeType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { if len(args) != 3 { return errs.ErrSchedulerConfig.FastGenByArgs("ranges and name") } @@ -356,7 +356,7 @@ func schedulersRegister() { // shuffle hot region RegisterSliceDecoderBuilder(ShuffleHotRegionType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { conf, ok := v.(*shuffleHotRegionSchedulerConfig) if !ok { return errs.ErrScheduleConfigNotExist.FastGenByArgs() @@ -385,7 +385,7 @@ func schedulersRegister() { // shuffle leader RegisterSliceDecoderBuilder(ShuffleLeaderType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { conf, ok := v.(*shuffleLeaderSchedulerConfig) if !ok { return errs.ErrScheduleConfigNotExist.FastGenByArgs() @@ -410,7 +410,7 @@ func schedulersRegister() { // shuffle region RegisterSliceDecoderBuilder(ShuffleRegionType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { conf, ok := v.(*shuffleRegionSchedulerConfig) if !ok { return errs.ErrScheduleConfigNotExist.FastGenByArgs() @@ -435,7 +435,7 @@ func schedulersRegister() { // split bucket RegisterSliceDecoderBuilder(SplitBucketType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { return nil } }) @@ -451,7 +451,7 @@ func schedulersRegister() { // transfer witness leader RegisterSliceDecoderBuilder(TransferWitnessLeaderType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { return nil } }) @@ -462,7 +462,7 @@ func schedulersRegister() { // evict slow store by trend RegisterSliceDecoderBuilder(EvictSlowTrendType, func(args []string) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { return nil } }) diff --git a/pkg/schedule/schedulers/scatter_range.go b/pkg/schedule/schedulers/scatter_range.go index 977d8cff05c..9ad9e597dfd 100644 --- a/pkg/schedule/schedulers/scatter_range.go +++ b/pkg/schedule/schedulers/scatter_range.go @@ -245,7 +245,7 @@ type scatterRangeHandler struct { } func (handler *scatterRangeHandler) UpdateConfig(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(handler.rd, w, r.Body, &input); err != nil { return } diff --git a/pkg/schedule/schedulers/scheduler.go b/pkg/schedule/schedulers/scheduler.go index 38fc8f5607d..b74b72283ec 100644 --- a/pkg/schedule/schedulers/scheduler.go +++ b/pkg/schedule/schedulers/scheduler.go @@ -49,7 +49,7 @@ type Scheduler interface { } // EncodeConfig encode the custom config for each scheduler. -func EncodeConfig(v interface{}) ([]byte, error) { +func EncodeConfig(v any) ([]byte, error) { marshaled, err := json.Marshal(v) if err != nil { return nil, errs.ErrJSONMarshal.Wrap(err) @@ -58,7 +58,7 @@ func EncodeConfig(v interface{}) ([]byte, error) { } // DecodeConfig decode the custom config for each scheduler. -func DecodeConfig(data []byte, v interface{}) error { +func DecodeConfig(data []byte, v any) error { err := json.Unmarshal(data, v) if err != nil { return errs.ErrJSONUnmarshal.Wrap(err) @@ -67,10 +67,10 @@ func DecodeConfig(data []byte, v interface{}) error { } // ToPayload returns the payload of config. -func ToPayload(sches, configs []string) map[string]interface{} { - payload := make(map[string]interface{}) +func ToPayload(sches, configs []string) map[string]any { + payload := make(map[string]any) for i, sche := range sches { - var config interface{} + var config any err := DecodeConfig([]byte(configs[i]), &config) if err != nil { log.Error("failed to decode scheduler config", @@ -85,14 +85,14 @@ func ToPayload(sches, configs []string) map[string]interface{} { } // ConfigDecoder used to decode the config. -type ConfigDecoder func(v interface{}) error +type ConfigDecoder func(v any) error // ConfigSliceDecoderBuilder used to build slice decoder of the config. type ConfigSliceDecoderBuilder func([]string) ConfigDecoder // ConfigJSONDecoder used to build a json decoder of the config. func ConfigJSONDecoder(data []byte) ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { return DecodeConfig(data, v) } } @@ -101,7 +101,7 @@ func ConfigJSONDecoder(data []byte) ConfigDecoder { func ConfigSliceDecoder(name string, args []string) ConfigDecoder { builder, ok := schedulerArgsToDecoder[name] if !ok { - return func(v interface{}) error { + return func(v any) error { return errors.Errorf("the config decoder do not register for %s", name) } } diff --git a/pkg/schedule/schedulers/shuffle_hot_region.go b/pkg/schedule/schedulers/shuffle_hot_region.go index cd5c40d4e07..541be959fcf 100644 --- a/pkg/schedule/schedulers/shuffle_hot_region.go +++ b/pkg/schedule/schedulers/shuffle_hot_region.go @@ -227,7 +227,7 @@ type shuffleHotRegionHandler struct { } func (handler *shuffleHotRegionHandler) UpdateConfig(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(handler.rd, w, r.Body, &input); err != nil { return } diff --git a/pkg/schedule/schedulers/split_bucket.go b/pkg/schedule/schedulers/split_bucket.go index 5e31f58129c..7e276402e49 100644 --- a/pkg/schedule/schedulers/split_bucket.go +++ b/pkg/schedule/schedulers/split_bucket.go @@ -138,7 +138,7 @@ func (h *splitBucketHandler) UpdateConfig(w http.ResponseWriter, r *http.Request return } - m := make(map[string]interface{}) + m := make(map[string]any) if err := json.Unmarshal(data, &m); err != nil { rd.JSON(w, http.StatusInternalServerError, err.Error()) return diff --git a/pkg/statistics/utils/topn.go b/pkg/statistics/utils/topn.go index 916bbb82f92..7ab6c6eaf3e 100644 --- a/pkg/statistics/utils/topn.go +++ b/pkg/statistics/utils/topn.go @@ -261,14 +261,14 @@ func (hp *indexedHeap) Swap(i, j int) { } // Implementing heap.Interface. -func (hp *indexedHeap) Push(x interface{}) { +func (hp *indexedHeap) Push(x any) { item := x.(TopNItem) hp.index[item.ID()] = hp.Len() hp.items = append(hp.items, item) } // Implementing heap.Interface. -func (hp *indexedHeap) Pop() interface{} { +func (hp *indexedHeap) Pop() any { l := hp.Len() item := hp.items[l-1] hp.items = hp.items[:l-1] diff --git a/pkg/storage/endpoint/config.go b/pkg/storage/endpoint/config.go index edfdcbca9a3..820778e36ff 100644 --- a/pkg/storage/endpoint/config.go +++ b/pkg/storage/endpoint/config.go @@ -25,8 +25,8 @@ import ( // ConfigStorage defines the storage operations on the config. type ConfigStorage interface { // Persisted config will be stored in the storage. - LoadConfig(cfg interface{}) (bool, error) - SaveConfig(cfg interface{}) error + LoadConfig(cfg any) (bool, error) + SaveConfig(cfg any) error // Each scheduler has its own customized config, so we need to store them separately. LoadAllSchedulerConfigs() ([]string, []string, error) LoadSchedulerConfig(schedulerName string) (string, error) @@ -37,7 +37,7 @@ type ConfigStorage interface { var _ ConfigStorage = (*StorageEndpoint)(nil) // LoadConfig loads config from configPath then unmarshal it to cfg. -func (se *StorageEndpoint) LoadConfig(cfg interface{}) (bool, error) { +func (se *StorageEndpoint) LoadConfig(cfg any) (bool, error) { value, err := se.Load(configPath) if err != nil || value == "" { return false, err @@ -50,7 +50,7 @@ func (se *StorageEndpoint) LoadConfig(cfg interface{}) (bool, error) { } // SaveConfig stores marshallable cfg to the configPath. -func (se *StorageEndpoint) SaveConfig(cfg interface{}) error { +func (se *StorageEndpoint) SaveConfig(cfg any) error { return se.saveJSON(configPath, cfg) } diff --git a/pkg/storage/endpoint/replication_status.go b/pkg/storage/endpoint/replication_status.go index 0a14770ff47..3cfaaefb9a4 100644 --- a/pkg/storage/endpoint/replication_status.go +++ b/pkg/storage/endpoint/replication_status.go @@ -22,14 +22,14 @@ import ( // ReplicationStatusStorage defines the storage operations on the replication status. type ReplicationStatusStorage interface { - LoadReplicationStatus(mode string, status interface{}) (bool, error) - SaveReplicationStatus(mode string, status interface{}) error + LoadReplicationStatus(mode string, status any) (bool, error) + SaveReplicationStatus(mode string, status any) error } var _ ReplicationStatusStorage = (*StorageEndpoint)(nil) // LoadReplicationStatus loads replication status by mode. -func (se *StorageEndpoint) LoadReplicationStatus(mode string, status interface{}) (bool, error) { +func (se *StorageEndpoint) LoadReplicationStatus(mode string, status any) (bool, error) { v, err := se.Load(replicationModePath(mode)) if err != nil || v == "" { return false, err @@ -42,6 +42,6 @@ func (se *StorageEndpoint) LoadReplicationStatus(mode string, status interface{} } // SaveReplicationStatus stores replication status by mode. -func (se *StorageEndpoint) SaveReplicationStatus(mode string, status interface{}) error { +func (se *StorageEndpoint) SaveReplicationStatus(mode string, status any) error { return se.saveJSON(replicationModePath(mode), status) } diff --git a/pkg/storage/endpoint/resource_group.go b/pkg/storage/endpoint/resource_group.go index 150ea77a1c7..e777ea635c6 100644 --- a/pkg/storage/endpoint/resource_group.go +++ b/pkg/storage/endpoint/resource_group.go @@ -24,9 +24,9 @@ type ResourceGroupStorage interface { SaveResourceGroupSetting(name string, msg proto.Message) error DeleteResourceGroupSetting(name string) error LoadResourceGroupStates(f func(k, v string)) error - SaveResourceGroupStates(name string, obj interface{}) error + SaveResourceGroupStates(name string, obj any) error DeleteResourceGroupStates(name string) error - SaveControllerConfig(config interface{}) error + SaveControllerConfig(config any) error LoadControllerConfig() (string, error) } @@ -48,7 +48,7 @@ func (se *StorageEndpoint) LoadResourceGroupSettings(f func(k, v string)) error } // SaveResourceGroupStates stores a resource group to storage. -func (se *StorageEndpoint) SaveResourceGroupStates(name string, obj interface{}) error { +func (se *StorageEndpoint) SaveResourceGroupStates(name string, obj any) error { return se.saveJSON(resourceGroupStateKeyPath(name), obj) } @@ -63,7 +63,7 @@ func (se *StorageEndpoint) LoadResourceGroupStates(f func(k, v string)) error { } // SaveControllerConfig stores the resource controller config to storage. -func (se *StorageEndpoint) SaveControllerConfig(config interface{}) error { +func (se *StorageEndpoint) SaveControllerConfig(config any) error { return se.saveJSON(controllerConfigPath, config) } diff --git a/pkg/storage/endpoint/rule.go b/pkg/storage/endpoint/rule.go index b0827fda477..d0092e8e303 100644 --- a/pkg/storage/endpoint/rule.go +++ b/pkg/storage/endpoint/rule.go @@ -31,11 +31,11 @@ type RuleStorage interface { // We need to use txn to avoid concurrent modification. // And it is helpful for the scheduling server to watch the rule. - SaveRule(txn kv.Txn, ruleKey string, rule interface{}) error + SaveRule(txn kv.Txn, ruleKey string, rule any) error DeleteRule(txn kv.Txn, ruleKey string) error - SaveRuleGroup(txn kv.Txn, groupID string, group interface{}) error + SaveRuleGroup(txn kv.Txn, groupID string, group any) error DeleteRuleGroup(txn kv.Txn, groupID string) error - SaveRegionRule(txn kv.Txn, ruleKey string, rule interface{}) error + SaveRegionRule(txn kv.Txn, ruleKey string, rule any) error DeleteRegionRule(txn kv.Txn, ruleKey string) error RunInTxn(ctx context.Context, f func(txn kv.Txn) error) error @@ -44,7 +44,7 @@ type RuleStorage interface { var _ RuleStorage = (*StorageEndpoint)(nil) // SaveRule stores a rule cfg to the rulesPath. -func (se *StorageEndpoint) SaveRule(txn kv.Txn, ruleKey string, rule interface{}) error { +func (se *StorageEndpoint) SaveRule(txn kv.Txn, ruleKey string, rule any) error { return saveJSONInTxn(txn, ruleKeyPath(ruleKey), rule) } @@ -59,7 +59,7 @@ func (se *StorageEndpoint) LoadRuleGroups(f func(k, v string)) error { } // SaveRuleGroup stores a rule group config to storage. -func (se *StorageEndpoint) SaveRuleGroup(txn kv.Txn, groupID string, group interface{}) error { +func (se *StorageEndpoint) SaveRuleGroup(txn kv.Txn, groupID string, group any) error { return saveJSONInTxn(txn, ruleGroupIDPath(groupID), group) } @@ -74,7 +74,7 @@ func (se *StorageEndpoint) LoadRegionRules(f func(k, v string)) error { } // SaveRegionRule saves a region rule to the storage. -func (se *StorageEndpoint) SaveRegionRule(txn kv.Txn, ruleKey string, rule interface{}) error { +func (se *StorageEndpoint) SaveRegionRule(txn kv.Txn, ruleKey string, rule any) error { return saveJSONInTxn(txn, regionLabelKeyPath(ruleKey), rule) } diff --git a/pkg/storage/endpoint/service_middleware.go b/pkg/storage/endpoint/service_middleware.go index 2becbf3686e..23095900755 100644 --- a/pkg/storage/endpoint/service_middleware.go +++ b/pkg/storage/endpoint/service_middleware.go @@ -22,14 +22,14 @@ import ( // ServiceMiddlewareStorage defines the storage operations on the service middleware. type ServiceMiddlewareStorage interface { - LoadServiceMiddlewareConfig(cfg interface{}) (bool, error) - SaveServiceMiddlewareConfig(cfg interface{}) error + LoadServiceMiddlewareConfig(cfg any) (bool, error) + SaveServiceMiddlewareConfig(cfg any) error } var _ ServiceMiddlewareStorage = (*StorageEndpoint)(nil) // LoadServiceMiddlewareConfig loads service middleware config from serviceMiddlewarePath then unmarshal it to cfg. -func (se *StorageEndpoint) LoadServiceMiddlewareConfig(cfg interface{}) (bool, error) { +func (se *StorageEndpoint) LoadServiceMiddlewareConfig(cfg any) (bool, error) { value, err := se.Load(serviceMiddlewarePath) if err != nil || value == "" { return false, err @@ -42,6 +42,6 @@ func (se *StorageEndpoint) LoadServiceMiddlewareConfig(cfg interface{}) (bool, e } // SaveServiceMiddlewareConfig stores marshallable cfg to the serviceMiddlewarePath. -func (se *StorageEndpoint) SaveServiceMiddlewareConfig(cfg interface{}) error { +func (se *StorageEndpoint) SaveServiceMiddlewareConfig(cfg any) error { return se.saveJSON(serviceMiddlewarePath, cfg) } diff --git a/pkg/storage/endpoint/util.go b/pkg/storage/endpoint/util.go index cf1e4ef2315..06535490206 100644 --- a/pkg/storage/endpoint/util.go +++ b/pkg/storage/endpoint/util.go @@ -46,11 +46,11 @@ func (se *StorageEndpoint) saveProto(key string, msg proto.Message) error { return se.Save(key, string(value)) } -func (se *StorageEndpoint) saveJSON(key string, data interface{}) error { +func (se *StorageEndpoint) saveJSON(key string, data any) error { return saveJSONInTxn(se /* use the same interface */, key, data) } -func saveJSONInTxn(txn kv.Txn, key string, data interface{}) error { +func saveJSONInTxn(txn kv.Txn, key string, data any) error { value, err := json.Marshal(data) if err != nil { return errs.ErrJSONMarshal.Wrap(err).GenWithStackByArgs() diff --git a/pkg/tso/admin.go b/pkg/tso/admin.go index f19d8e71d05..bc9fd1f853d 100644 --- a/pkg/tso/admin.go +++ b/pkg/tso/admin.go @@ -67,7 +67,7 @@ func NewAdminHandler(handler Handler, rd *render.Render) *AdminHandler { // during EBS based restore, we call this to make sure ts of pd >= resolved_ts in backup. func (h *AdminHandler) ResetTS(w http.ResponseWriter, r *http.Request) { handler := h.handler - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { return } diff --git a/pkg/tso/allocator_manager.go b/pkg/tso/allocator_manager.go index 251a3aaf2e6..4055ec12a7d 100644 --- a/pkg/tso/allocator_manager.go +++ b/pkg/tso/allocator_manager.go @@ -108,7 +108,7 @@ type ElectionMember interface { // MemberValue returns the member value. MemberValue() string // GetMember returns the current member - GetMember() interface{} + GetMember() any // Client returns the etcd client. Client() *clientv3.Client // IsLeader returns whether the participant is the leader or not by checking its diff --git a/pkg/tso/keyspace_group_manager.go b/pkg/tso/keyspace_group_manager.go index 77967a97ef7..b752233fcff 100644 --- a/pkg/tso/keyspace_group_manager.go +++ b/pkg/tso/keyspace_group_manager.go @@ -624,7 +624,7 @@ func (kgm *KeyspaceGroupManager) primaryPriorityCheckLoop() { member, kg, localPriority, nextGroupID := kgm.getNextPrimaryToReset(groupID, kgm.tsoServiceID.ServiceAddr) if member != nil { aliveTSONodes := make(map[string]struct{}) - kgm.tsoNodes.Range(func(key, _ interface{}) bool { + kgm.tsoNodes.Range(func(key, _ any) bool { aliveTSONodes[key.(string)] = struct{}{} return true }) diff --git a/pkg/tso/local_allocator.go b/pkg/tso/local_allocator.go index 9d244d2531d..45c200ca566 100644 --- a/pkg/tso/local_allocator.go +++ b/pkg/tso/local_allocator.go @@ -139,7 +139,7 @@ func (lta *LocalTSOAllocator) Reset() { } // setAllocatorLeader sets the current Local TSO Allocator leader. -func (lta *LocalTSOAllocator) setAllocatorLeader(member interface{}) { +func (lta *LocalTSOAllocator) setAllocatorLeader(member any) { lta.allocatorLeader.Store(member) } diff --git a/pkg/utils/apiutil/apiutil.go b/pkg/utils/apiutil/apiutil.go index f8ca1174b3b..4777d49df96 100644 --- a/pkg/utils/apiutil/apiutil.go +++ b/pkg/utils/apiutil/apiutil.go @@ -280,7 +280,7 @@ func ParseUint64VarsField(vars map[string]string, varName string) (uint64, *Fiel } // CollectEscapeStringOption is used to collect string using escaping from input map for given option -func CollectEscapeStringOption(option string, input map[string]interface{}, collectors ...func(v string)) error { +func CollectEscapeStringOption(option string, input map[string]any, collectors ...func(v string)) error { if v, ok := input[option].(string); ok { value, err := url.QueryUnescape(v) if err != nil { @@ -295,7 +295,7 @@ func CollectEscapeStringOption(option string, input map[string]interface{}, coll } // CollectStringOption is used to collect string using from input map for given option -func CollectStringOption(option string, input map[string]interface{}, collectors ...func(v string)) error { +func CollectStringOption(option string, input map[string]any, collectors ...func(v string)) error { if v, ok := input[option].(string); ok { for _, c := range collectors { c(v) @@ -306,7 +306,7 @@ func CollectStringOption(option string, input map[string]interface{}, collectors } // ParseKey is used to parse interface into []byte and string -func ParseKey(name string, input map[string]interface{}) ([]byte, string, error) { +func ParseKey(name string, input map[string]any) ([]byte, string, error) { k, ok := input[name] if !ok { return nil, "", fmt.Errorf("missing %s", name) @@ -324,7 +324,7 @@ func ParseKey(name string, input map[string]interface{}) ([]byte, string, error) // ReadJSON reads a JSON data from r and then closes it. // An error due to invalid json will be returned as a JSONError -func ReadJSON(r io.ReadCloser, data interface{}) error { +func ReadJSON(r io.ReadCloser, data any) error { var err error defer DeferClose(r, &err) b, err := io.ReadAll(r) @@ -342,7 +342,7 @@ func ReadJSON(r io.ReadCloser, data interface{}) error { // ReadJSONRespondError writes json into data. // On error respond with a 400 Bad Request -func ReadJSONRespondError(rd *render.Render, w http.ResponseWriter, body io.ReadCloser, data interface{}) error { +func ReadJSONRespondError(rd *render.Render, w http.ResponseWriter, body io.ReadCloser, data any) error { err := ReadJSON(body, data) if err == nil { return nil diff --git a/pkg/utils/assertutil/assertutil.go b/pkg/utils/assertutil/assertutil.go index 9eb2719b220..74b831d5472 100644 --- a/pkg/utils/assertutil/assertutil.go +++ b/pkg/utils/assertutil/assertutil.go @@ -19,7 +19,7 @@ import "github.com/stretchr/testify/require" // Checker accepts the injection of check functions and context from test files. // Any check function should be set before usage unless the test will fail. type Checker struct { - IsNil func(obtained interface{}) + IsNil func(obtained any) FailNow func() } @@ -34,14 +34,14 @@ func CheckerWithNilAssert(re *require.Assertions) *Checker { checker.FailNow = func() { re.FailNow("should be nil") } - checker.IsNil = func(obtained interface{}) { + checker.IsNil = func(obtained any) { re.Nil(obtained) } return checker } // AssertNil calls the injected IsNil assertion. -func (c *Checker) AssertNil(obtained interface{}) { +func (c *Checker) AssertNil(obtained any) { if c.IsNil == nil { c.FailNow() return diff --git a/pkg/utils/configutil/configutil.go b/pkg/utils/configutil/configutil.go index 978edce7764..2e7c74d9f8c 100644 --- a/pkg/utils/configutil/configutil.go +++ b/pkg/utils/configutil/configutil.go @@ -96,7 +96,7 @@ func PrintConfigCheckMsg(w io.Writer, warningMsgs []string) { } // ConfigFromFile loads config from file. -func ConfigFromFile(c interface{}, path string) (*toml.MetaData, error) { +func ConfigFromFile(c any, path string) (*toml.MetaData, error) { meta, err := toml.DecodeFile(path, c) return &meta, errors.WithStack(err) } diff --git a/pkg/utils/etcdutil/health_checker.go b/pkg/utils/etcdutil/health_checker.go index 50df3ab38e8..d1a57e97c5f 100644 --- a/pkg/utils/etcdutil/health_checker.go +++ b/pkg/utils/etcdutil/health_checker.go @@ -146,7 +146,7 @@ func (checker *healthChecker) inspector(ctx context.Context) { } func (checker *healthChecker) close() { - checker.healthyClients.Range(func(key, value interface{}) bool { + checker.healthyClients.Range(func(key, value any) bool { healthyCli := value.(*healthyClient) healthyCli.healthState.Set(0) healthyCli.Client.Close() @@ -172,9 +172,9 @@ func (checker *healthChecker) patrol(ctx context.Context) ([]string, []string, b probeCh = make(chan healthProbe, count) wg sync.WaitGroup ) - checker.healthyClients.Range(func(key, value interface{}) bool { + checker.healthyClients.Range(func(key, value any) bool { wg.Add(1) - go func(key, value interface{}) { + go func(key, value any) { defer wg.Done() defer logutil.LogPanic() var ( @@ -274,7 +274,7 @@ func (checker *healthChecker) updateEvictedEps(lastEps, pickedEps []string) { pickedSet[ep] = true } // Reset the count to 0 if it's in evictedEps but not in the pickedEps. - checker.evictedEps.Range(func(key, _ interface{}) bool { + checker.evictedEps.Range(func(key, _ any) bool { ep := key.(string) if !pickedSet[ep] { checker.evictedEps.Store(ep, 0) @@ -380,7 +380,7 @@ func (checker *healthChecker) update() { } } // Clean up the stale clients which are not in the etcd cluster anymore. - checker.healthyClients.Range(func(key, value interface{}) bool { + checker.healthyClients.Range(func(key, value any) bool { ep := key.(string) if _, ok := epMap[ep]; !ok { log.Info("remove stale etcd client", @@ -394,7 +394,7 @@ func (checker *healthChecker) update() { func (checker *healthChecker) clientCount() int { count := 0 - checker.healthyClients.Range(func(_, _ interface{}) bool { + checker.healthyClients.Range(func(_, _ any) bool { count++ return true }) diff --git a/pkg/utils/etcdutil/health_checker_test.go b/pkg/utils/etcdutil/health_checker_test.go index f5682b1f1f0..82dd1362ba2 100644 --- a/pkg/utils/etcdutil/health_checker_test.go +++ b/pkg/utils/etcdutil/health_checker_test.go @@ -43,7 +43,7 @@ func check(re *require.Assertions, testCases []*testCase) { pickedEps = checker.filterEps(pickedEps) // Check the evicted states after finishing picking. count := 0 - checker.evictedEps.Range(func(key, value interface{}) bool { + checker.evictedEps.Range(func(key, value any) bool { count++ ep := key.(string) times := value.(int) diff --git a/pkg/utils/jsonutil/jsonutil.go b/pkg/utils/jsonutil/jsonutil.go index 32549a2698f..141dbb570ce 100644 --- a/pkg/utils/jsonutil/jsonutil.go +++ b/pkg/utils/jsonutil/jsonutil.go @@ -22,8 +22,8 @@ import ( ) // AddKeyValue is used to add a key value pair into `old` -func AddKeyValue(old interface{}, key string, value interface{}) (updated bool, found bool, err error) { - data, err := json.Marshal(map[string]interface{}{key: value}) +func AddKeyValue(old any, key string, value any) (updated bool, found bool, err error) { + data, err := json.Marshal(map[string]any{key: value}) if err != nil { return false, false, err } @@ -31,7 +31,7 @@ func AddKeyValue(old interface{}, key string, value interface{}) (updated bool, } // MergeJSONObject is used to merge a marshaled json object into v -func MergeJSONObject(v interface{}, data []byte) (updated bool, found bool, err error) { +func MergeJSONObject(v any, data []byte) (updated bool, found bool, err error) { old, _ := json.Marshal(v) if err := json.Unmarshal(data, v); err != nil { return false, false, err @@ -40,7 +40,7 @@ func MergeJSONObject(v interface{}, data []byte) (updated bool, found bool, err if !bytes.Equal(old, new) { return true, true, nil } - m := make(map[string]interface{}) + m := make(map[string]any) if err := json.Unmarshal(data, &m); err != nil { return false, false, err } diff --git a/pkg/utils/logutil/log_test.go b/pkg/utils/logutil/log_test.go index fd46acbdda3..7d4be7a88bd 100644 --- a/pkg/utils/logutil/log_test.go +++ b/pkg/utils/logutil/log_test.go @@ -39,9 +39,9 @@ func TestRedactLog(t *testing.T) { re := require.New(t) testCases := []struct { name string - arg interface{} + arg any enableRedactLog bool - expect interface{} + expect any }{ { name: "string arg, enable redact", diff --git a/pkg/utils/operatorutil/operator_check.go b/pkg/utils/operatorutil/operator_check.go index f6517be29d7..5d366cf8fb9 100644 --- a/pkg/utils/operatorutil/operator_check.go +++ b/pkg/utils/operatorutil/operator_check.go @@ -41,7 +41,7 @@ func CheckTransferLeaderFrom(re *require.Assertions, op *operator.Operator, kind func CheckMultiTargetTransferLeader(re *require.Assertions, op *operator.Operator, kind operator.OpKind, sourceID uint64, targetIDs []uint64) { re.NotNil(op) re.Equal(1, op.Len()) - expectedOps := make([]interface{}, 0, len(targetIDs)) + expectedOps := make([]any, 0, len(targetIDs)) for _, targetID := range targetIDs { expectedOps = append(expectedOps, operator.TransferLeader{FromStore: sourceID, ToStore: targetID, ToStores: targetIDs}) } diff --git a/pkg/utils/reflectutil/tag.go b/pkg/utils/reflectutil/tag.go index 3671519f96b..1d04d25502b 100644 --- a/pkg/utils/reflectutil/tag.go +++ b/pkg/utils/reflectutil/tag.go @@ -44,7 +44,7 @@ func FindJSONFullTagByChildTag(t reflect.Type, tag string) string { } // FindSameFieldByJSON is used to check whether there is same field between `m` and `v` -func FindSameFieldByJSON(v interface{}, m map[string]interface{}) bool { +func FindSameFieldByJSON(v any, m map[string]any) bool { t := reflect.TypeOf(v).Elem() for i := 0; i < t.NumField(); i++ { jsonTag := t.Field(i).Tag.Get("json") diff --git a/pkg/utils/reflectutil/tag_test.go b/pkg/utils/reflectutil/tag_test.go index d8619898ea5..f613f1f81b6 100644 --- a/pkg/utils/reflectutil/tag_test.go +++ b/pkg/utils/reflectutil/tag_test.go @@ -53,12 +53,12 @@ func TestFindJSONFullTagByChildTag(t *testing.T) { func TestFindSameFieldByJSON(t *testing.T) { t.Parallel() re := require.New(t) - input := map[string]interface{}{ + input := map[string]any{ "name": "test2", } t2 := testStruct2{} re.True(FindSameFieldByJSON(&t2, input)) - input = map[string]interface{}{ + input = map[string]any{ "enable": "test2", } re.False(FindSameFieldByJSON(&t2, input)) diff --git a/pkg/utils/testutil/api_check.go b/pkg/utils/testutil/api_check.go index 58934bf08f6..e4c58f68396 100644 --- a/pkg/utils/testutil/api_check.go +++ b/pkg/utils/testutil/api_check.go @@ -43,7 +43,7 @@ func StatusNotOK(re *require.Assertions) func([]byte, int, http.Header) { } // ExtractJSON is used to check whether given data can be extracted successfully. -func ExtractJSON(re *require.Assertions, data interface{}) func([]byte, int, http.Header) { +func ExtractJSON(re *require.Assertions, data any) func([]byte, int, http.Header) { return func(resp []byte, _ int, _ http.Header) { re.NoError(json.Unmarshal(resp, data), "resp: "+string(resp)) } @@ -78,7 +78,7 @@ func WithoutHeader(re *require.Assertions, key string) func([]byte, int, http.He } // ReadGetJSON is used to do get request and check whether given data can be extracted successfully. -func ReadGetJSON(re *require.Assertions, client *http.Client, url string, data interface{}, checkOpts ...func([]byte, int, http.Header)) error { +func ReadGetJSON(re *require.Assertions, client *http.Client, url string, data any, checkOpts ...func([]byte, int, http.Header)) error { resp, err := apiutil.GetJSON(client, url, nil) if err != nil { return err @@ -88,7 +88,7 @@ func ReadGetJSON(re *require.Assertions, client *http.Client, url string, data i } // ReadGetJSONWithBody is used to do get request with input and check whether given data can be extracted successfully. -func ReadGetJSONWithBody(re *require.Assertions, client *http.Client, url string, input []byte, data interface{}, checkOpts ...func([]byte, int, http.Header)) error { +func ReadGetJSONWithBody(re *require.Assertions, client *http.Client, url string, input []byte, data any, checkOpts ...func([]byte, int, http.Header)) error { resp, err := apiutil.GetJSON(client, url, input) if err != nil { return err diff --git a/pkg/utils/typeutil/conversion.go b/pkg/utils/typeutil/conversion.go index 6864a0f6111..128c7a887a4 100644 --- a/pkg/utils/typeutil/conversion.go +++ b/pkg/utils/typeutil/conversion.go @@ -53,8 +53,8 @@ func BoolToInt(b bool) int { } // JSONToUint64Slice converts JSON slice to uint64 slice. -func JSONToUint64Slice(from interface{}) ([]uint64, bool) { - items, ok := from.([]interface{}) +func JSONToUint64Slice(from any) ([]uint64, bool) { + items, ok := from.([]any) if !ok { return nil, false } diff --git a/pkg/utils/typeutil/conversion_test.go b/pkg/utils/typeutil/conversion_test.go index 0a209c899e8..14b2f9dea52 100644 --- a/pkg/utils/typeutil/conversion_test.go +++ b/pkg/utils/typeutil/conversion_test.go @@ -50,7 +50,7 @@ func TestJSONToUint64Slice(t *testing.T) { Array: []uint64{1, 2, 3}, } bytes, _ := json.Marshal(a) - var jsonStr map[string]interface{} + var jsonStr map[string]any err := json.Unmarshal(bytes, &jsonStr) re.NoError(err) // valid case @@ -69,7 +69,7 @@ func TestJSONToUint64Slice(t *testing.T) { Array: []string{"1", "2", "3"}, } bytes, _ = json.Marshal(a1) - var jsonStr1 map[string]interface{} + var jsonStr1 map[string]any err = json.Unmarshal(bytes, &jsonStr1) re.NoError(err) res, ok = JSONToUint64Slice(jsonStr1["array"]) diff --git a/plugin/scheduler_example/evict_leader.go b/plugin/scheduler_example/evict_leader.go index 063ae9eb150..eaeb449f4a6 100644 --- a/plugin/scheduler_example/evict_leader.go +++ b/plugin/scheduler_example/evict_leader.go @@ -46,7 +46,7 @@ const ( func init() { schedulers.RegisterSliceDecoderBuilder(EvictLeaderType, func(args []string) schedulers.ConfigDecoder { - return func(v interface{}) error { + return func(v any) error { if len(args) != 1 { return errors.New("should specify the store-id") } @@ -249,7 +249,7 @@ type evictLeaderHandler struct { } func (handler *evictLeaderHandler) UpdateConfig(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(handler.rd, w, r.Body, &input); err != nil { return } @@ -307,7 +307,7 @@ func (handler *evictLeaderHandler) DeleteConfig(w http.ResponseWriter, r *http.R handler.config.Persist() handler.config.mu.Lock() - var resp interface{} + var resp any if len(handler.config.StoreIDWitRanges) == 0 { resp = noStoreInSchedulerInfo } diff --git a/server/api/admin.go b/server/api/admin.go index 49fe7cdc567..fc63f9630a6 100644 --- a/server/api/admin.go +++ b/server/api/admin.go @@ -179,7 +179,7 @@ func (h *adminHandler) UnmarkSnapshotRecovering(w http.ResponseWriter, r *http.R // RecoverAllocID recover base alloc id // body should be in {"id": "123"} format func (h *adminHandler) RecoverAllocID(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { return } diff --git a/server/api/admin_test.go b/server/api/admin_test.go index 050aa9cfb32..3a628a1de61 100644 --- a/server/api/admin_test.go +++ b/server/api/admin_test.go @@ -186,7 +186,7 @@ func makeTS(offset time.Duration) uint64 { func (suite *adminTestSuite) TestResetTS() { re := suite.Require() - args := make(map[string]interface{}) + args := make(map[string]any) t1 := makeTS(time.Hour) url := fmt.Sprintf("%s/admin/reset-ts", suite.urlPrefix) args["tso"] = fmt.Sprintf("%d", t1) diff --git a/server/api/config.go b/server/api/config.go index 6037de650a0..16ad1f74f9b 100644 --- a/server/api/config.go +++ b/server/api/config.go @@ -113,7 +113,7 @@ func (h *confHandler) SetConfig(w http.ResponseWriter, r *http.Request) { return } - conf := make(map[string]interface{}) + conf := make(map[string]any) if err := json.Unmarshal(data, &conf); err != nil { h.rd.JSON(w, http.StatusBadRequest, err.Error()) return @@ -157,7 +157,7 @@ func (h *confHandler) SetConfig(w http.ResponseWriter, r *http.Request) { h.rd.JSON(w, http.StatusOK, "The config is updated.") } -func (h *confHandler) updateConfig(cfg *config.Config, key string, value interface{}) error { +func (h *confHandler) updateConfig(cfg *config.Config, key string, value any) error { kp := strings.Split(key, ".") switch kp[0] { case "schedule": @@ -187,7 +187,7 @@ func (h *confHandler) updateConfig(cfg *config.Config, key string, value interfa return errors.Errorf("config prefix %s not found", kp[0]) } -func (h *confHandler) updateKeyspaceConfig(config *config.Config, key string, value interface{}) error { +func (h *confHandler) updateKeyspaceConfig(config *config.Config, key string, value any) error { updated, found, err := jsonutil.AddKeyValue(&config.Keyspace, key, value) if err != nil { return err @@ -203,7 +203,7 @@ func (h *confHandler) updateKeyspaceConfig(config *config.Config, key string, va return err } -func (h *confHandler) updateMicroServiceConfig(config *config.Config, key string, value interface{}) error { +func (h *confHandler) updateMicroServiceConfig(config *config.Config, key string, value any) error { updated, found, err := jsonutil.AddKeyValue(&config.MicroService, key, value) if err != nil { return err @@ -219,7 +219,7 @@ func (h *confHandler) updateMicroServiceConfig(config *config.Config, key string return err } -func (h *confHandler) updateSchedule(config *config.Config, key string, value interface{}) error { +func (h *confHandler) updateSchedule(config *config.Config, key string, value any) error { updated, found, err := jsonutil.AddKeyValue(&config.Schedule, key, value) if err != nil { return err @@ -235,7 +235,7 @@ func (h *confHandler) updateSchedule(config *config.Config, key string, value in return err } -func (h *confHandler) updateReplication(config *config.Config, key string, value interface{}) error { +func (h *confHandler) updateReplication(config *config.Config, key string, value any) error { updated, found, err := jsonutil.AddKeyValue(&config.Replication, key, value) if err != nil { return err @@ -251,8 +251,8 @@ func (h *confHandler) updateReplication(config *config.Config, key string, value return err } -func (h *confHandler) updateReplicationModeConfig(config *config.Config, key []string, value interface{}) error { - cfg := make(map[string]interface{}) +func (h *confHandler) updateReplicationModeConfig(config *config.Config, key []string, value any) error { + cfg := make(map[string]any) cfg = getConfigMap(cfg, key, value) data, err := json.Marshal(cfg) if err != nil { @@ -273,7 +273,7 @@ func (h *confHandler) updateReplicationModeConfig(config *config.Config, key []s return err } -func (h *confHandler) updatePDServerConfig(config *config.Config, key string, value interface{}) error { +func (h *confHandler) updatePDServerConfig(config *config.Config, key string, value any) error { updated, found, err := jsonutil.AddKeyValue(&config.PDServerCfg, key, value) if err != nil { return err @@ -289,7 +289,7 @@ func (h *confHandler) updatePDServerConfig(config *config.Config, key string, va return err } -func (h *confHandler) updateLogLevel(kp []string, value interface{}) error { +func (h *confHandler) updateLogLevel(kp []string, value any) error { if len(kp) != 2 || kp[1] != "level" { return errors.Errorf("only support changing log level") } @@ -304,7 +304,7 @@ func (h *confHandler) updateLogLevel(kp []string, value interface{}) error { return errors.Errorf("input value %v is illegal", value) } -func (h *confHandler) updateClusterVersion(value interface{}) error { +func (h *confHandler) updateClusterVersion(value any) error { if version, ok := value.(string); ok { err := h.svr.SetClusterVersion(version) if err != nil { @@ -315,13 +315,13 @@ func (h *confHandler) updateClusterVersion(value interface{}) error { return errors.Errorf("input value %v is illegal", value) } -func getConfigMap(cfg map[string]interface{}, key []string, value interface{}) map[string]interface{} { +func getConfigMap(cfg map[string]any, key []string, value any) map[string]any { if len(key) == 1 { cfg[key[0]] = value return cfg } - subConfig := make(map[string]interface{}) + subConfig := make(map[string]any) cfg[key[0]] = getConfigMap(subConfig, key[1:], value) return cfg } @@ -366,7 +366,7 @@ func (h *confHandler) SetScheduleConfig(w http.ResponseWriter, r *http.Request) return } - conf := make(map[string]interface{}) + conf := make(map[string]any) if err := json.Unmarshal(data, &conf); err != nil { h.rd.JSON(w, http.StatusBadRequest, err.Error()) return diff --git a/server/api/diagnostic_test.go b/server/api/diagnostic_test.go index 8ba77f1267d..c98717902c5 100644 --- a/server/api/diagnostic_test.go +++ b/server/api/diagnostic_test.go @@ -84,7 +84,7 @@ func (suite *diagnosticTestSuite) TestSchedulerDiagnosticAPI() { re.NoError(tu.ReadGetJSON(re, testDialClient, addr, cfg)) re.True(cfg.Schedule.EnableDiagnostic) - ms := map[string]interface{}{ + ms := map[string]any{ "enable-diagnostic": "true", "max-replicas": 1, } @@ -104,7 +104,7 @@ func (suite *diagnosticTestSuite) TestSchedulerDiagnosticAPI() { evictLeaderURL := suite.urlPrefix + "/" + schedulers.EvictLeaderName re.NoError(tu.CheckGetJSON(testDialClient, evictLeaderURL, nil, tu.StatusNotOK(re))) - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = schedulers.BalanceRegionName body, err := json.Marshal(input) re.NoError(err) @@ -112,7 +112,7 @@ func (suite *diagnosticTestSuite) TestSchedulerDiagnosticAPI() { re.NoError(err) suite.checkStatus("pending", balanceRegionURL) - input = make(map[string]interface{}) + input = make(map[string]any) input["delay"] = 30 pauseArgs, err := json.Marshal(input) re.NoError(err) diff --git a/server/api/member.go b/server/api/member.go index df8c0aee622..a3688ef458c 100644 --- a/server/api/member.go +++ b/server/api/member.go @@ -238,7 +238,7 @@ func (h *memberHandler) SetMemberPropertyByName(w http.ResponseWriter, r *http.R return } - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { return } diff --git a/server/api/operator.go b/server/api/operator.go index 049a343d3bd..f7b82b27552 100644 --- a/server/api/operator.go +++ b/server/api/operator.go @@ -112,7 +112,7 @@ func (h *operatorHandler) GetOperators(w http.ResponseWriter, r *http.Request) { // @Failure 500 {string} string "PD server failed to proceed the request." // @Router /operators [post] func (h *operatorHandler) CreateOperator(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.r, w, r.Body, &input); err != nil { return } diff --git a/server/api/region.go b/server/api/region.go index e3abebb4bb0..28249629db5 100644 --- a/server/api/region.go +++ b/server/api/region.go @@ -631,7 +631,7 @@ func (h *regionsHandler) GetTopCPURegions(w http.ResponseWriter, r *http.Request // @Failure 400 {string} string "The input is invalid." // @Router /regions/accelerate-schedule [post] func (h *regionsHandler) AccelerateRegionsScheduleInRange(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { return } @@ -666,7 +666,7 @@ func (h *regionsHandler) AccelerateRegionsScheduleInRange(w http.ResponseWriter, // @Failure 400 {string} string "The input is invalid." // @Router /regions/accelerate-schedule/batch [post] func (h *regionsHandler) AccelerateRegionsScheduleInRanges(w http.ResponseWriter, r *http.Request) { - var input []map[string]interface{} + var input []map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { return } @@ -728,7 +728,7 @@ func (h *regionsHandler) GetTopNRegions(w http.ResponseWriter, r *http.Request, // @Failure 400 {string} string "The input is invalid." // @Router /regions/scatter [post] func (h *regionsHandler) ScatterRegions(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { return } @@ -767,7 +767,7 @@ func (h *regionsHandler) ScatterRegions(w http.ResponseWriter, r *http.Request) // @Failure 400 {string} string "The input is invalid." // @Router /regions/split [post] func (h *regionsHandler) SplitRegions(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { return } @@ -776,7 +776,7 @@ func (h *regionsHandler) SplitRegions(w http.ResponseWriter, r *http.Request) { h.rd.JSON(w, http.StatusBadRequest, "split_keys should be provided.") return } - rawSplitKeys := s.([]interface{}) + rawSplitKeys := s.([]any) if len(rawSplitKeys) < 1 { h.rd.JSON(w, http.StatusBadRequest, "empty split keys.") return @@ -804,13 +804,13 @@ func (h *RegionHeap) Less(i, j int) bool { return h.less(h.regions[i], h.regions func (h *RegionHeap) Swap(i, j int) { h.regions[i], h.regions[j] = h.regions[j], h.regions[i] } // Push pushes an element x onto the heap. -func (h *RegionHeap) Push(x interface{}) { +func (h *RegionHeap) Push(x any) { h.regions = append(h.regions, x.(*core.RegionInfo)) } // Pop removes the minimum element (according to Less) from the heap and returns // it. -func (h *RegionHeap) Pop() interface{} { +func (h *RegionHeap) Pop() any { pos := len(h.regions) - 1 x := h.regions[pos] h.regions = h.regions[:pos] diff --git a/server/api/region_label_test.go b/server/api/region_label_test.go index 811c83df678..1ed0997b8e7 100644 --- a/server/api/region_label_test.go +++ b/server/api/region_label_test.go @@ -108,10 +108,10 @@ func (suite *regionLabelTestSuite) TestGetSet() { re.Equal([]*labeler.LabelRule{rules[1], rules[2]}, resp) } -func makeKeyRanges(keys ...string) []interface{} { - var res []interface{} +func makeKeyRanges(keys ...string) []any { + var res []any for i := 0; i < len(keys); i += 2 { - res = append(res, map[string]interface{}{"start_key": keys[i], "end_key": keys[i+1]}) + res = append(res, map[string]any{"start_key": keys[i], "end_key": keys[i+1]}) } return res } diff --git a/server/api/region_test.go b/server/api/region_test.go index 55933376e57..5d4c3d51605 100644 --- a/server/api/region_test.go +++ b/server/api/region_test.go @@ -80,7 +80,7 @@ func (suite *regionTestSuite) TestRegion() { mustRegionHeartbeat(re, suite.svr, r) url := fmt.Sprintf("%s/region/id/%d", suite.urlPrefix, r.GetID()) r1 := &response.RegionInfo{} - r1m := make(map[string]interface{}) + r1m := make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, url, r1)) r1.Adjust() re.Equal(response.NewAPIRegionInfo(r), r1) @@ -89,7 +89,7 @@ func (suite *regionTestSuite) TestRegion() { re.Equal(float64(r.GetKeysWritten()), r1m["written_keys"].(float64)) re.Equal(float64(r.GetBytesRead()), r1m["read_bytes"].(float64)) re.Equal(float64(r.GetKeysRead()), r1m["read_keys"].(float64)) - keys := r1m["buckets"].([]interface{}) + keys := r1m["buckets"].([]any) re.Len(keys, 2) re.Equal(core.HexRegionKeyStr([]byte("a")), keys[0].(string)) re.Equal(core.HexRegionKeyStr([]byte("b")), keys[1].(string)) diff --git a/server/api/router.go b/server/api/router.go index fc963d6a2f9..705e4da0959 100644 --- a/server/api/router.go +++ b/server/api/router.go @@ -71,7 +71,7 @@ func createIndentRender() *render.Render { }) } -func getFunctionName(f interface{}) string { +func getFunctionName(f any) string { strs := strings.Split(runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name(), ".") return strings.Split(strs[len(strs)-1], "-")[0] } diff --git a/server/api/scheduler.go b/server/api/scheduler.go index e28e852b006..8ecec7f721c 100644 --- a/server/api/scheduler.go +++ b/server/api/scheduler.go @@ -70,7 +70,7 @@ func (h *schedulerHandler) GetSchedulers(w http.ResponseWriter, r *http.Request) // @Failure 500 {string} string "PD server failed to proceed the request." // @Router /schedulers [post] func (h *schedulerHandler) CreateScheduler(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.r, w, r.Body, &input); err != nil { return } @@ -204,7 +204,7 @@ func (h *schedulerHandler) CreateScheduler(w http.ResponseWriter, r *http.Reques h.r.JSON(w, http.StatusOK, "The scheduler is created.") } -func (h *schedulerHandler) addEvictOrGrant(w http.ResponseWriter, input map[string]interface{}, name string) { +func (h *schedulerHandler) addEvictOrGrant(w http.ResponseWriter, input map[string]any, name string) { storeID, ok := input["store_id"].(float64) if !ok { h.r.JSON(w, http.StatusBadRequest, "missing store id") diff --git a/server/api/service_middleware.go b/server/api/service_middleware.go index 41d2f6601f0..5be15c81550 100644 --- a/server/api/service_middleware.go +++ b/server/api/service_middleware.go @@ -72,7 +72,7 @@ func (h *serviceMiddlewareHandler) SetServiceMiddlewareConfig(w http.ResponseWri return } - conf := make(map[string]interface{}) + conf := make(map[string]any) if err := json.Unmarshal(data, &conf); err != nil { h.rd.JSON(w, http.StatusBadRequest, err.Error()) return @@ -104,7 +104,7 @@ func (h *serviceMiddlewareHandler) SetServiceMiddlewareConfig(w http.ResponseWri h.rd.JSON(w, http.StatusOK, "The service-middleware config is updated.") } -func (h *serviceMiddlewareHandler) updateServiceMiddlewareConfig(cfg *config.ServiceMiddlewareConfig, key string, value interface{}) error { +func (h *serviceMiddlewareHandler) updateServiceMiddlewareConfig(cfg *config.ServiceMiddlewareConfig, key string, value any) error { kp := strings.Split(key, ".") switch kp[0] { case "audit": @@ -117,7 +117,7 @@ func (h *serviceMiddlewareHandler) updateServiceMiddlewareConfig(cfg *config.Ser return errors.Errorf("config prefix %s not found", kp[0]) } -func (h *serviceMiddlewareHandler) updateAudit(config *config.ServiceMiddlewareConfig, key string, value interface{}) error { +func (h *serviceMiddlewareHandler) updateAudit(config *config.ServiceMiddlewareConfig, key string, value any) error { updated, found, err := jsonutil.AddKeyValue(&config.AuditConfig, key, value) if err != nil { return err @@ -142,7 +142,7 @@ func (h *serviceMiddlewareHandler) updateAudit(config *config.ServiceMiddlewareC // @Failure 500 {string} string "config item not found" // @Router /service-middleware/config/rate-limit [POST] func (h *serviceMiddlewareHandler) SetRateLimitConfig(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { return } @@ -238,7 +238,7 @@ func (h *serviceMiddlewareHandler) SetRateLimitConfig(w http.ResponseWriter, r * // @Failure 500 {string} string "config item not found" // @Router /service-middleware/config/grpc-rate-limit [POST] func (h *serviceMiddlewareHandler) SetGRPCRateLimitConfig(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { return } diff --git a/server/api/service_middleware_test.go b/server/api/service_middleware_test.go index c4db58c39ae..7d5e0db98be 100644 --- a/server/api/service_middleware_test.go +++ b/server/api/service_middleware_test.go @@ -61,7 +61,7 @@ func (suite *auditMiddlewareTestSuite) TestConfigAuditSwitch() { re.NoError(tu.ReadGetJSON(re, testDialClient, addr, sc)) re.True(sc.EnableAudit) - ms := map[string]interface{}{ + ms := map[string]any{ "audit.enable-audit": "false", } postData, err := json.Marshal(ms) @@ -70,7 +70,7 @@ func (suite *auditMiddlewareTestSuite) TestConfigAuditSwitch() { sc = &config.ServiceMiddlewareConfig{} re.NoError(tu.ReadGetJSON(re, testDialClient, addr, sc)) re.False(sc.EnableAudit) - ms = map[string]interface{}{ + ms = map[string]any{ "enable-audit": "true", } postData, err = json.Marshal(ms) @@ -81,25 +81,25 @@ func (suite *auditMiddlewareTestSuite) TestConfigAuditSwitch() { re.True(sc.EnableAudit) // test empty - ms = map[string]interface{}{} + ms = map[string]any{} postData, err = json.Marshal(ms) re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re), tu.StringContain(re, "The input is empty."))) - ms = map[string]interface{}{ + ms = map[string]any{ "audit": "false", } postData, err = json.Marshal(ms) re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "config item audit not found"))) re.NoError(failpoint.Enable("github.com/tikv/pd/server/config/persistServiceMiddlewareFail", "return(true)")) - ms = map[string]interface{}{ + ms = map[string]any{ "audit.enable-audit": "false", } postData, err = json.Marshal(ms) re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(re, http.StatusBadRequest))) re.NoError(failpoint.Disable("github.com/tikv/pd/server/config/persistServiceMiddlewareFail")) - ms = map[string]interface{}{ + ms = map[string]any{ "audit.audit": "false", } postData, err = json.Marshal(ms) @@ -135,7 +135,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { urlPrefix := fmt.Sprintf("%s%s/api/v1/service-middleware/config/rate-limit", suite.svr.GetAddr(), apiPrefix) // test empty type - input := make(map[string]interface{}) + input := make(map[string]any) input["type"] = 123 jsonBody, err := json.Marshal(input) re.NoError(err) @@ -143,7 +143,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "\"The type is empty.\"\n")) re.NoError(err) // test invalid type - input = make(map[string]interface{}) + input = make(map[string]any) input["type"] = "url" jsonBody, err = json.Marshal(input) re.NoError(err) @@ -152,7 +152,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { re.NoError(err) // test empty label - input = make(map[string]interface{}) + input = make(map[string]any) input["type"] = "label" input["label"] = "" jsonBody, err = json.Marshal(input) @@ -161,7 +161,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "\"The label is empty.\"\n")) re.NoError(err) // test no label matched - input = make(map[string]interface{}) + input = make(map[string]any) input["type"] = "label" input["label"] = "TestLabel" jsonBody, err = json.Marshal(input) @@ -171,7 +171,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { re.NoError(err) // test empty path - input = make(map[string]interface{}) + input = make(map[string]any) input["type"] = "path" input["path"] = "" jsonBody, err = json.Marshal(input) @@ -181,7 +181,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { re.NoError(err) // test path but no label matched - input = make(map[string]interface{}) + input = make(map[string]any) input["type"] = "path" input["path"] = "/pd/api/v1/test" jsonBody, err = json.Marshal(input) @@ -191,7 +191,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { re.NoError(err) // no change - input = make(map[string]interface{}) + input = make(map[string]any) input["type"] = "label" input["label"] = "GetHealthStatus" jsonBody, err = json.Marshal(input) @@ -201,7 +201,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { re.NoError(err) // change concurrency - input = make(map[string]interface{}) + input = make(map[string]any) input["type"] = "path" input["path"] = "/pd/api/v1/health" input["method"] = http.MethodGet @@ -219,7 +219,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { re.NoError(err) // change qps - input = make(map[string]interface{}) + input = make(map[string]any) input["type"] = "path" input["path"] = "/pd/api/v1/health" input["method"] = http.MethodGet @@ -230,7 +230,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { tu.StatusOK(re), tu.StringContain(re, "QPS rate limiter is changed.")) re.NoError(err) - input = make(map[string]interface{}) + input = make(map[string]any) input["type"] = "path" input["path"] = "/pd/api/v1/health" input["method"] = http.MethodGet @@ -250,7 +250,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { re.NoError(err) // change both - input = make(map[string]interface{}) + input = make(map[string]any) input["type"] = "path" input["path"] = "/pd/api/v1/debug/pprof/profile" input["qps"] = 100 @@ -272,7 +272,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateRateLimitConfig() { limiter.Update("SetRateLimitConfig", ratelimit.AddLabelAllowList()) // Allow list - input = make(map[string]interface{}) + input = make(map[string]any) input["type"] = "label" input["label"] = "SetRateLimitConfig" input["qps"] = 100 @@ -289,7 +289,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateGRPCRateLimitConfig() { re := suite.Require() // test empty label - input := make(map[string]interface{}) + input := make(map[string]any) input["label"] = "" jsonBody, err := json.Marshal(input) re.NoError(err) @@ -297,7 +297,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateGRPCRateLimitConfig() { tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "\"The label is empty.\"\n")) re.NoError(err) // test no label matched - input = make(map[string]interface{}) + input = make(map[string]any) input["label"] = "TestLabel" jsonBody, err = json.Marshal(input) re.NoError(err) @@ -306,7 +306,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateGRPCRateLimitConfig() { re.NoError(err) // no change - input = make(map[string]interface{}) + input = make(map[string]any) input["label"] = "StoreHeartbeat" jsonBody, err = json.Marshal(input) re.NoError(err) @@ -315,7 +315,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateGRPCRateLimitConfig() { re.NoError(err) // change concurrency - input = make(map[string]interface{}) + input = make(map[string]any) input["label"] = "StoreHeartbeat" input["concurrency"] = 100 jsonBody, err = json.Marshal(input) @@ -331,7 +331,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateGRPCRateLimitConfig() { re.NoError(err) // change qps - input = make(map[string]interface{}) + input = make(map[string]any) input["label"] = "StoreHeartbeat" input["qps"] = 100 jsonBody, err = json.Marshal(input) @@ -340,7 +340,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateGRPCRateLimitConfig() { tu.StatusOK(re), tu.StringContain(re, "QPS rate limiter is changed.")) re.NoError(err) - input = make(map[string]interface{}) + input = make(map[string]any) input["label"] = "StoreHeartbeat" input["qps"] = 0.3 jsonBody, err = json.Marshal(input) @@ -358,7 +358,7 @@ func (suite *rateLimitConfigTestSuite) TestUpdateGRPCRateLimitConfig() { re.NoError(err) // change both - input = make(map[string]interface{}) + input = make(map[string]any) input["label"] = "GetStore" input["qps"] = 100 input["concurrency"] = 100 @@ -384,7 +384,7 @@ func (suite *rateLimitConfigTestSuite) TestConfigRateLimitSwitch() { re.True(sc.RateLimitConfig.EnableRateLimit) re.True(sc.GRPCRateLimitConfig.EnableRateLimit) - ms := map[string]interface{}{ + ms := map[string]any{ "enable-rate-limit": "false", "enable-grpc-rate-limit": "false", } @@ -395,7 +395,7 @@ func (suite *rateLimitConfigTestSuite) TestConfigRateLimitSwitch() { re.NoError(tu.ReadGetJSON(re, testDialClient, addr, sc)) re.False(sc.RateLimitConfig.EnableRateLimit) re.False(sc.GRPCRateLimitConfig.EnableRateLimit) - ms = map[string]interface{}{ + ms = map[string]any{ "enable-rate-limit": "true", "enable-grpc-rate-limit": "true", } @@ -408,18 +408,18 @@ func (suite *rateLimitConfigTestSuite) TestConfigRateLimitSwitch() { re.True(sc.GRPCRateLimitConfig.EnableRateLimit) // test empty - ms = map[string]interface{}{} + ms = map[string]any{} postData, err = json.Marshal(ms) re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re), tu.StringContain(re, "The input is empty."))) - ms = map[string]interface{}{ + ms = map[string]any{ "rate-limit": "false", } postData, err = json.Marshal(ms) re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "config item rate-limit not found"))) re.NoError(failpoint.Enable("github.com/tikv/pd/server/config/persistServiceMiddlewareFail", "return(true)")) - ms = map[string]interface{}{ + ms = map[string]any{ "rate-limit.enable-rate-limit": "false", "grpc-rate-limit.enable-grpc-rate-limit": "false", } @@ -427,7 +427,7 @@ func (suite *rateLimitConfigTestSuite) TestConfigRateLimitSwitch() { re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, addr, postData, tu.Status(re, http.StatusBadRequest))) re.NoError(failpoint.Disable("github.com/tikv/pd/server/config/persistServiceMiddlewareFail")) - ms = map[string]interface{}{ + ms = map[string]any{ "rate-limit.rate-limit": "false", } postData, err = json.Marshal(ms) @@ -440,10 +440,10 @@ func (suite *rateLimitConfigTestSuite) TestConfigLimiterConfigByOriginAPI() { // this test case is used to test updating `limiter-config` by origin API simply addr := fmt.Sprintf("%s/service-middleware/config", suite.urlPrefix) dimensionConfig := ratelimit.DimensionConfig{QPS: 1} - limiterConfig := map[string]interface{}{ + limiterConfig := map[string]any{ "CreateOperator": dimensionConfig, } - ms := map[string]interface{}{ + ms := map[string]any{ "limiter-config": limiterConfig, } postData, err := json.Marshal(ms) diff --git a/server/api/store.go b/server/api/store.go index a3bd52bb6a6..1d0da0e9825 100644 --- a/server/api/store.go +++ b/server/api/store.go @@ -258,7 +258,7 @@ func (h *storeHandler) SetStoreWeight(w http.ResponseWriter, r *http.Request) { return } - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { return } @@ -318,7 +318,7 @@ func (h *storeHandler) SetStoreLimit(w http.ResponseWriter, r *http.Request) { return } - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { return } @@ -405,7 +405,7 @@ func (h *storesHandler) RemoveTombStone(w http.ResponseWriter, r *http.Request) // @Failure 500 {string} string "PD server failed to proceed the request." // @Router /stores/limit [post] func (h *storesHandler) SetAllStoresLimit(w http.ResponseWriter, r *http.Request) { - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { return } @@ -452,7 +452,7 @@ func (h *storesHandler) SetAllStoresLimit(w http.ResponseWriter, r *http.Request } } } else { - labelMap := input["labels"].(map[string]interface{}) + labelMap := input["labels"].(map[string]any) labels := make([]*metapb.StoreLabel, 0, len(input)) for k, v := range labelMap { labels = append(labels, &metapb.StoreLabel{ @@ -744,7 +744,7 @@ func (filter *storeStateFilter) filter(stores []*metapb.Store) []*metapb.Store { return ret } -func getStoreLimitType(input map[string]interface{}) ([]storelimit.Type, error) { +func getStoreLimitType(input map[string]any) ([]storelimit.Type, error) { typeNameIface, ok := input["type"] var err error if ok { diff --git a/server/api/store_test.go b/server/api/store_test.go index fc1bbc3c902..24d541dbf7c 100644 --- a/server/api/store_test.go +++ b/server/api/store_test.go @@ -510,7 +510,7 @@ func (suite *storeTestSuite) TestGetAllLimit() { re := suite.Require() for _, testCase := range testCases { suite.T().Logf(testCase.name) - info := make(map[uint64]interface{}, 4) + info := make(map[uint64]any, 4) err := tu.ReadGetJSON(re, testDialClient, testCase.url, &info) re.NoError(err) re.Len(info, len(testCase.expectedStores)) @@ -525,7 +525,7 @@ func (suite *storeTestSuite) TestStoreLimitTTL() { re := suite.Require() // add peer url := fmt.Sprintf("%s/store/1/limit?ttlSecond=%v", suite.urlPrefix, 5) - data := map[string]interface{}{ + data := map[string]any{ "type": "add-peer", "rate": 999, } @@ -534,7 +534,7 @@ func (suite *storeTestSuite) TestStoreLimitTTL() { err = tu.CheckPostJSON(testDialClient, url, postData, tu.StatusOK(re)) re.NoError(err) // remove peer - data = map[string]interface{}{ + data = map[string]any{ "type": "remove-peer", "rate": 998, } @@ -544,7 +544,7 @@ func (suite *storeTestSuite) TestStoreLimitTTL() { re.NoError(err) // all store limit add peer url = fmt.Sprintf("%s/stores/limit?ttlSecond=%v", suite.urlPrefix, 3) - data = map[string]interface{}{ + data = map[string]any{ "type": "add-peer", "rate": 997, } @@ -553,7 +553,7 @@ func (suite *storeTestSuite) TestStoreLimitTTL() { err = tu.CheckPostJSON(testDialClient, url, postData, tu.StatusOK(re)) re.NoError(err) // all store limit remove peer - data = map[string]interface{}{ + data = map[string]any{ "type": "remove-peer", "rate": 996, } diff --git a/server/api/unsafe_operation.go b/server/api/unsafe_operation.go index 11fd59933eb..b60afbf19d5 100644 --- a/server/api/unsafe_operation.go +++ b/server/api/unsafe_operation.go @@ -46,7 +46,7 @@ func newUnsafeOperationHandler(svr *server.Server, rd *render.Render) *unsafeOpe // @Router /admin/unsafe/remove-failed-stores [POST] func (h *unsafeOperationHandler) RemoveFailedStores(w http.ResponseWriter, r *http.Request) { rc := getCluster(r) - var input map[string]interface{} + var input map[string]any if err := apiutil.ReadJSONRespondError(h.rd, w, r.Body, &input); err != nil { h.rd.JSON(w, http.StatusBadRequest, err.Error()) return diff --git a/server/api/unsafe_operation_test.go b/server/api/unsafe_operation_test.go index 37c1506f6a7..e708a93abfc 100644 --- a/server/api/unsafe_operation_test.go +++ b/server/api/unsafe_operation_test.go @@ -56,25 +56,25 @@ func (suite *unsafeOperationTestSuite) TearDownTest() { func (suite *unsafeOperationTestSuite) TestRemoveFailedStores() { re := suite.Require() - input := map[string]interface{}{"stores": []uint64{}} + input := map[string]any{"stores": []uint64{}} data, _ := json.Marshal(input) err := tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/remove-failed-stores", data, tu.StatusNotOK(re), tu.StringEqual(re, "\"[PD:unsaferecovery:ErrUnsafeRecoveryInvalidInput]invalid input no store specified\"\n")) re.NoError(err) - input = map[string]interface{}{"stores": []string{"abc", "def"}} + input = map[string]any{"stores": []string{"abc", "def"}} data, _ = json.Marshal(input) err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/remove-failed-stores", data, tu.StatusNotOK(re), tu.StringEqual(re, "\"Store ids are invalid\"\n")) re.NoError(err) - input = map[string]interface{}{"stores": []uint64{1, 2}} + input = map[string]any{"stores": []uint64{1, 2}} data, _ = json.Marshal(input) err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/remove-failed-stores", data, tu.StatusNotOK(re), tu.StringEqual(re, "\"[PD:unsaferecovery:ErrUnsafeRecoveryInvalidInput]invalid input store 2 doesn't exist\"\n")) re.NoError(err) - input = map[string]interface{}{"stores": []uint64{1}} + input = map[string]any{"stores": []uint64{1}} data, _ = json.Marshal(input) err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/remove-failed-stores", data, tu.StatusOK(re)) re.NoError(err) @@ -88,13 +88,13 @@ func (suite *unsafeOperationTestSuite) TestRemoveFailedStores() { func (suite *unsafeOperationTestSuite) TestRemoveFailedStoresAutoDetect() { re := suite.Require() - input := map[string]interface{}{"auto-detect": false} + input := map[string]any{"auto-detect": false} data, _ := json.Marshal(input) err := tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/remove-failed-stores", data, tu.StatusNotOK(re), tu.StringEqual(re, "\"Store ids are invalid\"\n")) re.NoError(err) - input = map[string]interface{}{"auto-detect": true} + input = map[string]any{"auto-detect": true} data, _ = json.Marshal(input) err = tu.CheckPostJSON(testDialClient, suite.urlPrefix+"/remove-failed-stores", data, tu.StatusOK(re)) re.NoError(err) diff --git a/server/cluster/cluster.go b/server/cluster/cluster.go index abb8af80a92..350a7fd5e91 100644 --- a/server/cluster/cluster.go +++ b/server/cluster/cluster.go @@ -1846,7 +1846,7 @@ func getStoreTopoWeight(store *core.StoreInfo, stores []*core.StoreInfo, locatio if slice.Contains(validLabels, label.Key) { weight /= float64(len(topo)) } - topo = topo[label.Value].(map[string]interface{}) + topo = topo[label.Value].(map[string]any) } else { break } @@ -1855,8 +1855,8 @@ func getStoreTopoWeight(store *core.StoreInfo, stores []*core.StoreInfo, locatio return weight / sameLocationStoreNum } -func buildTopology(s *core.StoreInfo, stores []*core.StoreInfo, locationLabels []string, count int) (map[string]interface{}, []string, float64, bool) { - topology := make(map[string]interface{}) +func buildTopology(s *core.StoreInfo, stores []*core.StoreInfo, locationLabels []string, count int) (map[string]any, []string, float64, bool) { + topology := make(map[string]any) sameLocationStoreNum := 1.0 totalLabelCount := make([]int, len(locationLabels)) for _, store := range stores { @@ -1913,7 +1913,7 @@ func getSortedLabels(storeLabels []*metapb.StoreLabel, locationLabels []string) } // updateTopology records stores' topology in the `topology` variable. -func updateTopology(topology map[string]interface{}, sortedLabels []*metapb.StoreLabel) []int { +func updateTopology(topology map[string]any, sortedLabels []*metapb.StoreLabel) []int { labelCount := make([]int, len(sortedLabels)) if len(sortedLabels) == 0 { return labelCount @@ -1921,10 +1921,10 @@ func updateTopology(topology map[string]interface{}, sortedLabels []*metapb.Stor topo := topology for i, l := range sortedLabels { if _, exist := topo[l.Value]; !exist { - topo[l.Value] = make(map[string]interface{}) + topo[l.Value] = make(map[string]any) labelCount[i] += 1 } - topo = topo[l.Value].(map[string]interface{}) + topo = topo[l.Value].(map[string]any) } return labelCount } diff --git a/server/cluster/cluster_test.go b/server/cluster/cluster_test.go index cc913426ed4..11c2c8c7836 100644 --- a/server/cluster/cluster_test.go +++ b/server/cluster/cluster_test.go @@ -2660,7 +2660,7 @@ func TestCheckRegionWithScheduleDeny(t *testing.T) { ID: "schedulelabel", Labels: []labeler.RegionLabel{{Key: "schedule", Value: "deny"}}, RuleType: labeler.KeyRange, - Data: []interface{}{map[string]interface{}{"start_key": "", "end_key": ""}}, + Data: []any{map[string]any{"start_key": "", "end_key": ""}}, }) // should allow to do rule checker @@ -3038,7 +3038,7 @@ func TestAddScheduler(t *testing.T) { re.NoError(err) conf, err := bl.EncodeConfig() re.NoError(err) - data := make(map[string]interface{}) + data := make(map[string]any) err = json.Unmarshal(conf, &data) re.NoError(err) batch := data["batch"].(float64) @@ -3056,7 +3056,7 @@ func TestAddScheduler(t *testing.T) { re.NoError(err) conf, err = hb.EncodeConfig() re.NoError(err) - data = make(map[string]interface{}) + data = make(map[string]any) re.NoError(json.Unmarshal(conf, &data)) re.Contains(data, "enable-for-tiflash") re.Equal("true", data["enable-for-tiflash"].(string)) diff --git a/server/gc_service.go b/server/gc_service.go index 90333654e5e..db3879a74fb 100644 --- a/server/gc_service.go +++ b/server/gc_service.go @@ -35,7 +35,7 @@ import ( // GetGCSafePointV2 return gc safe point for the given keyspace. func (s *GrpcServer) GetGCSafePointV2(ctx context.Context, request *pdpb.GetGCSafePointV2Request) (*pdpb.GetGCSafePointV2Response, error) { - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).GetGCSafePointV2(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -60,7 +60,7 @@ func (s *GrpcServer) GetGCSafePointV2(ctx context.Context, request *pdpb.GetGCSa // UpdateGCSafePointV2 update gc safe point for the given keyspace. func (s *GrpcServer) UpdateGCSafePointV2(ctx context.Context, request *pdpb.UpdateGCSafePointV2Request) (*pdpb.UpdateGCSafePointV2Response, error) { - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).UpdateGCSafePointV2(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -97,7 +97,7 @@ func (s *GrpcServer) UpdateGCSafePointV2(ctx context.Context, request *pdpb.Upda // UpdateServiceSafePointV2 update service safe point for the given keyspace. func (s *GrpcServer) UpdateServiceSafePointV2(ctx context.Context, request *pdpb.UpdateServiceSafePointV2Request) (*pdpb.UpdateServiceSafePointV2Response, error) { - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).UpdateServiceSafePointV2(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -194,7 +194,7 @@ func (s *GrpcServer) WatchGCSafePointV2(request *pdpb.WatchGCSafePointV2Request, // GetAllGCSafePointV2 return all gc safe point v2. func (s *GrpcServer) GetAllGCSafePointV2(ctx context.Context, request *pdpb.GetAllGCSafePointV2Request) (*pdpb.GetAllGCSafePointV2Response, error) { - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).GetAllGCSafePointV2(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { diff --git a/server/grpc_service.go b/server/grpc_service.go index 54df54832f1..0dbdcc8532f 100644 --- a/server/grpc_service.go +++ b/server/grpc_service.go @@ -232,14 +232,14 @@ type request interface { GetHeader() *pdpb.RequestHeader } -type forwardFn func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) +type forwardFn func(ctx context.Context, client *grpc.ClientConn) (any, error) -func (s *GrpcServer) unaryMiddleware(ctx context.Context, req request, fn forwardFn) (rsp interface{}, err error) { +func (s *GrpcServer) unaryMiddleware(ctx context.Context, req request, fn forwardFn) (rsp any, err error) { return s.unaryFollowerMiddleware(ctx, req, fn, nil) } // unaryFollowerMiddleware adds the check of followers enable compared to unaryMiddleware. -func (s *GrpcServer) unaryFollowerMiddleware(ctx context.Context, req request, fn forwardFn, allowFollower *bool) (rsp interface{}, err error) { +func (s *GrpcServer) unaryFollowerMiddleware(ctx context.Context, req request, fn forwardFn, allowFollower *bool) (rsp any, err error) { failpoint.Inject("customTimeout", func() { time.Sleep(5 * time.Second) }) @@ -301,7 +301,7 @@ func (s *GrpcServer) GetMinTS( }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).GetMinTS(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -606,7 +606,7 @@ func (s *GrpcServer) Bootstrap(ctx context.Context, request *pdpb.BootstrapReque }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).Bootstrap(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -650,7 +650,7 @@ func (s *GrpcServer) IsBootstrapped(ctx context.Context, request *pdpb.IsBootstr }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).IsBootstrapped(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -679,7 +679,7 @@ func (s *GrpcServer) AllocID(ctx context.Context, request *pdpb.AllocIDRequest) }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).AllocID(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -741,7 +741,7 @@ func (s *GrpcServer) GetStore(ctx context.Context, request *pdpb.GetStoreRequest }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).GetStore(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -797,7 +797,7 @@ func (s *GrpcServer) PutStore(ctx context.Context, request *pdpb.PutStoreRequest }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).PutStore(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -854,7 +854,7 @@ func (s *GrpcServer) GetAllStores(ctx context.Context, request *pdpb.GetAllStore }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).GetAllStores(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -899,7 +899,7 @@ func (s *GrpcServer) StoreHeartbeat(ctx context.Context, request *pdpb.StoreHear }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).StoreHeartbeat(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -1403,7 +1403,7 @@ func (s *GrpcServer) GetRegion(ctx context.Context, request *pdpb.GetRegionReque }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).GetRegion(ctx, request) } followerHandle := new(bool) @@ -1464,7 +1464,7 @@ func (s *GrpcServer) GetPrevRegion(ctx context.Context, request *pdpb.GetRegionR }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).GetPrevRegion(ctx, request) } followerHandle := new(bool) @@ -1523,7 +1523,7 @@ func (s *GrpcServer) GetRegionByID(ctx context.Context, request *pdpb.GetRegionB }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).GetRegionByID(ctx, request) } followerHandle := new(bool) @@ -1584,7 +1584,7 @@ func (s *GrpcServer) ScanRegions(ctx context.Context, request *pdpb.ScanRegionsR }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).ScanRegions(ctx, request) } followerHandle := new(bool) @@ -1642,7 +1642,7 @@ func (s *GrpcServer) AskSplit(ctx context.Context, request *pdpb.AskSplitRequest }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).AskSplit(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -1717,7 +1717,7 @@ func (s *GrpcServer) AskBatchSplit(ctx context.Context, request *pdpb.AskBatchSp return s.convertAskSplitResponse(resp), nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).AskBatchSplit(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -1770,7 +1770,7 @@ func (s *GrpcServer) ReportSplit(ctx context.Context, request *pdpb.ReportSplitR }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).ReportSplit(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -1808,7 +1808,7 @@ func (s *GrpcServer) ReportBatchSplit(ctx context.Context, request *pdpb.ReportB }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).ReportBatchSplit(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -1847,7 +1847,7 @@ func (s *GrpcServer) GetClusterConfig(ctx context.Context, request *pdpb.GetClus }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).GetClusterConfig(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -1879,7 +1879,7 @@ func (s *GrpcServer) PutClusterConfig(ctx context.Context, request *pdpb.PutClus }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).PutClusterConfig(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -1963,7 +1963,7 @@ func (s *GrpcServer) ScatterRegion(ctx context.Context, request *pdpb.ScatterReg } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).ScatterRegion(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -2034,7 +2034,7 @@ func (s *GrpcServer) GetGCSafePoint(ctx context.Context, request *pdpb.GetGCSafe }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).GetGCSafePoint(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -2093,7 +2093,7 @@ func (s *GrpcServer) UpdateGCSafePoint(ctx context.Context, request *pdpb.Update }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).UpdateGCSafePoint(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -2142,7 +2142,7 @@ func (s *GrpcServer) UpdateServiceGCSafePoint(ctx context.Context, request *pdpb }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).UpdateServiceGCSafePoint(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -2224,7 +2224,7 @@ func (s *GrpcServer) GetOperator(ctx context.Context, request *pdpb.GetOperatorR return s.convertOperatorResponse(resp), nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).GetOperator(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -2545,7 +2545,7 @@ func (s *GrpcServer) SplitRegions(ctx context.Context, request *pdpb.SplitRegion } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).SplitRegions(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -2581,7 +2581,7 @@ func (s *GrpcServer) SplitAndScatterRegions(ctx context.Context, request *pdpb.S }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).SplitAndScatterRegions(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -2907,7 +2907,7 @@ func (s *GrpcServer) ReportMinResolvedTS(ctx context.Context, request *pdpb.Repo }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).ReportMinResolvedTS(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -2947,7 +2947,7 @@ func (s *GrpcServer) SetExternalTimestamp(ctx context.Context, request *pdpb.Set }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).SetExternalTimestamp(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { @@ -2985,7 +2985,7 @@ func (s *GrpcServer) GetExternalTimestamp(ctx context.Context, request *pdpb.Get }, nil } } - fn := func(ctx context.Context, client *grpc.ClientConn) (interface{}, error) { + fn := func(ctx context.Context, client *grpc.ClientConn) (any, error) { return pdpb.NewPDClient(client).GetExternalTimestamp(ctx, request) } if rsp, err := s.unaryMiddleware(ctx, request, fn); err != nil { diff --git a/server/handler.go b/server/handler.go index b91c8e368f9..7c840eabe60 100644 --- a/server/handler.go +++ b/server/handler.go @@ -495,7 +495,7 @@ func (h *Handler) GetAddr() string { // SetStoreLimitTTL set storeLimit with ttl func (h *Handler) SetStoreLimitTTL(data string, value float64, ttl time.Duration) error { - return h.s.SaveTTLConfig(map[string]interface{}{ + return h.s.SaveTTLConfig(map[string]any{ data: value, }, ttl) } @@ -568,7 +568,7 @@ func (h *Handler) GetHistoryHotRegionIter( // RedirectSchedulerUpdate update scheduler config. Export this func to help handle damaged store. func (h *Handler) redirectSchedulerUpdate(name string, storeID float64) error { - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = name input["store_id"] = storeID updateURL, err := url.JoinPath(h.GetAddr(), "pd", SchedulerConfigHandlerPath, name, "config") diff --git a/server/server.go b/server/server.go index 0e9c3d84074..4d26b0bd079 100644 --- a/server/server.go +++ b/server/server.go @@ -1176,7 +1176,7 @@ func (s *Server) UpdateRateLimitConfig(key, label string, value ratelimit.Dimens } // UpdateRateLimit is used to update rate-limit config which will overwrite limiter-config -func (s *Server) UpdateRateLimit(cfg *config.RateLimitConfig, key string, value interface{}) error { +func (s *Server) UpdateRateLimit(cfg *config.RateLimitConfig, key string, value any) error { updated, found, err := jsonutil.AddKeyValue(cfg, key, value) if err != nil { return err @@ -1225,7 +1225,7 @@ func (s *Server) UpdateGRPCRateLimitConfig(key, label string, value ratelimit.Di } // UpdateGRPCRateLimit is used to update gRPC rate-limit config which will overwrite limiter-config -func (s *Server) UpdateGRPCRateLimit(cfg *config.GRPCRateLimitConfig, key string, value interface{}) error { +func (s *Server) UpdateGRPCRateLimit(cfg *config.GRPCRateLimitConfig, key string, value any) error { updated, found, err := jsonutil.AddKeyValue(cfg, key, value) if err != nil { return err @@ -1924,7 +1924,7 @@ func (s *Server) PersistFile(name string, data []byte) error { } // SaveTTLConfig save ttl config -func (s *Server) SaveTTLConfig(data map[string]interface{}, ttl time.Duration) error { +func (s *Server) SaveTTLConfig(data map[string]any, ttl time.Duration) error { for k := range data { if !config.IsSupportedTTLConfig(k) { return fmt.Errorf("unsupported ttl config %s", k) diff --git a/tests/cluster.go b/tests/cluster.go index 41efc2b045d..3b798f8738a 100644 --- a/tests/cluster.go +++ b/tests/cluster.go @@ -551,7 +551,7 @@ func restartTestCluster( } wg.Wait() - errorMap.Range(func(key, value interface{}) bool { + errorMap.Range(func(key, value any) bool { if value != nil { err = value.(error) return false diff --git a/tests/dashboard/service_test.go b/tests/dashboard/service_test.go index 47857629328..a59420a93b7 100644 --- a/tests/dashboard/service_test.go +++ b/tests/dashboard/service_test.go @@ -148,7 +148,7 @@ func (suite *dashboardTestSuite) testDashboard(re *require.Assertions, internalP } } - input := map[string]interface{}{ + input := map[string]any{ "dashboard-address": dashboardAddress2, } data, err := json.Marshal(input) @@ -161,7 +161,7 @@ func (suite *dashboardTestSuite) testDashboard(re *require.Assertions, internalP re.Equal(dashboardAddress2, leader.GetServer().GetPersistOptions().GetDashboardAddress()) // pd-ctl set stop - input = map[string]interface{}{ + input = map[string]any{ "dashboard-address": "none", } data, err = json.Marshal(input) diff --git a/tests/integrations/client/client_test.go b/tests/integrations/client/client_test.go index 07e5c65d286..cfb896878f2 100644 --- a/tests/integrations/client/client_test.go +++ b/tests/integrations/client/client_test.go @@ -498,7 +498,7 @@ type TSOAllocatorsGetter interface{ GetTSOAllocators() *sync.Map } func getTSOAllocatorServingEndpointURLs(c TSOAllocatorsGetter) map[string]string { allocatorLeaders := make(map[string]string) - c.GetTSOAllocators().Range(func(dcLocation, url interface{}) bool { + c.GetTSOAllocators().Range(func(dcLocation, url any) bool { allocatorLeaders[dcLocation.(string)] = url.(string) return true }) @@ -884,7 +884,7 @@ func TestConfigTTLAfterTransferLeader(t *testing.T) { leader := cluster.GetServer(cluster.WaitLeader()) re.NoError(leader.BootstrapCluster()) addr := fmt.Sprintf("%s/pd/api/v1/config?ttlSecond=5", leader.GetAddr()) - postData, err := json.Marshal(map[string]interface{}{ + postData, err := json.Marshal(map[string]any{ "schedule.max-snapshot-count": 999, "schedule.enable-location-replacement": false, "schedule.max-merge-region-size": 999, diff --git a/tests/integrations/client/http_client_test.go b/tests/integrations/client/http_client_test.go index 4961fb9b90a..4fe6b955c5d 100644 --- a/tests/integrations/client/http_client_test.go +++ b/tests/integrations/client/http_client_test.go @@ -487,9 +487,9 @@ func (suite *httpClientTestSuite) checkConfig(mode mode, client pd.Client) { config, err := client.GetConfig(env.ctx) re.NoError(err) - re.Equal(float64(4), config["schedule"].(map[string]interface{})["leader-schedule-limit"]) + re.Equal(float64(4), config["schedule"].(map[string]any)["leader-schedule-limit"]) - newConfig := map[string]interface{}{ + newConfig := map[string]any{ "schedule.leader-schedule-limit": float64(8), } err = client.SetConfig(env.ctx, newConfig) @@ -497,10 +497,10 @@ func (suite *httpClientTestSuite) checkConfig(mode mode, client pd.Client) { config, err = client.GetConfig(env.ctx) re.NoError(err) - re.Equal(float64(8), config["schedule"].(map[string]interface{})["leader-schedule-limit"]) + re.Equal(float64(8), config["schedule"].(map[string]any)["leader-schedule-limit"]) // Test the config with TTL. - newConfig = map[string]interface{}{ + newConfig = map[string]any{ "schedule.leader-schedule-limit": float64(16), } err = client.SetConfig(env.ctx, newConfig, 5) diff --git a/tests/integrations/mcs/resourcemanager/resource_manager_test.go b/tests/integrations/mcs/resourcemanager/resource_manager_test.go index e83e9db23cd..8d8243ed7d7 100644 --- a/tests/integrations/mcs/resourcemanager/resource_manager_test.go +++ b/tests/integrations/mcs/resourcemanager/resource_manager_test.go @@ -1447,7 +1447,7 @@ func (suite *resourceManagerClientTestSuite) TestResourceGroupControllerConfigCh testCases := []struct { configJSON string - value interface{} + value any expected func(ruConfig *controller.RUConfig) }{ { diff --git a/tests/integrations/mcs/scheduling/api_test.go b/tests/integrations/mcs/scheduling/api_test.go index 7e17a521c5d..38294598bc5 100644 --- a/tests/integrations/mcs/scheduling/api_test.go +++ b/tests/integrations/mcs/scheduling/api_test.go @@ -83,14 +83,14 @@ func (suite *apiTestSuite) checkGetCheckerByName(cluster *tests.TestCluster) { for _, testCase := range testCases { name := testCase.name // normal run - resp := make(map[string]interface{}) + resp := make(map[string]any) err := testutil.ReadGetJSON(re, testDialClient, fmt.Sprintf("%s/%s", urlPrefix, name), &resp) re.NoError(err) re.False(resp["paused"].(bool)) // paused err = co.PauseOrResumeChecker(name, 30) re.NoError(err) - resp = make(map[string]interface{}) + resp = make(map[string]any) err = testutil.ReadGetJSON(re, testDialClient, fmt.Sprintf("%s/%s", urlPrefix, name), &resp) re.NoError(err) re.True(resp["paused"].(bool)) @@ -98,7 +98,7 @@ func (suite *apiTestSuite) checkGetCheckerByName(cluster *tests.TestCluster) { err = co.PauseOrResumeChecker(name, 1) re.NoError(err) time.Sleep(time.Second) - resp = make(map[string]interface{}) + resp = make(map[string]any) err = testutil.ReadGetJSON(re, testDialClient, fmt.Sprintf("%s/%s", urlPrefix, name), &resp) re.NoError(err) re.False(resp["paused"].(bool)) @@ -115,7 +115,7 @@ func (suite *apiTestSuite) checkAPIForward(cluster *tests.TestCluster) { leader := cluster.GetLeaderServer().GetServer() urlPrefix := fmt.Sprintf("%s/pd/api/v1", leader.GetAddr()) var respSlice []string - var resp map[string]interface{} + var resp map[string]any testutil.Eventually(re, func() bool { return leader.GetRaftCluster().IsServiceIndependent(utils.SchedulingServiceName) }) @@ -150,7 +150,7 @@ func (suite *apiTestSuite) checkAPIForward(cluster *tests.TestCluster) { // Test pause postChecker := func(delay int) { - input := make(map[string]interface{}) + input := make(map[string]any) input["delay"] = delay pauseArgs, err := json.Marshal(input) re.NoError(err) @@ -180,7 +180,7 @@ func (suite *apiTestSuite) checkAPIForward(cluster *tests.TestCluster) { }) postScheduler := func(delay int) { - input := make(map[string]interface{}) + input := make(map[string]any) input["delay"] = delay pauseArgs, err := json.Marshal(input) re.NoError(err) @@ -219,7 +219,7 @@ func (suite *apiTestSuite) checkAPIForward(cluster *tests.TestCluster) { testutil.WithoutHeader(re, apiutil.XForwardedToMicroServiceHeader)) re.NoError(err) - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = "balance-leader-scheduler" b, err := json.Marshal(input) re.NoError(err) @@ -420,7 +420,7 @@ func (suite *apiTestSuite) checkConfigForward(cluster *tests.TestCluster) { re := suite.Require() sche := cluster.GetSchedulingPrimaryServer() opts := sche.GetPersistConfig() - var cfg map[string]interface{} + var cfg map[string]any addr := cluster.GetLeaderServer().GetAddr() urlPrefix := fmt.Sprintf("%s/pd/api/v1/config", addr) @@ -428,17 +428,17 @@ func (suite *apiTestSuite) checkConfigForward(cluster *tests.TestCluster) { // Expect to get same config in scheduling server and api server testutil.Eventually(re, func() bool { testutil.ReadGetJSON(re, testDialClient, urlPrefix, &cfg) - re.Equal(cfg["schedule"].(map[string]interface{})["leader-schedule-limit"], + re.Equal(cfg["schedule"].(map[string]any)["leader-schedule-limit"], float64(opts.GetLeaderScheduleLimit())) - re.Equal(cfg["replication"].(map[string]interface{})["max-replicas"], + re.Equal(cfg["replication"].(map[string]any)["max-replicas"], float64(opts.GetReplicationConfig().MaxReplicas)) - schedulers := cfg["schedule"].(map[string]interface{})["schedulers-payload"].(map[string]interface{}) + schedulers := cfg["schedule"].(map[string]any)["schedulers-payload"].(map[string]any) return len(schedulers) == 4 }) // Test to change config in api server // Expect to get new config in scheduling server and api server - reqData, err := json.Marshal(map[string]interface{}{ + reqData, err := json.Marshal(map[string]any{ "max-replicas": 4, }) re.NoError(err) @@ -446,7 +446,7 @@ func (suite *apiTestSuite) checkConfigForward(cluster *tests.TestCluster) { re.NoError(err) testutil.Eventually(re, func() bool { testutil.ReadGetJSON(re, testDialClient, urlPrefix, &cfg) - return cfg["replication"].(map[string]interface{})["max-replicas"] == 4. && + return cfg["replication"].(map[string]any)["max-replicas"] == 4. && opts.GetReplicationConfig().MaxReplicas == 4. }) @@ -455,11 +455,11 @@ func (suite *apiTestSuite) checkConfigForward(cluster *tests.TestCluster) { opts.GetScheduleConfig().LeaderScheduleLimit = 100 re.Equal(100, int(opts.GetLeaderScheduleLimit())) testutil.ReadGetJSON(re, testDialClient, urlPrefix, &cfg) - re.Equal(100., cfg["schedule"].(map[string]interface{})["leader-schedule-limit"]) + re.Equal(100., cfg["schedule"].(map[string]any)["leader-schedule-limit"]) opts.GetReplicationConfig().MaxReplicas = 5 re.Equal(5, int(opts.GetReplicationConfig().MaxReplicas)) testutil.ReadGetJSON(re, testDialClient, urlPrefix, &cfg) - re.Equal(5., cfg["replication"].(map[string]interface{})["max-replicas"]) + re.Equal(5., cfg["replication"].(map[string]any)["max-replicas"]) } func (suite *apiTestSuite) TestAdminRegionCache() { @@ -559,7 +559,7 @@ func (suite *apiTestSuite) checkFollowerForward(cluster *tests.TestCluster) { // follower will forward to leader server re.NotEqual(cluster.GetLeaderServer().GetAddr(), followerAddr) - results := make(map[string]interface{}) + results := make(map[string]any) err = testutil.ReadGetJSON(re, testDialClient, fmt.Sprintf("%s/%s", urlPrefix, "config"), &results, testutil.WithoutHeader(re, apiutil.XForwardedToMicroServiceHeader), ) @@ -653,33 +653,33 @@ func (suite *apiTestSuite) checkStores(cluster *tests.TestCluster) { // Test /stores apiServerAddr := cluster.GetLeaderServer().GetAddr() urlPrefix := fmt.Sprintf("%s/pd/api/v1/stores", apiServerAddr) - var resp map[string]interface{} + var resp map[string]any err := testutil.ReadGetJSON(re, testDialClient, urlPrefix, &resp) re.NoError(err) re.Equal(3, int(resp["count"].(float64))) - re.Len(resp["stores"].([]interface{}), 3) + re.Len(resp["stores"].([]any), 3) scheServerAddr := cluster.GetSchedulingPrimaryServer().GetAddr() urlPrefix = fmt.Sprintf("%s/scheduling/api/v1/stores", scheServerAddr) err = testutil.ReadGetJSON(re, testDialClient, urlPrefix, &resp) re.NoError(err) re.Equal(3, int(resp["count"].(float64))) - re.Len(resp["stores"].([]interface{}), 3) + re.Len(resp["stores"].([]any), 3) // Test /stores/{id} urlPrefix = fmt.Sprintf("%s/scheduling/api/v1/stores/1", scheServerAddr) err = testutil.ReadGetJSON(re, testDialClient, urlPrefix, &resp) re.NoError(err) - re.Equal("tikv1", resp["store"].(map[string]interface{})["address"]) - re.Equal("Up", resp["store"].(map[string]interface{})["state_name"]) + re.Equal("tikv1", resp["store"].(map[string]any)["address"]) + re.Equal("Up", resp["store"].(map[string]any)["state_name"]) urlPrefix = fmt.Sprintf("%s/scheduling/api/v1/stores/6", scheServerAddr) err = testutil.ReadGetJSON(re, testDialClient, urlPrefix, &resp) re.NoError(err) - re.Equal("tikv6", resp["store"].(map[string]interface{})["address"]) - re.Equal("Offline", resp["store"].(map[string]interface{})["state_name"]) + re.Equal("tikv6", resp["store"].(map[string]any)["address"]) + re.Equal("Offline", resp["store"].(map[string]any)["state_name"]) urlPrefix = fmt.Sprintf("%s/scheduling/api/v1/stores/7", scheServerAddr) err = testutil.ReadGetJSON(re, testDialClient, urlPrefix, &resp) re.NoError(err) - re.Equal("tikv7", resp["store"].(map[string]interface{})["address"]) - re.Equal("Tombstone", resp["store"].(map[string]interface{})["state_name"]) + re.Equal("tikv7", resp["store"].(map[string]any)["address"]) + re.Equal("Tombstone", resp["store"].(map[string]any)["state_name"]) urlPrefix = fmt.Sprintf("%s/scheduling/api/v1/stores/233", scheServerAddr) testutil.CheckGetJSON(testDialClient, urlPrefix, nil, testutil.Status(re, http.StatusNotFound), testutil.StringContain(re, "not found")) @@ -697,17 +697,17 @@ func (suite *apiTestSuite) checkRegions(cluster *tests.TestCluster) { // Test /regions apiServerAddr := cluster.GetLeaderServer().GetAddr() urlPrefix := fmt.Sprintf("%s/pd/api/v1/regions", apiServerAddr) - var resp map[string]interface{} + var resp map[string]any err := testutil.ReadGetJSON(re, testDialClient, urlPrefix, &resp) re.NoError(err) re.Equal(3, int(resp["count"].(float64))) - re.Len(resp["regions"].([]interface{}), 3) + re.Len(resp["regions"].([]any), 3) scheServerAddr := cluster.GetSchedulingPrimaryServer().GetAddr() urlPrefix = fmt.Sprintf("%s/scheduling/api/v1/regions", scheServerAddr) err = testutil.ReadGetJSON(re, testDialClient, urlPrefix, &resp) re.NoError(err) re.Equal(3, int(resp["count"].(float64))) - re.Len(resp["regions"].([]interface{}), 3) + re.Len(resp["regions"].([]any), 3) // Test /regions/{id} and /regions/count urlPrefix = fmt.Sprintf("%s/scheduling/api/v1/regions/1", scheServerAddr) err = testutil.ReadGetJSON(re, testDialClient, urlPrefix, &resp) diff --git a/tests/integrations/mcs/scheduling/config_test.go b/tests/integrations/mcs/scheduling/config_test.go index 69d77bb24ac..d7883379731 100644 --- a/tests/integrations/mcs/scheduling/config_test.go +++ b/tests/integrations/mcs/scheduling/config_test.go @@ -164,7 +164,7 @@ func (suite *configTestSuite) TestSchedulerConfigWatch() { }) re.Equal(namesFromAPIServer, namesFromSchedulingServer) // Add a new scheduler. - api.MustAddScheduler(re, suite.pdLeaderServer.GetAddr(), schedulers.EvictLeaderName, map[string]interface{}{ + api.MustAddScheduler(re, suite.pdLeaderServer.GetAddr(), schedulers.EvictLeaderName, map[string]any{ "store_id": 1, }) // Check the new scheduler's config. @@ -186,7 +186,7 @@ func (suite *configTestSuite) TestSchedulerConfigWatch() { }, ) re.NoError(err) - api.MustAddScheduler(re, suite.pdLeaderServer.GetAddr(), schedulers.EvictLeaderName, map[string]interface{}{ + api.MustAddScheduler(re, suite.pdLeaderServer.GetAddr(), schedulers.EvictLeaderName, map[string]any{ "store_id": 2, }) assertEvictLeaderStoreIDs(re, storage, []uint64{1, 2}) diff --git a/tests/integrations/mcs/scheduling/server_test.go b/tests/integrations/mcs/scheduling/server_test.go index 198fa360b9b..38c1cc6a41b 100644 --- a/tests/integrations/mcs/scheduling/server_test.go +++ b/tests/integrations/mcs/scheduling/server_test.go @@ -303,7 +303,7 @@ func (suite *serverTestSuite) TestSchedulerSync() { schedulersController := tc.GetPrimaryServer().GetCluster().GetCoordinator().GetSchedulersController() checkEvictLeaderSchedulerExist(re, schedulersController, false) // Add a new evict-leader-scheduler through the API server. - api.MustAddScheduler(re, suite.backendEndpoints, schedulers.EvictLeaderName, map[string]interface{}{ + api.MustAddScheduler(re, suite.backendEndpoints, schedulers.EvictLeaderName, map[string]any{ "store_id": 1, }) // Check if the evict-leader-scheduler is added. @@ -321,7 +321,7 @@ func (suite *serverTestSuite) TestSchedulerSync() { }, ) re.NoError(err) - api.MustAddScheduler(re, suite.backendEndpoints, schedulers.EvictLeaderName, map[string]interface{}{ + api.MustAddScheduler(re, suite.backendEndpoints, schedulers.EvictLeaderName, map[string]any{ "store_id": 2, }) checkEvictLeaderSchedulerExist(re, schedulersController, true) @@ -331,7 +331,7 @@ func (suite *serverTestSuite) TestSchedulerSync() { checkEvictLeaderSchedulerExist(re, schedulersController, true) checkEvictLeaderStoreIDs(re, schedulersController, []uint64{2}) // Add a store_id to the evict-leader-scheduler through the API server by the scheduler handler. - api.MustCallSchedulerConfigAPI(re, http.MethodPost, suite.backendEndpoints, schedulers.EvictLeaderName, []string{"config"}, map[string]interface{}{ + api.MustCallSchedulerConfigAPI(re, http.MethodPost, suite.backendEndpoints, schedulers.EvictLeaderName, []string{"config"}, map[string]any{ "name": schedulers.EvictLeaderName, "store_id": 1, }) @@ -347,7 +347,7 @@ func (suite *serverTestSuite) TestSchedulerSync() { checkEvictLeaderSchedulerExist(re, schedulersController, false) // Delete the evict-leader-scheduler through the API server by removing the last store_id. - api.MustAddScheduler(re, suite.backendEndpoints, schedulers.EvictLeaderName, map[string]interface{}{ + api.MustAddScheduler(re, suite.backendEndpoints, schedulers.EvictLeaderName, map[string]any{ "store_id": 1, }) checkEvictLeaderSchedulerExist(re, schedulersController, true) @@ -356,7 +356,7 @@ func (suite *serverTestSuite) TestSchedulerSync() { checkEvictLeaderSchedulerExist(re, schedulersController, false) // Delete the evict-leader-scheduler through the API server. - api.MustAddScheduler(re, suite.backendEndpoints, schedulers.EvictLeaderName, map[string]interface{}{ + api.MustAddScheduler(re, suite.backendEndpoints, schedulers.EvictLeaderName, map[string]any{ "store_id": 1, }) checkEvictLeaderSchedulerExist(re, schedulersController, true) diff --git a/tests/integrations/mcs/tso/api_test.go b/tests/integrations/mcs/tso/api_test.go index dd683c88fd7..0a026aff916 100644 --- a/tests/integrations/mcs/tso/api_test.go +++ b/tests/integrations/mcs/tso/api_test.go @@ -170,7 +170,7 @@ func TestTSOServerStartFirst(t *testing.T) { <-ch time.Sleep(time.Second * 1) - input := make(map[string]interface{}) + input := make(map[string]any) input["new-id"] = 1 input["keyspaces"] = []uint32{2} jsonBody, err := json.Marshal(input) diff --git a/tests/integrations/realcluster/mock_db.go b/tests/integrations/realcluster/mock_db.go index 255ff6c0057..2a636b9b86b 100644 --- a/tests/integrations/realcluster/mock_db.go +++ b/tests/integrations/realcluster/mock_db.go @@ -85,7 +85,7 @@ func (db *TestDB) Gorm() *gorm.DB { } // MustExec executes a query -func (db *TestDB) MustExec(sql string, values ...interface{}) { +func (db *TestDB) MustExec(sql string, values ...any) { err := db.inner.Exec(sql, values...).Error db.require.NoError(err) } diff --git a/tests/server/api/api_test.go b/tests/server/api/api_test.go index c80048b141f..b70c688993d 100644 --- a/tests/server/api/api_test.go +++ b/tests/server/api/api_test.go @@ -142,7 +142,7 @@ func (suite *middlewareTestSuite) TestRequestInfoMiddleware() { leader := suite.cluster.GetLeaderServer() re.NotNil(leader) - input := map[string]interface{}{ + input := map[string]any{ "enable-audit": "true", } data, err := json.Marshal(input) @@ -153,7 +153,7 @@ func (suite *middlewareTestSuite) TestRequestInfoMiddleware() { resp.Body.Close() re.True(leader.GetServer().GetServiceMiddlewarePersistOptions().IsAuditEnabled()) - labels := make(map[string]interface{}) + labels := make(map[string]any) labels["testkey"] = "testvalue" data, _ = json.Marshal(labels) resp, err = dialClient.Post(leader.GetAddr()+"/pd/api/v1/debug/pprof/profile?force=true", "application/json", bytes.NewBuffer(data)) @@ -170,7 +170,7 @@ func (suite *middlewareTestSuite) TestRequestInfoMiddleware() { re.Equal("anonymous", resp.Header.Get("caller-id")) re.Equal("127.0.0.1", resp.Header.Get("ip")) - input = map[string]interface{}{ + input = map[string]any{ "enable-audit": "false", } data, err = json.Marshal(input) @@ -194,7 +194,7 @@ func BenchmarkDoRequestWithServiceMiddleware(b *testing.B) { cluster.RunInitialServers() cluster.WaitLeader() leader := cluster.GetLeaderServer() - input := map[string]interface{}{ + input := map[string]any{ "enable-audit": "true", } data, _ := json.Marshal(input) @@ -213,7 +213,7 @@ func (suite *middlewareTestSuite) TestRateLimitMiddleware() { re := suite.Require() leader := suite.cluster.GetLeaderServer() re.NotNil(leader) - input := map[string]interface{}{ + input := map[string]any{ "enable-rate-limit": "true", } data, err := json.Marshal(input) @@ -232,7 +232,7 @@ func (suite *middlewareTestSuite) TestRateLimitMiddleware() { resp.Body.Close() re.NoError(err) re.Equal(http.StatusOK, resp.StatusCode) - input = make(map[string]interface{}) + input = make(map[string]any) input["type"] = "label" input["label"] = "SetLogLevel" input["qps"] = 0.5 @@ -353,7 +353,7 @@ func (suite *middlewareTestSuite) TestRateLimitMiddleware() { re.Equal(string(data), fmt.Sprintf("%s\n", http.StatusText(http.StatusTooManyRequests))) } - input = map[string]interface{}{ + input = map[string]any{ "enable-rate-limit": "false", } data, err = json.Marshal(input) @@ -390,7 +390,7 @@ func (suite *middlewareTestSuite) TestAuditPrometheusBackend() { re := suite.Require() leader := suite.cluster.GetLeaderServer() re.NotNil(leader) - input := map[string]interface{}{ + input := map[string]any{ "enable-audit": "true", } data, err := json.Marshal(input) @@ -442,7 +442,7 @@ func (suite *middlewareTestSuite) TestAuditPrometheusBackend() { output = string(content) re.Contains(output, "pd_service_audit_handling_seconds_count{caller_id=\"anonymous\",ip=\"127.0.0.1\",method=\"HTTP\",service=\"GetTrend\"} 2") - input = map[string]interface{}{ + input = map[string]any{ "enable-audit": "false", } data, err = json.Marshal(input) @@ -460,7 +460,7 @@ func (suite *middlewareTestSuite) TestAuditLocalLogBackend() { defer os.RemoveAll(fname) leader := suite.cluster.GetLeaderServer() re.NotNil(leader) - input := map[string]interface{}{ + input := map[string]any{ "enable-audit": "true", } data, err := json.Marshal(input) @@ -489,7 +489,7 @@ func BenchmarkDoRequestWithLocalLogAudit(b *testing.B) { cluster.RunInitialServers() cluster.WaitLeader() leader := cluster.GetLeaderServer() - input := map[string]interface{}{ + input := map[string]any{ "enable-audit": "true", } data, _ := json.Marshal(input) @@ -511,7 +511,7 @@ func BenchmarkDoRequestWithPrometheusAudit(b *testing.B) { cluster.RunInitialServers() cluster.WaitLeader() leader := cluster.GetLeaderServer() - input := map[string]interface{}{ + input := map[string]any{ "enable-audit": "true", } data, _ := json.Marshal(input) @@ -533,7 +533,7 @@ func BenchmarkDoRequestWithoutServiceMiddleware(b *testing.B) { cluster.RunInitialServers() cluster.WaitLeader() leader := cluster.GetLeaderServer() - input := map[string]interface{}{ + input := map[string]any{ "enable-audit": "false", } data, _ := json.Marshal(input) diff --git a/tests/server/api/checker_test.go b/tests/server/api/checker_test.go index 884772bba97..198cfca216f 100644 --- a/tests/server/api/checker_test.go +++ b/tests/server/api/checker_test.go @@ -70,7 +70,7 @@ func (suite *checkerTestSuite) checkAPI(cluster *tests.TestCluster) { func (suite *checkerTestSuite) testErrCases(re *require.Assertions, cluster *tests.TestCluster) { urlPrefix := fmt.Sprintf("%s/pd/api/v1/checker", cluster.GetLeaderServer().GetAddr()) // missing args - input := make(map[string]interface{}) + input := make(map[string]any) pauseArgs, err := json.Marshal(input) re.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix+"/merge", pauseArgs, tu.StatusNotOK(re)) @@ -98,10 +98,10 @@ func (suite *checkerTestSuite) testErrCases(re *require.Assertions, cluster *tes } func (suite *checkerTestSuite) testGetStatus(re *require.Assertions, cluster *tests.TestCluster, name string) { - input := make(map[string]interface{}) + input := make(map[string]any) urlPrefix := fmt.Sprintf("%s/pd/api/v1/checker", cluster.GetLeaderServer().GetAddr()) // normal run - resp := make(map[string]interface{}) + resp := make(map[string]any) err := tu.ReadGetJSON(re, testDialClient, fmt.Sprintf("%s/%s", urlPrefix, name), &resp) re.NoError(err) re.False(resp["paused"].(bool)) @@ -111,7 +111,7 @@ func (suite *checkerTestSuite) testGetStatus(re *require.Assertions, cluster *te re.NoError(err) err = tu.CheckPostJSON(testDialClient, urlPrefix+"/"+name, pauseArgs, tu.StatusOK(re)) re.NoError(err) - resp = make(map[string]interface{}) + resp = make(map[string]any) err = tu.ReadGetJSON(re, testDialClient, fmt.Sprintf("%s/%s", urlPrefix, name), &resp) re.NoError(err) re.True(resp["paused"].(bool)) @@ -122,16 +122,16 @@ func (suite *checkerTestSuite) testGetStatus(re *require.Assertions, cluster *te err = tu.CheckPostJSON(testDialClient, urlPrefix+"/"+name, pauseArgs, tu.StatusOK(re)) re.NoError(err) time.Sleep(time.Second) - resp = make(map[string]interface{}) + resp = make(map[string]any) err = tu.ReadGetJSON(re, testDialClient, fmt.Sprintf("%s/%s", urlPrefix, name), &resp) re.NoError(err) re.False(resp["paused"].(bool)) } func (suite *checkerTestSuite) testPauseOrResume(re *require.Assertions, cluster *tests.TestCluster, name string) { - input := make(map[string]interface{}) + input := make(map[string]any) urlPrefix := fmt.Sprintf("%s/pd/api/v1/checker", cluster.GetLeaderServer().GetAddr()) - resp := make(map[string]interface{}) + resp := make(map[string]any) // test pause. input["delay"] = 30 @@ -153,7 +153,7 @@ func (suite *checkerTestSuite) testPauseOrResume(re *require.Assertions, cluster re.False(resp["paused"].(bool)) // test resume. - input = make(map[string]interface{}) + input = make(map[string]any) input["delay"] = 30 pauseArgs, err = json.Marshal(input) re.NoError(err) diff --git a/tests/server/api/operator_test.go b/tests/server/api/operator_test.go index cd3f2ac34dc..eb2ea5e1cd8 100644 --- a/tests/server/api/operator_test.go +++ b/tests/server/api/operator_test.go @@ -455,7 +455,7 @@ func (suite *operatorTestSuite) checkTransferRegionWithPlacementRule(cluster *te url := fmt.Sprintf("%s/pd/api/v1/config", svr.GetAddr()) for _, testCase := range testCases { suite.T().Log(testCase.name) - data := make(map[string]interface{}) + data := make(map[string]any) if testCase.placementRuleEnable { data["enable-placement-rules"] = "true" } else { @@ -616,7 +616,7 @@ func (suite *operatorTestSuite) checkGetOperatorsAsObject(cluster *tests.TestClu func (suite *operatorTestSuite) pauseRuleChecker(re *require.Assertions, cluster *tests.TestCluster) { checkerName := "rule" addr := cluster.GetLeaderServer().GetAddr() - resp := make(map[string]interface{}) + resp := make(map[string]any) url := fmt.Sprintf("%s/pd/api/v1/checker/%s", addr, checkerName) err := tu.CheckPostJSON(testDialClient, url, []byte(`{"delay":1000}`), tu.StatusOK(re)) re.NoError(err) diff --git a/tests/server/api/region_test.go b/tests/server/api/region_test.go index bb499550058..8c286dc12e2 100644 --- a/tests/server/api/region_test.go +++ b/tests/server/api/region_test.go @@ -420,7 +420,7 @@ func (suite *regionTestSuite) checkRegionCount(re *require.Assertions, cluster * func (suite *regionTestSuite) pauseRuleChecker(re *require.Assertions, cluster *tests.TestCluster) { checkerName := "rule" addr := cluster.GetLeaderServer().GetAddr() - resp := make(map[string]interface{}) + resp := make(map[string]any) url := fmt.Sprintf("%s/pd/api/v1/checker/%s", addr, checkerName) err := tu.CheckPostJSON(testDialClient, url, []byte(`{"delay":1000}`), tu.StatusOK(re)) re.NoError(err) diff --git a/tests/server/api/rule_test.go b/tests/server/api/rule_test.go index a845d2f3e05..912ff83e8d5 100644 --- a/tests/server/api/rule_test.go +++ b/tests/server/api/rule_test.go @@ -1429,7 +1429,7 @@ func (suite *regionRuleTestSuite) checkRegionPlacementRule(cluster *tests.TestCl re, errs.ErrRegionInvalidID.Error())) re.NoError(err) - data := make(map[string]interface{}) + data := make(map[string]any) data["enable-placement-rules"] = "false" reqData, e := json.Marshal(data) re.NoError(e) diff --git a/tests/server/api/scheduler_test.go b/tests/server/api/scheduler_test.go index e029df5bf97..569741d026c 100644 --- a/tests/server/api/scheduler_test.go +++ b/tests/server/api/scheduler_test.go @@ -79,7 +79,7 @@ func (suite *scheduleTestSuite) checkOriginAPI(cluster *tests.TestCluster) { tests.MustPutStore(re, cluster, store) } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = "evict-leader-scheduler" input["store_id"] = 1 body, err := json.Marshal(input) @@ -87,11 +87,11 @@ func (suite *scheduleTestSuite) checkOriginAPI(cluster *tests.TestCluster) { re.NoError(tu.CheckPostJSON(testDialClient, urlPrefix, body, tu.StatusOK(re))) suite.assertSchedulerExists(urlPrefix, "evict-leader-scheduler") - resp := make(map[string]interface{}) + resp := make(map[string]any) listURL := fmt.Sprintf("%s%s%s/%s/list", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, "evict-leader-scheduler") re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) re.Len(resp["store-id-ranges"], 1) - input1 := make(map[string]interface{}) + input1 := make(map[string]any) input1["name"] = "evict-leader-scheduler" input1["store_id"] = 2 body, err = json.Marshal(input1) @@ -99,20 +99,20 @@ func (suite *scheduleTestSuite) checkOriginAPI(cluster *tests.TestCluster) { re.NoError(failpoint.Enable("github.com/tikv/pd/pkg/schedule/schedulers/persistFail", "return(true)")) re.NoError(tu.CheckPostJSON(testDialClient, urlPrefix, body, tu.StatusNotOK(re))) suite.assertSchedulerExists(urlPrefix, "evict-leader-scheduler") - resp = make(map[string]interface{}) + resp = make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) re.Len(resp["store-id-ranges"], 1) re.NoError(failpoint.Disable("github.com/tikv/pd/pkg/schedule/schedulers/persistFail")) re.NoError(tu.CheckPostJSON(testDialClient, urlPrefix, body, tu.StatusOK(re))) suite.assertSchedulerExists(urlPrefix, "evict-leader-scheduler") - resp = make(map[string]interface{}) + resp = make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) re.Len(resp["store-id-ranges"], 2) deleteURL := fmt.Sprintf("%s/%s", urlPrefix, "evict-leader-scheduler-1") err = tu.CheckDelete(testDialClient, deleteURL, tu.StatusOK(re)) re.NoError(err) suite.assertSchedulerExists(urlPrefix, "evict-leader-scheduler") - resp1 := make(map[string]interface{}) + resp1 := make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp1)) re.Len(resp1["store-id-ranges"], 1) deleteURL = fmt.Sprintf("%s/%s", urlPrefix, "evict-leader-scheduler-2") @@ -149,7 +149,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { type arg struct { opt string - value interface{} + value any } testCases := []struct { name string @@ -161,18 +161,18 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { name: "balance-leader-scheduler", createdName: "balance-leader-scheduler", extraTestFunc: func(name string) { - resp := make(map[string]interface{}) + resp := make(map[string]any) listURL := fmt.Sprintf("%s%s%s/%s/list", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) re.Equal(4.0, resp["batch"]) - dataMap := make(map[string]interface{}) + dataMap := make(map[string]any) dataMap["batch"] = 3 updateURL := fmt.Sprintf("%s%s%s/%s/config", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) body, err := json.Marshal(dataMap) re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(re))) tu.Eventually(re, func() bool { // wait for scheduling server to be synced. - resp = make(map[string]interface{}) + resp = make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) return resp["batch"] == 3.0 }) @@ -183,7 +183,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { tu.StringEqual(re, "\"Config is the same with origin, so do nothing.\"\n")) re.NoError(err) // update invalidate batch - dataMap = map[string]interface{}{} + dataMap = map[string]any{} dataMap["batch"] = 100 body, err = json.Marshal(dataMap) re.NoError(err) @@ -191,7 +191,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "\"invalid batch size which should be an integer between 1 and 10\"\n")) re.NoError(err) - resp = make(map[string]interface{}) + resp = make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) re.Equal(3.0, resp["batch"]) // empty body @@ -200,7 +200,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { tu.StringEqual(re, "\"unexpected end of JSON input\"\n")) re.NoError(err) // config item not found - dataMap = map[string]interface{}{} + dataMap = map[string]any{} dataMap["error"] = 3 body, err = json.Marshal(dataMap) re.NoError(err) @@ -214,10 +214,10 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { name: "balance-hot-region-scheduler", createdName: "balance-hot-region-scheduler", extraTestFunc: func(name string) { - resp := make(map[string]interface{}) + resp := make(map[string]any) listURL := fmt.Sprintf("%s%s%s/%s/list", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) - expectMap := map[string]interface{}{ + expectMap := map[string]any{ "min-hot-byte-rate": 100.0, "min-hot-key-rate": 10.0, "min-hot-query-rate": 10.0, @@ -233,9 +233,9 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { "dst-tolerance-ratio": 1.05, "split-thresholds": 0.2, "rank-formula-version": "v2", - "read-priorities": []interface{}{"byte", "key"}, - "write-leader-priorities": []interface{}{"key", "byte"}, - "write-peer-priorities": []interface{}{"byte", "key"}, + "read-priorities": []any{"byte", "key"}, + "write-leader-priorities": []any{"key", "byte"}, + "write-peer-priorities": []any{"byte", "key"}, "enable-for-tiflash": "true", "strict-picking-store": "true", } @@ -243,14 +243,14 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { for key := range expectMap { re.Equal(expectMap[key], resp[key]) } - dataMap := make(map[string]interface{}) + dataMap := make(map[string]any) dataMap["max-zombie-rounds"] = 5.0 expectMap["max-zombie-rounds"] = 5.0 updateURL := fmt.Sprintf("%s%s%s/%s/config", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) body, err := json.Marshal(dataMap) re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(re))) - resp = make(map[string]interface{}) + resp = make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) for key := range expectMap { @@ -263,7 +263,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { tu.StringEqual(re, "Config is the same with origin, so do nothing.")) re.NoError(err) // config item not found - dataMap = map[string]interface{}{} + dataMap = map[string]any{} dataMap["error"] = 3 body, err = json.Marshal(dataMap) re.NoError(err) @@ -277,18 +277,18 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { name: "split-bucket-scheduler", createdName: "split-bucket-scheduler", extraTestFunc: func(name string) { - resp := make(map[string]interface{}) + resp := make(map[string]any) listURL := fmt.Sprintf("%s%s%s/%s/list", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) re.Equal(3.0, resp["degree"]) re.Equal(0.0, resp["split-limit"]) - dataMap := make(map[string]interface{}) + dataMap := make(map[string]any) dataMap["degree"] = 4 updateURL := fmt.Sprintf("%s%s%s/%s/config", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) body, err := json.Marshal(dataMap) re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(re))) - resp = make(map[string]interface{}) + resp = make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) re.Equal(4.0, resp["degree"]) // update again @@ -302,7 +302,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { tu.StringEqual(re, "\"unexpected end of JSON input\"\n")) re.NoError(err) // config item not found - dataMap = map[string]interface{}{} + dataMap = map[string]any{} dataMap["error"] = 3 body, err = json.Marshal(dataMap) re.NoError(err) @@ -332,17 +332,17 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { name: "balance-witness-scheduler", createdName: "balance-witness-scheduler", extraTestFunc: func(name string) { - resp := make(map[string]interface{}) + resp := make(map[string]any) listURL := fmt.Sprintf("%s%s%s/%s/list", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) re.Equal(4.0, resp["batch"]) - dataMap := make(map[string]interface{}) + dataMap := make(map[string]any) dataMap["batch"] = 3 updateURL := fmt.Sprintf("%s%s%s/%s/config", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) body, err := json.Marshal(dataMap) re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(re))) - resp = make(map[string]interface{}) + resp = make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) re.Equal(3.0, resp["batch"]) // update again @@ -351,7 +351,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { tu.StringEqual(re, "\"Config is the same with origin, so do nothing.\"\n")) re.NoError(err) // update invalidate batch - dataMap = map[string]interface{}{} + dataMap = map[string]any{} dataMap["batch"] = 100 body, err = json.Marshal(dataMap) re.NoError(err) @@ -359,7 +359,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { tu.Status(re, http.StatusBadRequest), tu.StringEqual(re, "\"invalid batch size which should be an integer between 1 and 10\"\n")) re.NoError(err) - resp = make(map[string]interface{}) + resp = make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) re.Equal(3.0, resp["batch"]) // empty body @@ -368,7 +368,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { tu.StringEqual(re, "\"unexpected end of JSON input\"\n")) re.NoError(err) // config item not found - dataMap = map[string]interface{}{} + dataMap = map[string]any{} dataMap["error"] = 3 body, err = json.Marshal(dataMap) re.NoError(err) @@ -383,31 +383,31 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { createdName: "grant-leader-scheduler", args: []arg{{"store_id", 1}}, extraTestFunc: func(name string) { - resp := make(map[string]interface{}) + resp := make(map[string]any) listURL := fmt.Sprintf("%s%s%s/%s/list", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) - exceptMap := make(map[string]interface{}) - exceptMap["1"] = []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}} + exceptMap := make(map[string]any) + exceptMap["1"] = []any{map[string]any{"end-key": "", "start-key": ""}} re.Equal(exceptMap, resp["store-id-ranges"]) // using /pd/v1/schedule-config/grant-leader-scheduler/config to add new store to grant-leader-scheduler - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = "grant-leader-scheduler" input["store_id"] = 2 updateURL := fmt.Sprintf("%s%s%s/%s/config", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) body, err := json.Marshal(input) re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(re))) - resp = make(map[string]interface{}) + resp = make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) - exceptMap["2"] = []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}} + exceptMap["2"] = []any{map[string]any{"end-key": "", "start-key": ""}} re.Equal(exceptMap, resp["store-id-ranges"]) // using /pd/v1/schedule-config/grant-leader-scheduler/config to delete exists store from grant-leader-scheduler deleteURL := fmt.Sprintf("%s%s%s/%s/delete/%s", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name, "2") err = tu.CheckDelete(testDialClient, deleteURL, tu.StatusOK(re)) re.NoError(err) - resp = make(map[string]interface{}) + resp = make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) delete(exceptMap, "2") re.Equal(exceptMap, resp["store-id-ranges"]) @@ -421,7 +421,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { args: []arg{{"start_key", ""}, {"end_key", ""}, {"range_name", "test"}}, // Test the scheduler config handler. extraTestFunc: func(name string) { - resp := make(map[string]interface{}) + resp := make(map[string]any) listURL := fmt.Sprintf("%s%s%s/%s/list", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) re.Equal("", resp["start-key"]) @@ -433,7 +433,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { body, err := json.Marshal(resp) re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(re))) - resp = make(map[string]interface{}) + resp = make(map[string]any) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) re.Equal("a_00", resp["start-key"]) re.Equal("a_99", resp["end-key"]) @@ -446,25 +446,25 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { args: []arg{{"store_id", 3}}, // Test the scheduler config handler. extraTestFunc: func(name string) { - resp := make(map[string]interface{}) + resp := make(map[string]any) listURL := fmt.Sprintf("%s%s%s/%s/list", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) - exceptMap := make(map[string]interface{}) - exceptMap["3"] = []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}} + exceptMap := make(map[string]any) + exceptMap["3"] = []any{map[string]any{"end-key": "", "start-key": ""}} re.Equal(exceptMap, resp["store-id-ranges"]) // using /pd/v1/schedule-config/evict-leader-scheduler/config to add new store to evict-leader-scheduler - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = "evict-leader-scheduler" input["store_id"] = 4 updateURL := fmt.Sprintf("%s%s%s/%s/config", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name) body, err := json.Marshal(input) re.NoError(err) re.NoError(tu.CheckPostJSON(testDialClient, updateURL, body, tu.StatusOK(re))) - resp = make(map[string]interface{}) + resp = make(map[string]any) tu.Eventually(re, func() bool { re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) - exceptMap["4"] = []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}} + exceptMap["4"] = []any{map[string]any{"end-key": "", "start-key": ""}} return reflect.DeepEqual(exceptMap, resp["store-id-ranges"]) }) @@ -472,7 +472,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { deleteURL := fmt.Sprintf("%s%s%s/%s/delete/%s", leaderAddr, apiPrefix, server.SchedulerConfigHandlerPath, name, "4") err = tu.CheckDelete(testDialClient, deleteURL, tu.StatusOK(re)) re.NoError(err) - resp = make(map[string]interface{}) + resp = make(map[string]any) tu.Eventually(re, func() bool { re.NoError(tu.ReadGetJSON(re, testDialClient, listURL, &resp)) delete(exceptMap, "4") @@ -488,7 +488,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { }, } for _, testCase := range testCases { - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = testCase.name for _, a := range testCase.args { input[a.opt] = a.value @@ -507,7 +507,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { // add schedulers. for _, testCase := range testCases { - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = testCase.name for _, a := range testCase.args { input[a.opt] = a.value @@ -522,7 +522,7 @@ func (suite *scheduleTestSuite) checkAPI(cluster *tests.TestCluster) { } // test pause all schedulers. - input := make(map[string]interface{}) + input := make(map[string]any) input["delay"] = 30 pauseArgs, err := json.Marshal(input) re.NoError(err) @@ -602,7 +602,7 @@ func (suite *scheduleTestSuite) checkDisable(cluster *tests.TestCluster) { } name := "shuffle-leader-scheduler" - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = name body, err := json.Marshal(input) re.NoError(err) @@ -658,7 +658,7 @@ func (suite *scheduleTestSuite) testPauseOrResume(re *require.Assertions, urlPre suite.assertSchedulerExists(urlPrefix, createdName) // wait for scheduler to be synced. // test pause. - input := make(map[string]interface{}) + input := make(map[string]any) input["delay"] = 30 pauseArgs, err := json.Marshal(input) re.NoError(err) @@ -676,7 +676,7 @@ func (suite *scheduleTestSuite) testPauseOrResume(re *require.Assertions, urlPre re.False(isPaused) // test resume. - input = make(map[string]interface{}) + input = make(map[string]any) input["delay"] = 30 pauseArgs, err = json.Marshal(input) re.NoError(err) @@ -713,7 +713,7 @@ func (suite *scheduleTestSuite) checkEmptySchedulers(cluster *tests.TestCluster) re.NoError(tu.ReadGetJSON(re, testDialClient, urlPrefix+query, &schedulers)) for _, scheduler := range schedulers { if strings.Contains(query, "disable") { - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = scheduler body, err := json.Marshal(input) re.NoError(err) diff --git a/tests/server/api/testutil.go b/tests/server/api/testutil.go index 6fab82ea2e3..1b2f3d09e3d 100644 --- a/tests/server/api/testutil.go +++ b/tests/server/api/testutil.go @@ -40,9 +40,9 @@ var dialClient = &http.Client{ // MustAddScheduler adds a scheduler with HTTP API. func MustAddScheduler( re *require.Assertions, serverAddr string, - schedulerName string, args map[string]interface{}, + schedulerName string, args map[string]any, ) { - request := map[string]interface{}{ + request := map[string]any{ "name": schedulerName, } for arg, val := range args { @@ -77,7 +77,7 @@ func MustDeleteScheduler(re *require.Assertions, serverAddr, schedulerName strin func MustCallSchedulerConfigAPI( re *require.Assertions, method, serverAddr, schedulerName string, args []string, - input map[string]interface{}, + input map[string]any, ) { data, err := json.Marshal(input) re.NoError(err) diff --git a/tests/server/cluster/cluster_test.go b/tests/server/cluster/cluster_test.go index 67c798d7f69..525b211b1fc 100644 --- a/tests/server/cluster/cluster_test.go +++ b/tests/server/cluster/cluster_test.go @@ -1312,10 +1312,10 @@ func TestTransferLeaderForScheduler(t *testing.T) { re.True(leaderServer.GetRaftCluster().IsPrepared()) schedsNum := len(rc.GetCoordinator().GetSchedulersController().GetSchedulerNames()) // Add evict leader scheduler - api.MustAddScheduler(re, leaderServer.GetAddr(), schedulers.EvictLeaderName, map[string]interface{}{ + api.MustAddScheduler(re, leaderServer.GetAddr(), schedulers.EvictLeaderName, map[string]any{ "store_id": 1, }) - api.MustAddScheduler(re, leaderServer.GetAddr(), schedulers.EvictLeaderName, map[string]interface{}{ + api.MustAddScheduler(re, leaderServer.GetAddr(), schedulers.EvictLeaderName, map[string]any{ "store_id": 2, }) // Check scheduler updated. diff --git a/tests/server/cluster/cluster_work_test.go b/tests/server/cluster/cluster_work_test.go index f503563dbb1..530e15f3f8c 100644 --- a/tests/server/cluster/cluster_work_test.go +++ b/tests/server/cluster/cluster_work_test.go @@ -109,12 +109,12 @@ func TestAskSplit(t *testing.T) { SplitCount: 10, } - re.NoError(leaderServer.GetServer().SaveTTLConfig(map[string]interface{}{"schedule.enable-tikv-split-region": 0}, time.Minute)) + re.NoError(leaderServer.GetServer().SaveTTLConfig(map[string]any{"schedule.enable-tikv-split-region": 0}, time.Minute)) _, err = rc.HandleAskSplit(req) re.ErrorIs(err, errs.ErrSchedulerTiKVSplitDisabled) _, err = rc.HandleAskBatchSplit(req1) re.ErrorIs(err, errs.ErrSchedulerTiKVSplitDisabled) - re.NoError(leaderServer.GetServer().SaveTTLConfig(map[string]interface{}{"schedule.enable-tikv-split-region": 0}, 0)) + re.NoError(leaderServer.GetServer().SaveTTLConfig(map[string]any{"schedule.enable-tikv-split-region": 0}, 0)) // wait ttl config takes effect time.Sleep(time.Second) diff --git a/tests/server/config/config_test.go b/tests/server/config/config_test.go index 98754127e55..1bc035cceca 100644 --- a/tests/server/config/config_test.go +++ b/tests/server/config/config_test.go @@ -58,7 +58,7 @@ func TestRateLimitConfigReload(t *testing.T) { limitCfg := make(map[string]ratelimit.DimensionConfig) limitCfg["GetRegions"] = ratelimit.DimensionConfig{QPS: 1} - input := map[string]interface{}{ + input := map[string]any{ "enable-rate-limit": "true", "limiter-config": limitCfg, } @@ -123,7 +123,7 @@ func (suite *configTestSuite) checkConfigAll(cluster *tests.TestCluster) { re.NoError(err) err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) re.NoError(err) - l := map[string]interface{}{ + l := map[string]any{ "location-labels": "zone,rack", "region-schedule-limit": 10, } @@ -132,7 +132,7 @@ func (suite *configTestSuite) checkConfigAll(cluster *tests.TestCluster) { err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) re.NoError(err) - l = map[string]interface{}{ + l = map[string]any{ "metric-storage": "http://127.0.0.1:9090", } postData, err = json.Marshal(l) @@ -150,7 +150,7 @@ func (suite *configTestSuite) checkConfigAll(cluster *tests.TestCluster) { re.Equal(newCfg, cfg) // the new way - l = map[string]interface{}{ + l = map[string]any{ "schedule.tolerant-size-ratio": 2.5, "schedule.enable-tikv-split-region": "false", "replication.location-labels": "idc,host", @@ -187,7 +187,7 @@ func (suite *configTestSuite) checkConfigAll(cluster *tests.TestCluster) { re.NoError(err) // illegal prefix - l = map[string]interface{}{ + l = map[string]any{ "replicate.max-replicas": 1, } postData, err = json.Marshal(l) @@ -198,7 +198,7 @@ func (suite *configTestSuite) checkConfigAll(cluster *tests.TestCluster) { re.NoError(err) // update prefix directly - l = map[string]interface{}{ + l = map[string]any{ "replication-mode": nil, } postData, err = json.Marshal(l) @@ -209,7 +209,7 @@ func (suite *configTestSuite) checkConfigAll(cluster *tests.TestCluster) { re.NoError(err) // config item not found - l = map[string]interface{}{ + l = map[string]any{ "schedule.region-limit": 10, } postData, err = json.Marshal(l) @@ -355,7 +355,7 @@ func (suite *configTestSuite) checkConfigDefault(cluster *tests.TestCluster) { re.NoError(err) err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) re.NoError(err) - l := map[string]interface{}{ + l := map[string]any{ "location-labels": "zone,rack", "region-schedule-limit": 10, } @@ -364,7 +364,7 @@ func (suite *configTestSuite) checkConfigDefault(cluster *tests.TestCluster) { err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusOK(re)) re.NoError(err) - l = map[string]interface{}{ + l = map[string]any{ "metric-storage": "http://127.0.0.1:9090", } postData, err = json.Marshal(l) @@ -393,7 +393,7 @@ func (suite *configTestSuite) checkConfigPDServer(cluster *tests.TestCluster) { urlPrefix := leaderServer.GetAddr() addrPost := urlPrefix + "/pd/api/v1/config" - ms := map[string]interface{}{ + ms := map[string]any{ "metric-storage": "", } postData, err := json.Marshal(ms) @@ -414,7 +414,7 @@ func (suite *configTestSuite) checkConfigPDServer(cluster *tests.TestCluster) { re.Equal(24*time.Hour, sc.MaxResetTSGap.Duration) } -var ttlConfig = map[string]interface{}{ +var ttlConfig = map[string]any{ "schedule.max-snapshot-count": 999, "schedule.enable-location-replacement": false, "schedule.max-merge-region-size": 999, @@ -428,7 +428,7 @@ var ttlConfig = map[string]interface{}{ "schedule.enable-tikv-split-region": false, } -var invalidTTLConfig = map[string]interface{}{ +var invalidTTLConfig = map[string]any{ "schedule.invalid-ttl-config": 0, } @@ -486,7 +486,7 @@ func (suite *configTestSuite) assertTTLConfigItemEqual( re *require.Assertions, cluster *tests.TestCluster, item string, - expectedValue interface{}, + expectedValue any, ) { checkFunc := func(options ttlConfigInterface) bool { switch item { @@ -550,7 +550,7 @@ func (suite *configTestSuite) checkConfigTTL(cluster *tests.TestCluster) { re.NoError(err) // only set max-merge-region-size - mergeConfig := map[string]interface{}{ + mergeConfig := map[string]any{ "schedule.max-merge-region-size": 999, } postData, err = json.Marshal(mergeConfig) @@ -563,7 +563,7 @@ func (suite *configTestSuite) checkConfigTTL(cluster *tests.TestCluster) { suite.assertTTLConfigItemEqual(re, cluster, "max-merge-region-keys", uint64(999*10000)) // on invalid value, we use default config - mergeConfig = map[string]interface{}{ + mergeConfig = map[string]any{ "schedule.enable-tikv-split-region": "invalid", } postData, err = json.Marshal(mergeConfig) @@ -588,7 +588,7 @@ func (suite *configTestSuite) checkTTLConflict(cluster *tests.TestCluster) { re.NoError(err) suite.assertTTLConfig(re, cluster, true) - cfg := map[string]interface{}{"max-snapshot-count": 30} + cfg := map[string]any{"max-snapshot-count": 30} postData, err = json.Marshal(cfg) re.NoError(err) addr = fmt.Sprintf("%s/pd/api/v1/config", urlPrefix) @@ -597,7 +597,7 @@ func (suite *configTestSuite) checkTTLConflict(cluster *tests.TestCluster) { addr = fmt.Sprintf("%s/pd/api/v1/config/schedule", urlPrefix) err = tu.CheckPostJSON(testDialClient, addr, postData, tu.StatusNotOK(re), tu.StringEqual(re, "\"need to clean up TTL first for schedule.max-snapshot-count\"\n")) re.NoError(err) - cfg = map[string]interface{}{"schedule.max-snapshot-count": 30} + cfg = map[string]any{"schedule.max-snapshot-count": 30} postData, err = json.Marshal(cfg) re.NoError(err) err = tu.CheckPostJSON(testDialClient, createTTLUrl(urlPrefix, 0), postData, tu.StatusOK(re)) diff --git a/tests/tso_cluster.go b/tests/tso_cluster.go index 2f80f7ff970..4021613df2a 100644 --- a/tests/tso_cluster.go +++ b/tests/tso_cluster.go @@ -84,7 +84,7 @@ func RestartTestTSOCluster( } wg.Wait() - errorMap.Range(func(key, value interface{}) bool { + errorMap.Range(func(key, value any) bool { if value != nil { err = value.(error) return false diff --git a/tools/pd-ctl/pdctl/command/config_command.go b/tools/pd-ctl/pdctl/command/config_command.go index 873ea222a4c..0e6fa7e9340 100644 --- a/tools/pd-ctl/pdctl/command/config_command.go +++ b/tools/pd-ctl/pdctl/command/config_command.go @@ -219,16 +219,16 @@ func showConfigCommandFunc(cmd *cobra.Command, args []string) { cmd.Printf("Failed to get config: %s\n", err) return } - allData := make(map[string]interface{}) + allData := make(map[string]any) err = json.Unmarshal([]byte(allR), &allData) if err != nil { cmd.Printf("Failed to unmarshal config: %s\n", err) return } - data := make(map[string]interface{}) + data := make(map[string]any) data["replication"] = allData["replication"] - scheduleConfig := make(map[string]interface{}) + scheduleConfig := make(map[string]any) scheduleConfigData, err := json.Marshal(allData["schedule"]) if err != nil { cmd.Printf("Failed to marshal schedule config: %s\n", err) @@ -335,8 +335,8 @@ func showServerCommandFunc(cmd *cobra.Command, args []string) { } func postConfigDataWithPath(cmd *cobra.Command, key, value, path string) error { - var val interface{} - data := make(map[string]interface{}) + var val any + data := make(map[string]any) val, err := strconv.ParseFloat(value, 64) if err != nil { val = value @@ -381,7 +381,7 @@ func postLabelProperty(cmd *cobra.Command, action string, args []string) { cmd.Println(cmd.UsageString()) return } - input := map[string]interface{}{ + input := map[string]any{ "type": args[0], "action": action, "label-key": args[1], @@ -396,7 +396,7 @@ func setClusterVersionCommandFunc(cmd *cobra.Command, args []string) { cmd.Println(cmd.UsageString()) return } - input := map[string]interface{}{ + input := map[string]any{ "cluster-version": args[0], } postJSON(cmd, clusterVersionPrefix, input) @@ -404,7 +404,7 @@ func setClusterVersionCommandFunc(cmd *cobra.Command, args []string) { func setReplicationModeCommandFunc(cmd *cobra.Command, args []string) { if len(args) == 1 { - postJSON(cmd, replicationModePrefix, map[string]interface{}{"replication-mode": args[0]}) + postJSON(cmd, replicationModePrefix, map[string]any{"replication-mode": args[0]}) } else if len(args) == 3 { t := reflectutil.FindFieldByJSONTag(reflect.TypeOf(config.ReplicationModeConfig{}), []string{args[0], args[1]}) if t != nil && t.Kind() == reflect.Int { @@ -414,10 +414,10 @@ func setReplicationModeCommandFunc(cmd *cobra.Command, args []string) { cmd.Printf("value %v cannot covert to number: %v", args[2], err) return } - postJSON(cmd, replicationModePrefix, map[string]interface{}{args[0]: map[string]interface{}{args[1]: arg2}}) + postJSON(cmd, replicationModePrefix, map[string]any{args[0]: map[string]any{args[1]: arg2}}) return } - postJSON(cmd, replicationModePrefix, map[string]interface{}{args[0]: map[string]string{args[1]: args[2]}}) + postJSON(cmd, replicationModePrefix, map[string]any{args[0]: map[string]string{args[1]: args[2]}}) } else { cmd.Println(cmd.UsageString()) } @@ -674,7 +674,7 @@ func updateRuleGroupFunc(cmd *cobra.Command, args []string) { cmd.Printf("override %s should be a boolean\n", args[2]) return } - postJSON(cmd, ruleGroupPrefix, map[string]interface{}{ + postJSON(cmd, ruleGroupPrefix, map[string]any{ "id": args[0], "index": index, "override": override, diff --git a/tools/pd-ctl/pdctl/command/global.go b/tools/pd-ctl/pdctl/command/global.go index 806ad4ecc53..d1ea1faa236 100644 --- a/tools/pd-ctl/pdctl/command/global.go +++ b/tools/pd-ctl/pdctl/command/global.go @@ -186,7 +186,7 @@ func getEndpoints(cmd *cobra.Command) []string { return strings.Split(addrs, ",") } -func requestJSON(cmd *cobra.Command, method, prefix string, input map[string]interface{}) { +func requestJSON(cmd *cobra.Command, method, prefix string, input map[string]any) { data, err := json.Marshal(input) if err != nil { cmd.Println(err) @@ -231,11 +231,11 @@ func requestJSON(cmd *cobra.Command, method, prefix string, input map[string]int cmd.Printf("Success! %s\n", strings.Trim(string(msg), "\"")) } -func postJSON(cmd *cobra.Command, prefix string, input map[string]interface{}) { +func postJSON(cmd *cobra.Command, prefix string, input map[string]any) { requestJSON(cmd, http.MethodPost, prefix, input) } -func patchJSON(cmd *cobra.Command, prefix string, input map[string]interface{}) { +func patchJSON(cmd *cobra.Command, prefix string, input map[string]any) { requestJSON(cmd, http.MethodPatch, prefix, input) } diff --git a/tools/pd-ctl/pdctl/command/hot_command.go b/tools/pd-ctl/pdctl/command/hot_command.go index 09160d8f2b9..f6be9c7176b 100644 --- a/tools/pd-ctl/pdctl/command/hot_command.go +++ b/tools/pd-ctl/pdctl/command/hot_command.go @@ -216,7 +216,7 @@ func parseOptionalArgs(prefix string, param string, args []string) (string, erro return prefix, nil } -func parseHotRegionsHistoryArgs(args []string) (map[string]interface{}, error) { +func parseHotRegionsHistoryArgs(args []string) (map[string]any, error) { startTime, err := strconv.ParseInt(args[0], 10, 64) if err != nil { return nil, errors.Errorf("start_time should be a number,but got %s", args[0]) @@ -225,7 +225,7 @@ func parseHotRegionsHistoryArgs(args []string) (map[string]interface{}, error) { if err != nil { return nil, errors.Errorf("end_time should be a number,but got %s", args[1]) } - input := map[string]interface{}{ + input := map[string]any{ "start_time": startTime, "end_time": endTime, } diff --git a/tools/pd-ctl/pdctl/command/keyspace_group_command.go b/tools/pd-ctl/pdctl/command/keyspace_group_command.go index 08d5c875a18..9c3a45f4744 100644 --- a/tools/pd-ctl/pdctl/command/keyspace_group_command.go +++ b/tools/pd-ctl/pdctl/command/keyspace_group_command.go @@ -192,7 +192,7 @@ func splitKeyspaceGroupCommandFunc(cmd *cobra.Command, args []string) { } keyspaces = append(keyspaces, uint32(id)) } - postJSON(cmd, fmt.Sprintf("%s/%s/split", keyspaceGroupsPrefix, args[0]), map[string]interface{}{ + postJSON(cmd, fmt.Sprintf("%s/%s/split", keyspaceGroupsPrefix, args[0]), map[string]any{ "new-id": uint32(newID), "keyspaces": keyspaces, }) @@ -223,7 +223,7 @@ func splitRangeKeyspaceGroupCommandFunc(cmd *cobra.Command, args []string) { cmd.Printf("Failed to parse the end keyspace ID: %s\n", err) return } - postJSON(cmd, fmt.Sprintf("%s/%s/split", keyspaceGroupsPrefix, args[0]), map[string]interface{}{ + postJSON(cmd, fmt.Sprintf("%s/%s/split", keyspaceGroupsPrefix, args[0]), map[string]any{ "new-id": uint32(newID), "start-keyspace-id": uint32(startKeyspaceID), "end-keyspace-id": uint32(endKeyspaceID), @@ -251,7 +251,7 @@ func finishSplitKeyspaceGroupCommandFunc(cmd *cobra.Command, args []string) { func mergeKeyspaceGroupCommandFunc(cmd *cobra.Command, args []string) { var ( targetGroupID uint32 - params = map[string]interface{}{} + params = map[string]any{} argNum = len(args) ) mergeAll, err := cmd.Flags().GetBool("all") @@ -334,7 +334,7 @@ func setNodesKeyspaceGroupCommandFunc(cmd *cobra.Command, args []string) { } nodes = append(nodes, arg) } - patchJSON(cmd, fmt.Sprintf("%s/%s", keyspaceGroupsPrefix, args[0]), map[string]interface{}{ + patchJSON(cmd, fmt.Sprintf("%s/%s", keyspaceGroupsPrefix, args[0]), map[string]any{ "Nodes": nodes, }) } @@ -369,7 +369,7 @@ func setPriorityKeyspaceGroupCommandFunc(cmd *cobra.Command, args []string) { return } - patchJSON(cmd, fmt.Sprintf("%s/%s/%s", keyspaceGroupsPrefix, args[0], node), map[string]interface{}{ + patchJSON(cmd, fmt.Sprintf("%s/%s/%s", keyspaceGroupsPrefix, args[0], node), map[string]any{ "Priority": priority, }) } diff --git a/tools/pd-ctl/pdctl/command/member_command.go b/tools/pd-ctl/pdctl/command/member_command.go index 677f7570131..c16a879429c 100644 --- a/tools/pd-ctl/pdctl/command/member_command.go +++ b/tools/pd-ctl/pdctl/command/member_command.go @@ -170,7 +170,7 @@ func setLeaderPriorityFunc(cmd *cobra.Command, args []string) { cmd.Printf("failed to parse priority: %v\n", err) return } - data := map[string]interface{}{"leader-priority": priority} + data := map[string]any{"leader-priority": priority} reqData, _ := json.Marshal(data) _, err = doRequest(cmd, prefix, http.MethodPost, http.Header{"Content-Type": {"application/json"}}, WithBody(bytes.NewBuffer(reqData))) if err != nil { diff --git a/tools/pd-ctl/pdctl/command/operator.go b/tools/pd-ctl/pdctl/command/operator.go index 1db237b55d0..c57e07db75a 100644 --- a/tools/pd-ctl/pdctl/command/operator.go +++ b/tools/pd-ctl/pdctl/command/operator.go @@ -158,7 +158,7 @@ func transferLeaderCommandFunc(cmd *cobra.Command, args []string) { return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["region_id"] = ids[0] input["to_store_id"] = ids[1] @@ -192,7 +192,7 @@ func transferRegionCommandFunc(cmd *cobra.Command, args []string) { return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["region_id"] = ids[0] input["to_store_ids"] = ids[1:] @@ -224,7 +224,7 @@ func transferPeerCommandFunc(cmd *cobra.Command, args []string) { return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["region_id"] = ids[0] input["from_store_id"] = ids[1] @@ -254,7 +254,7 @@ func addPeerCommandFunc(cmd *cobra.Command, args []string) { return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["region_id"] = ids[0] input["store_id"] = ids[1] @@ -283,7 +283,7 @@ func addLearnerCommandFunc(cmd *cobra.Command, args []string) { return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["region_id"] = ids[0] input["store_id"] = ids[1] @@ -312,7 +312,7 @@ func mergeRegionCommandFunc(cmd *cobra.Command, args []string) { return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["source_region_id"] = ids[0] input["target_region_id"] = ids[1] @@ -341,7 +341,7 @@ func removePeerCommandFunc(cmd *cobra.Command, args []string) { return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["region_id"] = ids[0] input["store_id"] = ids[1] @@ -381,7 +381,7 @@ func splitRegionCommandFunc(cmd *cobra.Command, args []string) { return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["region_id"] = ids[0] input["policy"] = policy @@ -415,7 +415,7 @@ func scatterRegionCommandFunc(cmd *cobra.Command, args []string) { return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["region_id"] = ids[0] postJSON(cmd, operatorsPrefix, input) diff --git a/tools/pd-ctl/pdctl/command/plugin_command.go b/tools/pd-ctl/pdctl/command/plugin_command.go index a713c8fd063..9716d1d7755 100644 --- a/tools/pd-ctl/pdctl/command/plugin_command.go +++ b/tools/pd-ctl/pdctl/command/plugin_command.go @@ -71,7 +71,7 @@ func sendPluginCommand(cmd *cobra.Command, action string, args []string) { cmd.Println(cmd.Usage()) return } - data := map[string]interface{}{ + data := map[string]any{ "plugin-path": args[0], } reqData, err := json.Marshal(data) diff --git a/tools/pd-ctl/pdctl/command/resource_manager_command.go b/tools/pd-ctl/pdctl/command/resource_manager_command.go index 8bc5ea85977..fe7913b0de6 100644 --- a/tools/pd-ctl/pdctl/command/resource_manager_command.go +++ b/tools/pd-ctl/pdctl/command/resource_manager_command.go @@ -69,12 +69,12 @@ func newConfigControllerSetCommand() *cobra.Command { return } - var val interface{} + var val any val, err := strconv.ParseFloat(args[1], 64) if err != nil { val = args[1] } - data := map[string]interface{}{args[0]: val} + data := map[string]any{args[0]: val} jsonData, err := json.Marshal(data) if err != nil { cmd.Println(err) diff --git a/tools/pd-ctl/pdctl/command/scheduler.go b/tools/pd-ctl/pdctl/command/scheduler.go index 695576edf84..d1dfe95c4d4 100644 --- a/tools/pd-ctl/pdctl/command/scheduler.go +++ b/tools/pd-ctl/pdctl/command/scheduler.go @@ -73,7 +73,7 @@ func pauseSchedulerCommandFunc(cmd *cobra.Command, args []string) { return } path := schedulersPrefix + "/" + args[0] - input := map[string]interface{}{"delay": delay} + input := map[string]any{"delay": delay} postJSON(cmd, path, input) } @@ -93,7 +93,7 @@ func resumeSchedulerCommandFunc(cmd *cobra.Command, args []string) { return } path := schedulersPrefix + "/" + args[0] - input := map[string]interface{}{"delay": 0} + input := map[string]any{"delay": 0} postJSON(cmd, path, input) } @@ -217,7 +217,7 @@ func addSchedulerForStoreCommandFunc(cmd *cobra.Command, args []string) { return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["store_id"] = storeID postJSON(cmd, schedulersPrefix, input) @@ -268,7 +268,7 @@ func addSchedulerForShuffleHotRegionCommandFunc(cmd *cobra.Command, args []strin } limit = l } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["limit"] = limit postJSON(cmd, schedulersPrefix, input) @@ -385,7 +385,7 @@ func NewSlowTrendEvictLeaderSchedulerCommand() *cobra.Command { } func addSchedulerForSplitBucketCommandFunc(cmd *cobra.Command, args []string) { - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() postJSON(cmd, schedulersPrefix, input) } @@ -395,7 +395,7 @@ func addSchedulerForGrantHotRegionCommandFunc(cmd *cobra.Command, args []string) cmd.Println(cmd.UsageString()) return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["store-leader-id"] = args[0] input["store-id"] = args[1] @@ -407,7 +407,7 @@ func addSchedulerCommandFunc(cmd *cobra.Command, args []string) { cmd.Println(cmd.UsageString()) return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() postJSON(cmd, schedulersPrefix, input) } @@ -439,7 +439,7 @@ func addSchedulerForScatterRangeCommandFunc(cmd *cobra.Command, args []string) { return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = cmd.Name() input["start_key"] = url.QueryEscape(startKey) input["end_key"] = url.QueryEscape(endKey) @@ -635,7 +635,7 @@ func addStoreToSchedulerConfig(cmd *cobra.Command, schedulerName string, args [] cmd.Println(err) return } - input := make(map[string]interface{}) + input := make(map[string]any) input["name"] = schedulerName input["store_id"] = storeID @@ -697,7 +697,7 @@ func setGrantHotRegionCommandFunc(cmd *cobra.Command, schedulerName string, args cmd.Println(cmd.UsageString()) return } - input := make(map[string]interface{}) + input := make(map[string]any) input["store-leader-id"] = args[0] input["store-id"] = args[1] postJSON(cmd, path.Join(schedulerConfigPrefix, schedulerName, "config"), input) @@ -708,8 +708,8 @@ func postSchedulerConfigCommandFunc(cmd *cobra.Command, schedulerName string, ar cmd.Println(cmd.UsageString()) return } - var val interface{} - input := make(map[string]interface{}) + var val any + input := make(map[string]any) key, value := args[0], args[1] val, err := strconv.ParseFloat(value, 64) if err != nil { diff --git a/tools/pd-ctl/pdctl/command/store_command.go b/tools/pd-ctl/pdctl/command/store_command.go index 7f466dfb3b5..085483cc5df 100644 --- a/tools/pd-ctl/pdctl/command/store_command.go +++ b/tools/pd-ctl/pdctl/command/store_command.go @@ -275,7 +275,7 @@ func storeLimitSceneCommandFunc(cmd *cobra.Command, args []string) { if len(args) == 3 { prefix = path.Join(prefix, fmt.Sprintf("?type=%s", args[2])) } - postJSON(cmd, prefix, map[string]interface{}{scene: rate}) + postJSON(cmd, prefix, map[string]any{scene: rate}) } } @@ -531,7 +531,7 @@ func labelStoreCommandFunc(cmd *cobra.Command, args []string) { return } - labels := make(map[string]interface{}) + labels := make(map[string]any) // useEqual is used to compatible the old way // TODO: remove old way useEqual := true @@ -584,7 +584,7 @@ func setStoreWeightCommandFunc(cmd *cobra.Command, args []string) { return } prefix := fmt.Sprintf(path.Join(storePrefix, "weight"), args[0]) - postJSON(cmd, prefix, map[string]interface{}{ + postJSON(cmd, prefix, map[string]any{ "leader": leader, "region": region, }) @@ -620,7 +620,7 @@ func storeLimitCommandFunc(cmd *cobra.Command, args []string) { } else { prefix = fmt.Sprintf(path.Join(storePrefix, "limit"), args[0]) } - postInput := map[string]interface{}{ + postInput := map[string]any{ "rate": rate, } if argsCount == 3 { @@ -631,7 +631,7 @@ func storeLimitCommandFunc(cmd *cobra.Command, args []string) { if args[0] != "all" { cmd.Println("Labels are an option of set all stores limit.") } else { - postInput := map[string]interface{}{} + postInput := map[string]any{} prefix := storesLimitPrefix ratePos := argsCount - 1 if argsCount%2 == 1 { @@ -648,7 +648,7 @@ func storeLimitCommandFunc(cmd *cobra.Command, args []string) { return } postInput["rate"] = rate - labels := make(map[string]interface{}) + labels := make(map[string]any) for i := 1; i < ratePos; i += 2 { labels[args[i]] = args[i+1] } @@ -728,7 +728,7 @@ func setAllLimitCommandFunc(cmd *cobra.Command, args []string) { return } prefix := storesLimitPrefix - input := map[string]interface{}{ + input := map[string]any{ "rate": rate, } if len(args) == 2 { diff --git a/tools/pd-ctl/pdctl/command/unsafe_command.go b/tools/pd-ctl/pdctl/command/unsafe_command.go index 8494eca4b5d..66ef8e6c934 100644 --- a/tools/pd-ctl/pdctl/command/unsafe_command.go +++ b/tools/pd-ctl/pdctl/command/unsafe_command.go @@ -61,7 +61,7 @@ func NewRemoveFailedStoresShowCommand() *cobra.Command { func removeFailedStoresCommandFunc(cmd *cobra.Command, args []string) { prefix := fmt.Sprintf("%s/remove-failed-stores", unsafePrefix) - postInput := make(map[string]interface{}, 3) + postInput := make(map[string]any, 3) autoDetect, err := cmd.Flags().GetBool("auto-detect") if err != nil { diff --git a/tools/pd-ctl/tests/config/config_test.go b/tools/pd-ctl/tests/config/config_test.go index 4a585851227..65ce3cce6d4 100644 --- a/tools/pd-ctl/tests/config/config_test.go +++ b/tools/pd-ctl/tests/config/config_test.go @@ -49,8 +49,8 @@ var testDialClient = &http.Client{ type testCase struct { name string - value interface{} - read func(scheduleConfig *sc.ScheduleConfig) interface{} + value any + read func(scheduleConfig *sc.ScheduleConfig) any } func (t *testCase) judge(re *require.Assertions, scheduleConfigs ...*sc.ScheduleConfig) { @@ -282,20 +282,20 @@ func (suite *configTestSuite) checkConfig(cluster *pdTests.TestCluster) { // test config read and write testCases := []testCase{ - {"leader-schedule-limit", uint64(64), func(scheduleConfig *sc.ScheduleConfig) interface{} { + {"leader-schedule-limit", uint64(64), func(scheduleConfig *sc.ScheduleConfig) any { return scheduleConfig.LeaderScheduleLimit - }}, {"hot-region-schedule-limit", uint64(64), func(scheduleConfig *sc.ScheduleConfig) interface{} { + }}, {"hot-region-schedule-limit", uint64(64), func(scheduleConfig *sc.ScheduleConfig) any { return scheduleConfig.HotRegionScheduleLimit - }}, {"hot-region-cache-hits-threshold", uint64(5), func(scheduleConfig *sc.ScheduleConfig) interface{} { + }}, {"hot-region-cache-hits-threshold", uint64(5), func(scheduleConfig *sc.ScheduleConfig) any { return scheduleConfig.HotRegionCacheHitsThreshold - }}, {"enable-remove-down-replica", false, func(scheduleConfig *sc.ScheduleConfig) interface{} { + }}, {"enable-remove-down-replica", false, func(scheduleConfig *sc.ScheduleConfig) any { return scheduleConfig.EnableRemoveDownReplica }}, - {"enable-debug-metrics", true, func(scheduleConfig *sc.ScheduleConfig) interface{} { + {"enable-debug-metrics", true, func(scheduleConfig *sc.ScheduleConfig) any { return scheduleConfig.EnableDebugMetrics }}, // set again - {"enable-debug-metrics", true, func(scheduleConfig *sc.ScheduleConfig) interface{} { + {"enable-debug-metrics", true, func(scheduleConfig *sc.ScheduleConfig) any { return scheduleConfig.EnableDebugMetrics }}, } diff --git a/tools/pd-ctl/tests/scheduler/scheduler_test.go b/tools/pd-ctl/tests/scheduler/scheduler_test.go index ab96d430523..ef6301234a6 100644 --- a/tools/pd-ctl/tests/scheduler/scheduler_test.go +++ b/tools/pd-ctl/tests/scheduler/scheduler_test.go @@ -153,9 +153,9 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { }) } - checkSchedulerConfigCommand := func(expectedConfig map[string]interface{}, schedulerName string) { + checkSchedulerConfigCommand := func(expectedConfig map[string]any, schedulerName string) { testutil.Eventually(re, func() bool { - configInfo := make(map[string]interface{}) + configInfo := make(map[string]any) mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", schedulerName}, &configInfo) return reflect.DeepEqual(expectedConfig, configInfo) }) @@ -238,8 +238,8 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { checkSchedulerCommand(args, expected) // scheduler config show command - expectedConfig := make(map[string]interface{}) - expectedConfig["store-id-ranges"] = map[string]interface{}{"2": []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}}} + expectedConfig := make(map[string]any) + expectedConfig["store-id-ranges"] = map[string]any{"2": []any{map[string]any{"end-key": "", "start-key": ""}}} checkSchedulerConfigCommand(expectedConfig, schedulers[idx]) checkStorePause([]uint64{2}, schedulers[idx]) @@ -256,7 +256,7 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { // check update success checkSchedulerCommand(args, expected) - expectedConfig["store-id-ranges"] = map[string]interface{}{"2": []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}}, "3": []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}}} + expectedConfig["store-id-ranges"] = map[string]any{"2": []any{map[string]any{"end-key": "", "start-key": ""}}, "3": []any{map[string]any{"end-key": "", "start-key": ""}}} checkSchedulerConfigCommand(expectedConfig, schedulers[idx]) checkStorePause([]uint64{2, 3}, schedulers[idx]) @@ -298,7 +298,7 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { checkSchedulerCommand(args, expected) // check add success - expectedConfig["store-id-ranges"] = map[string]interface{}{"2": []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}}, "4": []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}}} + expectedConfig["store-id-ranges"] = map[string]any{"2": []any{map[string]any{"end-key": "", "start-key": ""}}, "4": []any{map[string]any{"end-key": "", "start-key": ""}}} checkSchedulerConfigCommand(expectedConfig, schedulers[idx]) checkStorePause([]uint64{2, 4}, schedulers[idx]) @@ -315,7 +315,7 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { checkSchedulerCommand(args, expected) // check remove success - expectedConfig["store-id-ranges"] = map[string]interface{}{"2": []interface{}{map[string]interface{}{"end-key": "", "start-key": ""}}} + expectedConfig["store-id-ranges"] = map[string]any{"2": []any{map[string]any{"end-key": "", "start-key": ""}}} checkSchedulerConfigCommand(expectedConfig, schedulers[idx]) checkStorePause([]uint64{2}, schedulers[idx]) @@ -363,9 +363,9 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { "balance-witness-scheduler": true, "evict-slow-store-scheduler": true, }) - var conf3 map[string]interface{} - expected3 := map[string]interface{}{ - "store-id": []interface{}{float64(1), float64(2), float64(3)}, + var conf3 map[string]any + expected3 := map[string]any{ + "store-id": []any{float64(1), float64(2), float64(3)}, "store-leader-id": float64(1), } mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", "grant-hot-region-scheduler"}, &conf3) @@ -404,7 +404,7 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { }) // test hot region config - expected1 := map[string]interface{}{ + expected1 := map[string]any{ "min-hot-byte-rate": float64(100), "min-hot-key-rate": float64(10), "min-hot-query-rate": float64(10), @@ -418,23 +418,23 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { "minor-dec-ratio": 0.99, "src-tolerance-ratio": 1.05, "dst-tolerance-ratio": 1.05, - "read-priorities": []interface{}{"byte", "key"}, - "write-leader-priorities": []interface{}{"key", "byte"}, - "write-peer-priorities": []interface{}{"byte", "key"}, + "read-priorities": []any{"byte", "key"}, + "write-leader-priorities": []any{"key", "byte"}, + "write-peer-priorities": []any{"byte", "key"}, "strict-picking-store": "true", "enable-for-tiflash": "true", "rank-formula-version": "v2", "split-thresholds": 0.2, } - checkHotSchedulerConfig := func(expect map[string]interface{}) { + checkHotSchedulerConfig := func(expect map[string]any) { testutil.Eventually(re, func() bool { - var conf1 map[string]interface{} + var conf1 map[string]any mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", "balance-hot-region-scheduler"}, &conf1) return reflect.DeepEqual(expect, conf1) }) } - var conf map[string]interface{} + var conf map[string]any mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", "balance-hot-region-scheduler", "list"}, &conf) re.Equal(expected1, conf) mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", "balance-hot-region-scheduler", "show"}, &conf) @@ -446,7 +446,7 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { echo = mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", "balance-hot-region-scheduler", "set", "read-priorities", "byte,key"}, nil) re.Contains(echo, "Success!") - expected1["read-priorities"] = []interface{}{"byte", "key"} + expected1["read-priorities"] = []any{"byte", "key"} checkHotSchedulerConfig(expected1) echo = mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", "balance-hot-region-scheduler", "set", "read-priorities", "key"}, nil) @@ -454,7 +454,7 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { checkHotSchedulerConfig(expected1) echo = mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", "balance-hot-region-scheduler", "set", "read-priorities", "key,byte"}, nil) re.Contains(echo, "Success!") - expected1["read-priorities"] = []interface{}{"key", "byte"} + expected1["read-priorities"] = []any{"key", "byte"} checkHotSchedulerConfig(expected1) echo = mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", "balance-hot-region-scheduler", "set", "read-priorities", "foo,bar"}, nil) re.Contains(echo, "Failed!") @@ -518,8 +518,8 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { re.Contains(echo, "Success") // test balance leader config - conf = make(map[string]interface{}) - conf1 := make(map[string]interface{}) + conf = make(map[string]any) + conf1 := make(map[string]any) mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", "balance-leader-scheduler", "show"}, &conf) re.Equal(4., conf["batch"]) echo = mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", "balance-leader-scheduler", "set", "batch", "3"}, nil) @@ -556,7 +556,7 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { }) echo = mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", schedulerName, "set", "recovery-duration", "100"}, nil) re.Contains(echo, "Success! Config updated.") - conf = make(map[string]interface{}) + conf = make(map[string]any) testutil.Eventually(re, func() bool { mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", schedulerName, "show"}, &conf) return conf["recovery-duration"] == 100. @@ -580,7 +580,7 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { }) echo = mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", "shuffle-hot-region-scheduler", "set", "limit", "127"}, nil) re.Contains(echo, "Success!") - conf = make(map[string]interface{}) + conf = make(map[string]any) testutil.Eventually(re, func() bool { mustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "config", "shuffle-hot-region-scheduler", "show"}, &conf) return conf["limit"] == 127. @@ -607,7 +607,7 @@ func (suite *schedulerTestSuite) checkScheduler(cluster *pdTests.TestCluster) { checkSchedulerWithStatusCommand("paused", []string{ "balance-leader-scheduler", }) - result := make(map[string]interface{}) + result := make(map[string]any) testutil.Eventually(re, func() bool { mightExec(re, cmd, []string{"-u", pdAddr, "scheduler", "describe", "balance-leader-scheduler"}, &result) return len(result) != 0 && result["status"] == "paused" && result["summary"] == "" @@ -644,7 +644,7 @@ func (suite *schedulerTestSuite) checkSchedulerDiagnostic(cluster *pdTests.TestC cmd := ctl.GetRootCmd() checkSchedulerDescribeCommand := func(schedulerName, expectedStatus, expectedSummary string) { - result := make(map[string]interface{}) + result := make(map[string]any) testutil.Eventually(re, func() bool { mightExec(re, cmd, []string{"-u", pdAddr, "scheduler", "describe", schedulerName}, &result) return len(result) != 0 && expectedStatus == result["status"] && expectedSummary == result["summary"] @@ -696,7 +696,7 @@ func (suite *schedulerTestSuite) checkSchedulerDiagnostic(cluster *pdTests.TestC checkSchedulerDescribeCommand("balance-leader-scheduler", "normal", "") } -func mustExec(re *require.Assertions, cmd *cobra.Command, args []string, v interface{}) string { +func mustExec(re *require.Assertions, cmd *cobra.Command, args []string, v any) string { output, err := tests.ExecuteCommand(cmd, args...) re.NoError(err) if v == nil { @@ -706,7 +706,7 @@ func mustExec(re *require.Assertions, cmd *cobra.Command, args []string, v inter return "" } -func mightExec(re *require.Assertions, cmd *cobra.Command, args []string, v interface{}) { +func mightExec(re *require.Assertions, cmd *cobra.Command, args []string, v any) { output, err := tests.ExecuteCommand(cmd, args...) re.NoError(err) if v == nil { diff --git a/tools/pd-ctl/tests/store/store_test.go b/tools/pd-ctl/tests/store/store_test.go index d0bca55e836..9cb5f795a24 100644 --- a/tools/pd-ctl/tests/store/store_test.go +++ b/tools/pd-ctl/tests/store/store_test.go @@ -274,7 +274,7 @@ func TestStore(t *testing.T) { output, err = tests.ExecuteCommand(cmd, args...) re.NoError(err) - allAddPeerLimit := make(map[string]map[string]interface{}) + allAddPeerLimit := make(map[string]map[string]any) json.Unmarshal(output, &allAddPeerLimit) re.Equal(float64(20), allAddPeerLimit["1"]["add-peer"].(float64)) re.Equal(float64(20), allAddPeerLimit["3"]["add-peer"].(float64)) @@ -285,7 +285,7 @@ func TestStore(t *testing.T) { output, err = tests.ExecuteCommand(cmd, args...) re.NoError(err) - allRemovePeerLimit := make(map[string]map[string]interface{}) + allRemovePeerLimit := make(map[string]map[string]any) json.Unmarshal(output, &allRemovePeerLimit) re.Equal(float64(20), allRemovePeerLimit["1"]["remove-peer"].(float64)) re.Equal(float64(25), allRemovePeerLimit["3"]["remove-peer"].(float64)) diff --git a/tools/pd-simulator/simulator/client.go b/tools/pd-simulator/simulator/client.go index 8dd1ee1646e..b461bffebb0 100644 --- a/tools/pd-simulator/simulator/client.go +++ b/tools/pd-simulator/simulator/client.go @@ -340,7 +340,7 @@ func (c *client) PutPDConfig(config *PDConfig) error { } if len(config.LocationLabels) > 0 { path := fmt.Sprintf("%s/%s/config", c.url, httpPrefix) - data := make(map[string]interface{}) + data := make(map[string]any) data["location-labels"] = config.LocationLabels content, err := json.Marshal(data) if err != nil {