Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

scheduler: add debug log #907

Merged
merged 12 commits into from
Jan 10, 2018
62 changes: 62 additions & 0 deletions pdctl/command/log_command.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright 2018 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package command

import (
"bytes"
"encoding/json"
"fmt"
"net/http"

"github.com/spf13/cobra"
)

var (
logPrefix = "pd/api/v1/log"
)

// NewLogCommand New a log subcommand of the rootCmd
func NewLogCommand() *cobra.Command {
conf := &cobra.Command{
Use: "log [fatal|error|warn|info|debug]",
Short: "set log level",
Run: logCommandFunc,
}
return conf
}

func logCommandFunc(cmd *cobra.Command, args []string) {
var err error
if len(args) != 1 {
fmt.Println(cmd.UsageString())
return
}

data, err := json.Marshal(args[0])
if err != nil {
fmt.Printf("Failed to set log level: %s\n", err)
return
}
req, err := getRequest(cmd, logPrefix, http.MethodPost, "application/json", bytes.NewBuffer(data))
if err != nil {
fmt.Printf("Failed to set log level: %s\n", err)
return
}
_, err = dail(req)
if err != nil {
fmt.Printf("Failed to set log level: %s\n", err)
return
}
fmt.Println("Success!")
}
1 change: 1 addition & 0 deletions pdctl/ctl.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ func init() {
command.NewClusterCommand(),
command.NewTableNamespaceCommand(),
command.NewHealthCommand(),
command.NewLogCommand(),
)
cobra.EnablePrefixMatching = true
}
Expand Down
5 changes: 3 additions & 2 deletions pkg/logutil/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,8 @@ func (hook *contextHook) Levels() []log.Level {
return log.AllLevels
}

