Skip to content

Commit

Permalink
configuration for logger (pingcap#6)
Browse files Browse the repository at this point in the history
* config section for logger & rename config file

* adjust to new configuration

* correct using config item

* adjust comment
  • Loading branch information
silentsai authored Mar 13, 2018
1 parent 3f52af6 commit 2d8d691
Show file tree
Hide file tree
Showing 9 changed files with 239 additions and 80 deletions.
25 changes: 4 additions & 21 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,23 @@ import (
_ "net/http/pprof"
"os"
"os/signal"
"path"
"syscall"

"github.com/ngaut/log"
log "github.com/sirupsen/logrus"

"github.com/pingcap/tidb-lightning/ingest"
"github.com/pingcap/tidb-lightning/ingest/common"
"github.com/pingcap/tidb-lightning/ingest/config"
applog "github.com/pingcap/tidb-lightning/ingest/log"
)

var (
cfgFile = flag.String("c", "tidb-lighting.toml", "tidb-lighting configuration file")
cfgFile = flag.String("c", "tidb-lightning.toml", "tidb-lightning configuration file")
)

func initEnv(cfg *config.Config) error {
common.EnsureDir(cfg.Dir)
// initLogger(cfg.Dir)
applog.InitLogger(&cfg.Log)

if len(cfg.ProfilePort) > 0 {
go func() { // TODO : config to enable it in debug mode
Expand All @@ -33,23 +33,6 @@ func initEnv(cfg *config.Config) error {
return nil
}

func initLogger(dir string) error {
logDir := path.Join(dir, "log")
logFile := path.Join(logDir, "ingest.log")
if err := os.MkdirAll(logDir, os.ModePerm); err != nil {
return err
}

log.SetRotateByDay()
log.SetHighlighting(false)
log.SetLevel(log.LOG_LEVEL_WARN)
if err := log.SetOutputByName(logFile); err != nil {
return err
}

return nil
}

func onExitSignal() {
sc := make(chan os.Signal, 1)
signal.Notify(sc,
Expand Down
39 changes: 28 additions & 11 deletions ingest/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"io/ioutil"

"github.com/BurntSushi/toml"
"github.com/pingcap/tidb-lightning/ingest/log"
)

type DataSource struct {
Expand All @@ -23,24 +24,32 @@ type Config struct {
Dir string `toml:"dir"`
SourceDir string `toml:"data_source_dir"`

PdAddr string `toml:"pd_backend"`
KvDeliverAddr string `toml:"kv_import_backend"`
TiDB DBStore `toml:"tidb"`
PdAddr string `toml:"pd_backend"`
TiDB DBStore `toml:"tidb"`

Log log.LogConfig `toml:"log"`

ProfilePort string `toml:"pprof_port"`
ProgressStore DBStore `toml:"progress_store"`

Mydump MydumperRuntime `toml:"mydumper"`
KvDev KVDeliverRuntime `toml:"kv-ingest"`
Mydumper MydumperRuntime `toml:"mydumper"`
KvIngest KVIngest `toml:"kv-ingest"`

Verify Verification `toml:"verify"`
}

type MydumperRuntime struct {
ReadBlockSize int64 `toml:"read-block-size"`
MinRegionSize int64 `toml:"region-min-size"`
}

type KVDeliverRuntime struct {
MaxFlushSize int64 `toml:"max-flush-size"`
type KVIngest struct {
Backend string `toml:"backend"`
BatchSize int64 `toml:"batch_size"`
}

type Verification struct {
RunCheckTable bool `toml:"run_check_table"`
}

func LoadConfig(file string) (*Config, error) {
Expand All @@ -54,10 +63,18 @@ func LoadConfig(file string) (*Config, error) {
return nil, err
}

// TODO ... adjust
// cfg.Mydump.MinRegionSize = MinRegionSize
// cfg.Mydump.ReadBlockSize = ReadBlockSize
cfg.KvDev.MaxFlushSize = MaxFlushSize
// handle mydumper
if cfg.Mydumper.MinRegionSize <= 0 {
cfg.Mydumper.MinRegionSize = MinRegionSize
}
if cfg.Mydumper.ReadBlockSize <= 0 {
cfg.Mydumper.ReadBlockSize = ReadBlockSize
}

// hendle kv ingest
if cfg.KvIngest.BatchSize <= 0 {
cfg.KvIngest.BatchSize = KVMaxBatchSize
}

return cfg, nil
}
8 changes: 4 additions & 4 deletions ingest/config/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ const (
_G = _M << 10

// mydumper
// ReadBlockSize int64 = 32 * _K
// MinRegionSize int64 = 256 * _M
ReadBlockSize int64 = 32 * _K
MinRegionSize int64 = 256 * _M

// // kv-deliver
MaxFlushSize int64 = 200 * _G
// kv ingest
KVMaxBatchSize int64 = 200 * _G
)
151 changes: 151 additions & 0 deletions ingest/log/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
package log

import (
"bytes"
"fmt"
"path"
"runtime"
"strings"

"github.com/juju/errors"
log "github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"

"github.com/pingcap/tidb-lightning/ingest/common"
)

const (
defaultLogTimeFormat = "2006/01/02 15:04:05.000"
defaultLogLevel = log.InfoLevel
defaultLogMaxDays = 7
defaultLogMaxSize = 512 // MB
)

// LogConfig serializes log related config in toml/json.
type LogConfig struct {
// Log level.
Level string `toml:"level" json:"level"`
// Log filename, leave empty to disable file log.
File string `toml:"file" json:"file"`
// Max size for a single file, in MB.
FileMaxSize int `toml:"max-size" json:"max-size"`
// Max log keep days, default is never deleting.
FileMaxDays int `toml:"max-days" json:"max-days"`
// Maximum number of old log files to retain.
FileMaxBackups int `toml:"max-backups" json:"max-backups"`
}

func (cfg *LogConfig) Adjust() {
if len(cfg.File) > 0 {
if cfg.FileMaxSize == 0 {
cfg.FileMaxSize = defaultLogMaxSize
}
if cfg.FileMaxDays == 0 {
cfg.FileMaxDays = defaultLogMaxDays
}
}
}

func stringToLogLevel(level string) log.Level {
switch strings.ToLower(level) {
case "fatal":
return log.FatalLevel
case "error":
return log.ErrorLevel
case "warn", "warning":
return log.WarnLevel
case "debug":
return log.DebugLevel
case "info":
return log.InfoLevel
}
return defaultLogLevel
}

type SimpleTextFormater struct{}

func (f *SimpleTextFormater) Format(entry *log.Entry) ([]byte, error) {
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}

// timestamp
fmt.Fprintf(b, "%s ", entry.Time.Format(defaultLogTimeFormat))
// code stack trace
if file, ok := entry.Data["file"]; ok {
fmt.Fprintf(b, "%s:%v:", file, entry.Data["line"])
}
// level + message
fmt.Fprintf(b, " [%s] %s", entry.Level.String(), entry.Message)

// others
for k, v := range entry.Data {
if k != "file" && k != "line" {
fmt.Fprintf(b, " %v=%v", k, v)
}
}

b.WriteByte('\n')

return b.Bytes(), nil
}

// modifyHook injects file name and line pos into log entry.
type contextHook struct{}

// Levels implements logrus.Hook interface.
func (hook *contextHook) Levels() []log.Level {
return log.AllLevels
}

// Fire implements logrus.Hook interface
// https://github.com/sirupsen/logrus/issues/63
func (hook *contextHook) Fire(entry *log.Entry) error {
pc := make([]uintptr, 3)
cnt := runtime.Callers(6, pc)

for i := 0; i < cnt; i++ {
fu := runtime.FuncForPC(pc[i] - 1)
name := fu.Name()
if !isSkippedPackageName(name) {
file, line := fu.FileLine(pc[i] - 1)
entry.Data["file"] = path.Base(file)
entry.Data["line"] = line
break
}
}
return nil
}

func isSkippedPackageName(name string) bool {
return strings.Contains(name, "github.com/sirupsen/logrus") ||
strings.Contains(name, "github.com/coreos/pkg/capnslog")
}

func InitLogger(cfg *LogConfig) error {
log.SetLevel(stringToLogLevel(cfg.Level))
log.AddHook(&contextHook{})
log.SetFormatter(&SimpleTextFormater{})

if len(cfg.File) > 0 {
if common.IsDirExists(cfg.File) {
return errors.Errorf("can't use directory as log file name : %s", cfg.File)
}

// use lumberjack to logrotate
output := &lumberjack.Logger{
Filename: cfg.File,
MaxAge: cfg.FileMaxDays,
MaxSize: cfg.FileMaxSize,
MaxBackups: cfg.FileMaxBackups,
LocalTime: true,
}

log.SetOutput(output)
}

return nil
}
12 changes: 6 additions & 6 deletions ingest/mainloop.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"runtime"
"sync"

"github.com/ngaut/log"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"

"github.com/pingcap/tidb-lightning/ingest/config"
Expand Down Expand Up @@ -34,7 +34,10 @@ func (m *mainloop) Run() {
runtime.GOMAXPROCS(runtime.NumCPU())

m.wg.Add(1)
go m.run()
go func() {
defer m.wg.Done()
m.run()
}()
m.wg.Wait()
}

Expand All @@ -47,10 +50,7 @@ func (m *mainloop) run() {

dbMeta := mdl.GetDatabase()
procedure := restore.NewRestoreControlloer(dbMeta, m.cfg)
defer func() {
procedure.Close()
m.wg.Done()
}()
defer procedure.Close()

procedure.Run(m.ctx)
return
Expand Down
12 changes: 6 additions & 6 deletions ingest/restore/restore.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"time"

"github.com/juju/errors"
"github.com/ngaut/log"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"

"github.com/pingcap/tidb-lightning/ingest/common"
Expand Down Expand Up @@ -109,11 +109,11 @@ func (rc *RestoreControlloer) restoreSchema(ctx context.Context) error {

err = tidbMgr.InitSchema(database, tablesSchema)
if err != nil {
log.Errorf("restore schema failed : %v", err)
return err
return errors.Errorf("db schema failed to init : %v", err)
}

// TODO : check tables' schema
rc.dbInfo = tidbMgr.SyncSchema(database)

return nil
}

Expand Down Expand Up @@ -206,7 +206,7 @@ func makeKVDeliver(
tableInfo *TidbTableInfo) (kv.KVDeliver, error) {

uuid := adjustUUID(fmt.Sprintf("%s_%s", dbInfo.Name, tableInfo.Name), 16)
return kv.NewKVDeliverClient(ctx, uuid, cfg.KvDeliverAddr)
return kv.NewKVDeliverClient(ctx, uuid, cfg.KvIngest.Backend)
}

////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -430,7 +430,7 @@ func NewTableRestore(
tableInfo: tableInfo,
tableMeta: tableMeta,
encoders: newKvEncoderPool(dbInfo, tableInfo, tableMeta).init(concurrency),
deliversMgr: kv.NewKVDeliverKeeper(cfg.KvDeliverAddr),
deliversMgr: kv.NewKVDeliverKeeper(cfg.KvIngest.Backend),
handledRegions: make(map[int]int64),
}

Expand Down
2 changes: 1 addition & 1 deletion ingest/restore/tidb.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/store/tikv"

"github.com/ngaut/log"
log "github.com/sirupsen/logrus"
goctx "golang.org/x/net/context"
)

Expand Down
Loading

0 comments on commit 2d8d691

Please sign in to comment.