Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions errors.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ error = '''
the option %s does not exist
'''

["PD:apiutil:ErrOptionTypeInvalid"]
error = '''
the type of option %s is invalid
'''

["PD:apiutil:ErrRedirect"]
error = '''
redirect failed
Expand Down
1 change: 1 addition & 0 deletions pkg/errs/errno.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ var (
var (
ErrRedirect = errors.Normalize("redirect failed", errors.RFCCodeText("PD:apiutil:ErrRedirect"))
ErrOptionNotExist = errors.Normalize("the option %s does not exist", errors.RFCCodeText("PD:apiutil:ErrOptionNotExist"))
ErrOptionTypeInvalid = errors.Normalize("the type of option %s is invalid", errors.RFCCodeText("PD:apiutil:ErrOptionTypeInvalid"))
ErrRedirectNoLeader = errors.Normalize("redirect finds no leader", errors.RFCCodeText("PD:apiutil:ErrRedirectNoLeader"))
ErrRedirectToNotLeader = errors.Normalize("redirect to not leader", errors.RFCCodeText("PD:apiutil:ErrRedirectToNotLeader"))
ErrRedirectToNotPrimary = errors.Normalize("redirect to not primary", errors.RFCCodeText("PD:apiutil:ErrRedirectToNotPrimary"))
Expand Down
47 changes: 36 additions & 11 deletions pkg/schedule/schedulers/balance_range.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,27 +90,52 @@ func (handler *balanceRangeSchedulerHandler) addJob(w http.ResponseWriter, r *ht
Status: pending,
Timeout: defaultJobTimeout,
}
job.Engine = input["engine"].(string)
engine, ok := input["engine"].(string)
if !ok || len(engine) == 0 {
handler.rd.JSON(w, http.StatusBadRequest, "engine is required and must be a string")
return
}
job.Engine = engine
if job.Engine != core.EngineTiFlash && job.Engine != core.EngineTiKV {
handler.rd.JSON(w, http.StatusBadRequest, fmt.Sprintf("engine:%s must be tikv or tiflash", input["engine"].(string)))
handler.rd.JSON(w, http.StatusBadRequest, fmt.Sprintf("engine:%s must be tikv or tiflash", job.Engine))
return
}
job.Rule = core.NewRule(input["rule"].(string))
ruleStr, ok := input["rule"].(string)
if !ok || len(ruleStr) == 0 {
handler.rd.JSON(w, http.StatusBadRequest, "rule is required and must be a string")
return
}
job.Rule = core.NewRule(ruleStr)
if job.Rule != core.LeaderScatter && job.Rule != core.PeerScatter && job.Rule != core.LearnerScatter {
handler.rd.JSON(w, http.StatusBadRequest, fmt.Sprintf("rule:%s must be leader-scatter, learner-scatter or peer-scatter",
input["engine"].(string)))
ruleStr))
return
}

job.Alias = input["alias"].(string)
timeoutStr, ok := input["timeout"].(string)
if ok && len(timeoutStr) > 0 {
timeout, err := time.ParseDuration(timeoutStr)
if err != nil {
handler.rd.JSON(w, http.StatusBadRequest, fmt.Sprintf("timeout:%s is invalid", input["timeout"].(string)))
alias, ok := input["alias"].(string)
if !ok || len(alias) == 0 {
handler.rd.JSON(w, http.StatusBadRequest, "alias is required and must be a string")
return
}
job.Alias = alias
if timeoutVal, exists := input["timeout"]; exists {
timeoutStr, ok := timeoutVal.(string)
if !ok {
handler.rd.JSON(w, http.StatusBadRequest, "timeout must be a string")
return
}
job.Timeout = timeout
if len(timeoutStr) > 0 {
timeout, err := time.ParseDuration(timeoutStr)
if err != nil {
handler.rd.JSON(w, http.StatusBadRequest, fmt.Sprintf("timeout:%s is invalid", timeoutStr))
return
}
if timeout <= 0 {
handler.rd.JSON(w, http.StatusBadRequest, "timeout must be positive")
return
}
job.Timeout = timeout
}
}

keys, err := keyutil.DecodeHTTPKeyRanges(input)
Expand Down
81 changes: 81 additions & 0 deletions pkg/schedule/schedulers/balance_range_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,17 @@
package schedulers

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"

"github.com/stretchr/testify/require"
"github.com/unrolled/render"

"github.com/pingcap/failpoint"

Expand Down Expand Up @@ -516,3 +521,79 @@ func TestPersistFail(t *testing.T) {
re.ErrorContains(conf.gcLocked(), errMsg)
re.Len(conf.jobs, 1)
}

func TestAddBalanceRangeJobWithInvalidFieldType(t *testing.T) {
re := require.New(t)
conf := &balanceRangeSchedulerConfig{
schedulerConfig: &baseSchedulerConfig{},
jobs: make([]*balanceRangeSchedulerJob, 0),
}
conf.init("test", storage.NewStorageWithMemoryBackend(), conf)
handler := &balanceRangeSchedulerHandler{
config: conf,
rd: render.New(render.Options{IndentJSON: true}),
}
count := 0
checkFn := func(data []byte, pass bool) {
req := httptest.NewRequest(http.MethodPut, "/job", bytes.NewReader(data))
resp := httptest.NewRecorder()
re.NotPanics(func() {
handler.addJob(resp, req)
})
if pass {
re.Equal(http.StatusOK, resp.Code)
count++
re.Len(conf.jobs, count)
} else {
re.Equal(http.StatusBadRequest, resp.Code)
}
re.Len(conf.jobs, count)
}

// invalid engine type
body, err := json.Marshal(map[string]any{
"alias": "a",
"engine": 1,
"rule": "leader-scatter",
"start-key": "100",
"end-key": "200",
})
re.NoError(err)
checkFn(body, false)

// invalid timeout type
body, err = json.Marshal(map[string]any{
"alias": "a",
"engine": "tikv",
"rule": "leader-scatter",
"start-key": "100",
"end-key": "200",
"timeout": "123",
})
re.NoError(err)
checkFn(body, false)

// normal case
body, err = json.Marshal(map[string]any{
"alias": "a",
"engine": "tikv",
"rule": "leader-scatter",
"start-key": "100",
"end-key": "200",
"timeout": "123s",
})
re.NoError(err)
checkFn(body, true)

// invalidate case
body, err = json.Marshal(map[string]any{
"alias": "a",
"engine": "tikv",
"rule": "leader-scatter",
"start-key": "100",
"end-key": "200",
"timeout": "0s",
})
re.NoError(err)
checkFn(body, false)
}
7 changes: 6 additions & 1 deletion pkg/schedule/schedulers/grant_hot_region.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,12 @@ func (handler *grantHotRegionHandler) updateConfig(w http.ResponseWriter, r *htt
}
storeIDs = append(storeIDs, id)
}
leaderID, err := strconv.ParseUint(input["store-leader-id"].(string), 10, 64)
leaderStr, ok := input["store-leader-id"].(string)
if !ok {
handler.rd.JSON(w, http.StatusBadRequest, errs.ErrSchedulerConfig)
return
}
leaderID, err := strconv.ParseUint(leaderStr, 10, 64)
if err != nil {
handler.rd.JSON(w, http.StatusBadRequest, errs.ErrBytesToUint64)
return
Expand Down
45 changes: 45 additions & 0 deletions pkg/schedule/schedulers/grant_hot_region_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright 2026 TiKV Project Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package schedulers

import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"

"github.com/stretchr/testify/require"
"github.com/unrolled/render"
)

func TestGrantHotRegionUpdateConfigWithInvalidLeaderIDType(t *testing.T) {
re := require.New(t)
handler := &grantHotRegionHandler{
config: &grantHotRegionSchedulerConfig{},
rd: render.New(render.Options{IndentJSON: true}),
}
body, err := json.Marshal(map[string]any{
"store-id": "1,2",
"store-leader-id": 1,
})
re.NoError(err)
req := httptest.NewRequest(http.MethodPost, "/config", bytes.NewReader(body))
resp := httptest.NewRecorder()
re.NotPanics(func() {
handler.updateConfig(resp, req)
})
re.Equal(http.StatusBadRequest, resp.Code)
}
3 changes: 3 additions & 0 deletions pkg/schedule/schedulers/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,9 @@ func schedulersRegister() {
if err != nil {
return errs.ErrURLParse.Wrap(err)
}
if duration <= 0 {
return errs.ErrURLParse.FastGenByArgs("timeout must be greater than 0")
}
alias, err := url.QueryUnescape(args[3])
if err != nil {
return errs.ErrURLParse.Wrap(err)
Expand Down
7 changes: 6 additions & 1 deletion pkg/schedule/schedulers/scheduler_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -429,8 +429,13 @@ func (c *Controller) CheckTransferWitnessLeader(region *core.RegionInfo) {
s, ok := c.schedulers[types.TransferWitnessLeaderScheduler.String()]
c.RUnlock()
if ok {
regionC := RecvRegionInfo(s.Scheduler)
if regionC == nil {
log.Warn("invalid scheduler type for transfer witness leader", zap.String("scheduler", s.GetName()))
return
}
select {
case RecvRegionInfo(s.Scheduler) <- region:
case regionC <- region:
default:
log.Warn("drop transfer witness leader due to recv region channel full", zap.Uint64("region-id", region.GetID()))
}
Expand Down
5 changes: 4 additions & 1 deletion pkg/schedule/schedulers/transfer_witness_leader.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,5 +114,8 @@ func scheduleTransferWitnessLeader(name string, cluster sche.SchedulerCluster, r

// RecvRegionInfo receives a checked region from coordinator
func RecvRegionInfo(s Scheduler) chan<- *core.RegionInfo {
return s.(*transferWitnessLeaderScheduler).regions
if scheduler, ok := s.(*transferWitnessLeaderScheduler); ok {
return scheduler.regions
}
return nil
}
17 changes: 11 additions & 6 deletions pkg/utils/apiutil/apiutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,13 +335,18 @@ func CollectEscapeStringOption(option string, input map[string]any, collectors .

// CollectStringOption is used to collect string using from input map for given option
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)
}
return nil
v, exist := input[option]
if !exist {
return errs.ErrOptionNotExist.FastGenByArgs(option)
}
return errs.ErrOptionNotExist.FastGenByArgs(option)
str, ok := v.(string)
if !ok {
return errs.ErrOptionTypeInvalid.FastGenByArgs(option)
}
for _, c := range collectors {
c(str)
}
return nil
}

// ParseKey is used to parse interface into []byte and string
Expand Down
28 changes: 20 additions & 8 deletions server/api/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,15 +125,19 @@ func (h *schedulerHandler) CreateScheduler(w http.ResponseWriter, r *http.Reques
handler.ServeHTTP(w, r)
return
}
h.r.JSON(w, http.StatusNotAcceptable, err.Error())
if err != nil {
h.r.JSON(w, http.StatusNotAcceptable, err.Error())
return
}
h.r.JSON(w, http.StatusNotAcceptable, "scheduler config handler is unavailable")
return
}
if err := apiutil.CollectStringOption("rule", input, collector); err != nil {
h.r.JSON(w, http.StatusInternalServerError, err.Error())
h.r.JSON(w, http.StatusBadRequest, err.Error())
return
}
if err := apiutil.CollectStringOption("engine", input, collector); err != nil {
h.r.JSON(w, http.StatusInternalServerError, err.Error())
h.r.JSON(w, http.StatusBadRequest, err.Error())
return
}

Expand All @@ -142,13 +146,13 @@ func (h *schedulerHandler) CreateScheduler(w http.ResponseWriter, r *http.Reques
if errors.ErrorEqual(err, errs.ErrOptionNotExist) {
collector(defaultTimeout)
} else {
h.r.JSON(w, http.StatusInternalServerError, err.Error())
h.r.JSON(w, http.StatusBadRequest, err.Error())
return
}
}

if err := apiutil.CollectStringOption("alias", input, collector); err != nil {
h.r.JSON(w, http.StatusInternalServerError, err.Error())
h.r.JSON(w, http.StatusBadRequest, err.Error())
return
}

Expand Down Expand Up @@ -245,7 +249,7 @@ func (h *schedulerHandler) CreateScheduler(w http.ResponseWriter, r *http.Reques
}

if err := h.AddScheduler(tp, args...); err != nil {
h.r.JSON(w, http.StatusInternalServerError, err.Error())
h.r.JSON(w, http.StatusBadRequest, err.Error())
return
}

Expand Down Expand Up @@ -298,7 +302,11 @@ func (h *schedulerHandler) redirectSchedulerDelete(w http.ResponseWriter, name,
}
resp, err := apiutil.DoDelete(h.svr.GetHTTPClient(), deleteURL)
if err != nil {
h.r.JSON(w, resp.StatusCode, err.Error())
status := http.StatusInternalServerError
if resp != nil {
status = resp.StatusCode
}
h.r.JSON(w, status, err.Error())
return
}
defer resp.Body.Close()
Expand Down Expand Up @@ -373,5 +381,9 @@ func (h *schedulerConfigHandler) handleSchedulerConfig(w http.ResponseWriter, r
sh.ServeHTTP(w, r)
return
}
h.rd.JSON(w, http.StatusNotAcceptable, err.Error())
if err != nil {
h.rd.JSON(w, http.StatusNotAcceptable, err.Error())
return
}
h.rd.JSON(w, http.StatusNotAcceptable, "scheduler config handler is unavailable")
}
3 changes: 3 additions & 0 deletions tools/pd-ctl/tests/scheduler/scheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,9 @@ func (suite *schedulerTestSuite) checkSchedulerConfig(cluster *pdTests.TestClust
re.Equal(core.HexRegionKeyStr([]byte("a")), ranges["start-key"])
re.Equal(core.HexRegionKeyStr([]byte("b")), ranges["end-key"])

echo = tests.MustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "add", "balance-range-scheduler", "--format=raw", "tiflash", "learner-scatter", "learner", "a", "b", "timeout", "0s"}, nil)
re.NotContains(echo, "Success!")

echo = tests.MustExec(re, cmd, []string{"-u", pdAddr, "scheduler", "add", "balance-range-scheduler", "--format=raw", "tiflash", "learner-scatter", "learner", "a", "b"}, nil)
re.Contains(echo, "Success!")
testutil.Eventually(re, func() bool {
Expand Down
Loading