func stringToLogLevel(level string) log.Level {
// StringToLogLevel converts string to relative log.Level.
func StringToLogLevel(level string) log.Level {
switch strings.ToLower(level) {
case "fatal":
return log.FatalLevel
Expand Down Expand Up @@ -221,7 +222,7 @@ var once sync.Once
func InitLogger(cfg *LogConfig) error {
var err error
once.Do(func() {
log.SetLevel(stringToLogLevel(cfg.Level))
log.SetLevel(StringToLogLevel(cfg.Level))
log.AddHook(&contextHook{})

if cfg.Format == "" {
Expand Down
14 changes: 7 additions & 7 deletions pkg/logutil/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@ func (s *testLogSuite) SetUpSuite(c *C) {
}

func (s *testLogSuite) TestStringToLogLevel(c *C) {
c.Assert(stringToLogLevel("fatal"), Equals, log.FatalLevel)
c.Assert(stringToLogLevel("ERROR"), Equals, log.ErrorLevel)
c.Assert(stringToLogLevel("warn"), Equals, log.WarnLevel)
c.Assert(stringToLogLevel("warning"), Equals, log.WarnLevel)
c.Assert(stringToLogLevel("debug"), Equals, log.DebugLevel)
c.Assert(stringToLogLevel("info"), Equals, log.InfoLevel)
c.Assert(stringToLogLevel("whatever"), Equals, log.InfoLevel)
c.Assert(StringToLogLevel("fatal"), Equals, log.FatalLevel)
c.Assert(StringToLogLevel("ERROR"), Equals, log.ErrorLevel)
c.Assert(StringToLogLevel("warn"), Equals, log.WarnLevel)
c.Assert(StringToLogLevel("warning"), Equals, log.WarnLevel)
c.Assert(StringToLogLevel("debug"), Equals, log.DebugLevel)
c.Assert(StringToLogLevel("info"), Equals, log.InfoLevel)
c.Assert(StringToLogLevel("whatever"), Equals, log.InfoLevel)
}

// TestLogging assure log format and log redirection works.
Expand Down
57 changes: 57 additions & 0 deletions server/api/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Copyright 2018 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package api

import (
"encoding/json"
"io/ioutil"
"net/http"

"github.com/pingcap/pd/pkg/logutil"
"github.com/pingcap/pd/server"
log "github.com/sirupsen/logrus"
"github.com/unrolled/render"
)

type logHandler struct {
svr *server.Server
rd *render.Render
}

func newlogHandler(svr *server.Server, rd *render.Render) *logHandler {
return &logHandler{
svr: svr,
rd: rd,
}
}

func (h *logHandler) Handle(w http.ResponseWriter, r *http.Request) {
var level string
data, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}
err = json.Unmarshal(data, &level)
if err != nil {
h.rd.JSON(w, http.StatusInternalServerError, err.Error())
return
}

h.svr.SetLogLevel(level)
log.SetLevel(logutil.StringToLogLevel(level))

h.rd.JSON(w, http.StatusOK, nil)
}
3 changes: 3 additions & 0 deletions server/api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,9 @@ func createRouter(prefix string, svr *server.Server) *mux.Router {
trendHandler := newTrendHandler(svr, rd)
router.HandleFunc("/api/v1/trend", trendHandler.Handle).Methods("GET")

logHanler := newlogHandler(svr, rd)
router.HandleFunc("/api/v1/log", logHanler.Handle).Methods("POST")

router.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {}).Methods("GET")
return router
}
3 changes: 3 additions & 0 deletions server/schedule/filters.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/pingcap/pd/server/cache"
"github.com/pingcap/pd/server/core"
"github.com/pingcap/pd/server/namespace"
log "github.com/sirupsen/logrus"
)

// Filter is an interface to filter source and target store.
Expand All @@ -31,6 +32,7 @@ type Filter interface {
func FilterSource(opt Options, store *core.StoreInfo, filters []Filter) bool {
for _, filter := range filters {
if filter.FilterSource(opt, store) {
log.Debugf("[filter %T] filters store %v from source", filter, store)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

%T will output all the fields of the filter, is it ok here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, it outputs like "*schedule.excludedFilter"

return true
}
}
Expand All @@ -41,6 +43,7 @@ func FilterSource(opt Options, store *core.StoreInfo, filters []Filter) bool {
func FilterTarget(opt Options, store *core.StoreInfo, filters []Filter) bool {
for _, filter := range filters {
if filter.FilterTarget(opt, store) {
log.Debugf("[filter %T] filters store %v from target", filter, store)
return true
}
}
Expand Down
2 changes: 2 additions & 0 deletions server/schedulers/balance_leader.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package schedulers
import (
"github.com/pingcap/pd/server/core"
"github.com/pingcap/pd/server/schedule"
log "github.com/sirupsen/logrus"
)

func init() {
Expand Down Expand Up @@ -74,6 +75,7 @@ func (l *balanceLeaderScheduler) Schedule(cluster schedule.Cluster, opInfluence

source := cluster.GetStore(region.Leader.GetStoreId())
target := cluster.GetStore(newLeader.GetStoreId())
log.Debugf("[region %d] source store id is %v, target store id is %v", region.GetId(), source.GetId(), target.GetId())
avgScore := cluster.GetStoresAverageScore(core.LeaderKind)
if !shouldBalance(source, target, avgScore, core.LeaderKind, region, opInfluence, cluster.GetTolerantSizeRatio()) {
schedulerCounter.WithLabelValues(l.GetName(), "skip").Inc()
Expand Down
2 changes: 2 additions & 0 deletions server/schedulers/balance_region.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/pingcap/pd/server/cache"
"github.com/pingcap/pd/server/core"
"github.com/pingcap/pd/server/schedule"
log "github.com/sirupsen/logrus"
)

func init() {
Expand Down Expand Up @@ -117,6 +118,7 @@ func (s *balanceRegionScheduler) transferPeer(cluster schedule.Cluster, region *

target := cluster.GetStore(newPeer.GetStoreId())
avgScore := cluster.GetStoresAverageScore(core.RegionKind)
log.Debugf("[region %d] source store id is %v, target store id is %v", region.GetId(), source.GetId(), target.GetId())
if !shouldBalance(source, target, avgScore, core.RegionKind, region, opInfluence, cluster.GetTolerantSizeRatio()) {
schedulerCounter.WithLabelValues(s.GetName(), "skip").Inc()
return nil
Expand Down
10 changes: 9 additions & 1 deletion server/schedulers/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ func scheduleTransferLeader(cluster schedule.Cluster, schedulerName string, s sc

mostLeaderStore := s.SelectSource(cluster, stores, filters...)
leastLeaderStore := s.SelectTarget(cluster, stores, filters...)
log.Debugf("[%s] mostLeaderStore is %v, leastLeaderStore is %v", schedulerName, mostLeaderStore, leastLeaderStore)

var mostLeaderDistance, leastLeaderDistance float64
if mostLeaderStore != nil {
Expand All @@ -47,6 +48,7 @@ func scheduleTransferLeader(cluster schedule.Cluster, schedulerName string, s sc
if leastLeaderStore != nil {
leastLeaderDistance = math.Abs(leastLeaderStore.LeaderScore() - averageLeader)
}
log.Debugf("[%s] mostLeaderDistance is %v, leastLeaderDistance is %v", schedulerName, mostLeaderDistance, leastLeaderDistance)
if mostLeaderDistance == 0 && leastLeaderDistance == 0 {
schedulerCounter.WithLabelValues(schedulerName, "already_balanced").Inc()
return nil, nil
Expand All @@ -63,7 +65,11 @@ func scheduleTransferLeader(cluster schedule.Cluster, schedulerName string, s sc
region, peer = scheduleRemoveLeader(cluster, schedulerName, mostLeaderStore.GetId(), s)
}
}

if region == nil {
log.Debugf("[%v] select no region", schedulerName)
} else {
log.Debugf("[region %v][%v] select %v to be new leader", schedulerName, region.GetId(), peer)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the parameter does not correspond.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, I mistake the order

}
return region, peer
}

Expand Down Expand Up @@ -173,6 +179,7 @@ func shouldBalance(source, target *core.StoreInfo, avgScore float64, kind core.R
sourceScore := source.ResourceScore(kind)
targetScore := target.ResourceScore(kind)
if targetScore >= sourceScore {
log.Debugf("should balance return false cause targetScore %v >= sourceScore %v", targetScore, sourceScore)
return false
}

Expand All @@ -183,6 +190,7 @@ func shouldBalance(source, target *core.StoreInfo, avgScore float64, kind core.R
sourceSizeDiff := (sourceScore - avgScore) * source.ResourceWeight(kind)
targetSizeDiff := (avgScore - targetScore) * target.ResourceWeight(kind)

log.Debugf("size diff is %v and region size is %v", math.Min(sourceSizeDiff, targetSizeDiff), float64(region.ApproximateSize)*tolerantRatio)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

region size -> tolerable size?better to indicate region id.

return math.Min(sourceSizeDiff, targetSizeDiff) >= float64(region.ApproximateSize)*tolerantRatio
}

Expand Down
5 changes: 5 additions & 0 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -558,3 +558,8 @@ func (s *Server) GetClusterStatus() (*ClusterStatus, error) {
func (s *Server) getAllocIDPath() string {
return path.Join(s.rootPath, "alloc_id")
}

// SetLogLevel sets log level.
func (s *Server) SetLogLevel(level string) {
s.cfg.Log.Level = level
}