From a741239cc7ed4c3f420f59ce4cac059782b86ada Mon Sep 17 00:00:00 2001 From: Jeffsky Date: Sun, 6 Aug 2023 13:38:21 +0800 Subject: [PATCH] fix: some problems when server starting --- .chglog/CHANGELOG.tpl.md | 38 --- .chglog/config.yml | 47 ---- .dockerignore | 1 + Dockerfile | 21 +- cmd/{admin => }/admin.go | 51 ++-- cmd/{main.go => arana/arana.go} | 22 +- cmd/{cmds/cmds.go => cmd.go} | 23 +- cmd/{tools/tools.go => import.go} | 27 +-- cmd/{start => }/start.go | 52 ++--- conf/bootstrap.docker.yaml | 9 + conf/bootstrap.local-etcd.yaml | 17 +- docker-compose.yaml | 6 +- example/admin_server/main.go | 20 +- example/import_config/main.go | 21 +- example/local_server/main.go | 13 +- go.mod | 2 +- go.sum | 3 +- pkg/boot/boot.go | 2 +- pkg/config/misc.go | 13 +- pkg/config/misc_test.go | 24 +- pkg/config/model.go | 14 +- pkg/executor/redirect.go | 39 +++- pkg/runtime/namespace/command.go | 2 +- pkg/util/log/logging.go | 376 ++++++++++++++++-------------- test/suite.go | 4 +- 25 files changed, 408 insertions(+), 439 deletions(-) delete mode 100755 .chglog/CHANGELOG.tpl.md delete mode 100755 .chglog/config.yml rename cmd/{admin => }/admin.go (82%) rename cmd/{main.go => arana/arana.go} (66%) rename cmd/{cmds/cmds.go => cmd.go} (71%) rename cmd/{tools/tools.go => import.go} (61%) rename cmd/{start => }/start.go (93%) diff --git a/.chglog/CHANGELOG.tpl.md b/.chglog/CHANGELOG.tpl.md deleted file mode 100755 index c7d097ae..00000000 --- a/.chglog/CHANGELOG.tpl.md +++ /dev/null @@ -1,38 +0,0 @@ -{{ range .Versions }} - -## {{ if .Tag.Previous }}[{{ .Tag.Name }}]({{ $.Info.RepositoryURL }}/compare/{{ .Tag.Previous.Name }}...{{ .Tag.Name }}){{ else }}{{ .Tag.Name }}{{ end }} ({{ datetime "2006-01-02" .Tag.Date }}) - -{{ range .CommitGroups -}} -### {{ .Title }} - -{{ range .Commits -}} -* {{ if .Scope }}**{{ .Scope }}:** {{ end }}{{ .Subject }} -{{ end }} -{{ end -}} - -{{- if .RevertCommits -}} -### Reverts - -{{ range .RevertCommits -}} -* {{ .Revert.Header }} -{{ end }} -{{ end -}} - -{{- if .MergeCommits -}} -### Pull Requests - -{{ range .MergeCommits -}} -* {{ .Header }} -{{ end }} -{{ end -}} - -{{- if .NoteGroups -}} -{{ range .NoteGroups -}} -### {{ .Title }} - -{{ range .Notes }} -{{ .Body }} -{{ end }} -{{ end -}} -{{ end -}} -{{ end -}} diff --git a/.chglog/config.yml b/.chglog/config.yml deleted file mode 100755 index 0732c533..00000000 --- a/.chglog/config.yml +++ /dev/null @@ -1,47 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you 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. -# - -style: github -template: CHANGELOG.tpl.md -info: - title: CHANGELOG - repository_url: https://github.com/arana-db/arana -options: - commits: - # filters: - # Type: - # - feat - # - fix - # - perf - # - refactor - commit_groups: - # title_maps: - # feat: Features - # fix: Bug Fixes - # perf: Performance Improvements - # refactor: Code Refactoring - header: - pattern: "^(\\w*)(?:\\(([\\w\\$\\.\\-\\*\\s]*)\\))?\\:\\s(.*)$" - pattern_maps: - - Type - - Scope - - Subject - notes: - keywords: - - BREAKING CHANGE diff --git a/.dockerignore b/.dockerignore index 314473e7..90fab539 100644 --- a/.dockerignore +++ b/.dockerignore @@ -31,4 +31,5 @@ staticcheck.conf .chglog/ justfile Makefile +cliff.toml *.md diff --git a/Dockerfile b/Dockerfile index e588aaef..05d4ca42 100644 --- a/Dockerfile +++ b/Dockerfile @@ -16,7 +16,7 @@ # ### BUILDER LAYER -FROM golang:1.18-alpine AS BE +FROM golang:1.20-alpine AS BE WORKDIR /app @@ -28,7 +28,7 @@ RUN go mod download COPY . . RUN mkdir ./bin && \ - go build -ldflags "-X main.Version=`cat VERSION` -extldflags \"-static\" -s -w" -o ./bin/arana ./cmd + go build -ldflags "-X main.Version=`cat VERSION` -extldflags \"-static\" -s -w" -o ./bin/arana ./cmd/arana ### UI LAYER FROM node:16-alpine as FE @@ -47,19 +47,22 @@ RUN git clone -n https://github.com/arana-db/arana-ui.git /arana-ui && \ ### RUNTIME LAYER FROM alpine:3 -ENV ARANA_LOG_NAME=arana.log \ - ARANA_LOG_LEVEL=0 \ - ARANA_LOG_MAX_SIZE=10 \ - ARANA_LOG_MAX_BACKUPS=5 \ - ARANA_LOG_MAX_AGE=30 \ - ARANA_LOG_COMPRESS=false +ENV ARANA_LOG_PATH=/var/log/arana \ + ARANA_LOG_LEVEL=INFO \ + ARANA_LOG_MAX_SIZE=128MB \ + ARANA_LOG_MAX_BACKUPS=3 \ + ARANA_LOG_MAX_AGE=7 \ + ARANA_LOG_COMPRESS=false \ + ARANA_LOG_CONSOLE=true \ + ARANA_LOG_SQL=false WORKDIR / -RUN mkdir -p /etc/arana /var/www/arana +RUN mkdir -p /etc/arana /var/www/arana /var/log/arana VOLUME /etc/arana VOLUME /var/www/arana +VOLUME /var/log/arana EXPOSE 13306 EXPOSE 8080 diff --git a/cmd/admin/admin.go b/cmd/admin.go similarity index 82% rename from cmd/admin/admin.go rename to cmd/admin.go index 1b341783..b3e18746 100644 --- a/cmd/admin/admin.go +++ b/cmd/admin.go @@ -15,7 +15,7 @@ * limitations under the License. */ -package admin +package cmd import ( "context" @@ -29,7 +29,6 @@ import ( ) import ( - "github.com/arana-db/arana/cmd/cmds" "github.com/arana-db/arana/pkg/admin" _ "github.com/arana-db/arana/pkg/admin/router" "github.com/arana-db/arana/pkg/boot" @@ -53,19 +52,36 @@ func init() { Use: "admin", Short: "admin", Example: "arana admin -c bootstrap.yaml -p 8080", - RunE: run, + RunE: runAdmin, } cmd.PersistentFlags(). StringP(constants.ConfigPathKey, "c", os.Getenv(constants.EnvBootstrapPath), "bootstrap configuration file path") cmd.PersistentFlags(). Uint16P(_keyPort, "p", _defaultPort, "listen port") - cmds.Handle(func(root *cobra.Command) { - root.AddCommand(cmd) - }) + RootCommand.AddCommand(cmd) } -func Run(bootstrapPath string, addr string) error { +func runAdmin(cmd *cobra.Command, args []string) error { + _ = args + bootstrapPath, _ := cmd.PersistentFlags().GetString(constants.ConfigPathKey) + port, _ := cmd.PersistentFlags().GetUint16("port") + if len(bootstrapPath) < 1 { + // search bootstrap yaml + for _, path := range constants.GetConfigSearchPathList() { + bootstrapPath = filepath.Join(path, "bootstrap.yaml") + if _, err := os.Stat(bootstrapPath); err == nil { + break + } + bootstrapPath = filepath.Join(path, "bootstrap.yml") + if _, err := os.Stat(bootstrapPath); err == nil { + break + } + } + } + + addr := fmt.Sprintf(":%d", port) + bootOptions, err := config.LoadBootOptions(bootstrapPath) if err != nil { return err @@ -93,24 +109,3 @@ func Run(bootstrapPath string, addr string) error { adminServer := admin.New(op, serviceDiscovery) return adminServer.Listen(addr) } - -func run(cmd *cobra.Command, args []string) error { - _ = args - btPath, _ := cmd.PersistentFlags().GetString(constants.ConfigPathKey) - port, _ := cmd.PersistentFlags().GetUint16("port") - if len(btPath) < 1 { - // search bootstrap yaml - for _, path := range constants.GetConfigSearchPathList() { - btPath = filepath.Join(path, "bootstrap.yaml") - if _, err := os.Stat(btPath); err == nil { - break - } - btPath = filepath.Join(path, "bootstrap.yml") - if _, err := os.Stat(btPath); err == nil { - break - } - } - } - - return Run(btPath, fmt.Sprintf(":%d", port)) -} diff --git a/cmd/main.go b/cmd/arana/arana.go similarity index 66% rename from cmd/main.go rename to cmd/arana/arana.go index edbc1f21..3cf1f792 100644 --- a/cmd/main.go +++ b/cmd/arana/arana.go @@ -18,27 +18,9 @@ package main import ( - "github.com/spf13/cobra" + "github.com/arana-db/arana/cmd" ) -import ( - _ "github.com/arana-db/arana/cmd/admin" - "github.com/arana-db/arana/cmd/cmds" - _ "github.com/arana-db/arana/cmd/start" - _ "github.com/arana-db/arana/cmd/tools" -) - -var Version = "0.1.0" - func main() { - rootCommand := &cobra.Command{ - Use: "arana", - Short: "arana is a db proxy server", - Version: Version, - } - - // initialize sub commands - cmds.Do(rootCommand) - - _ = rootCommand.Execute() + cmd.Main() } diff --git a/cmd/cmds/cmds.go b/cmd/cmd.go similarity index 71% rename from cmd/cmds/cmds.go rename to cmd/cmd.go index 88e2ff3e..54137b23 100644 --- a/cmd/cmds/cmds.go +++ b/cmd/cmd.go @@ -15,25 +15,22 @@ * limitations under the License. */ -package cmds +package cmd import ( + "github.com/pkg/errors" + "github.com/spf13/cobra" ) -var _handlers []Handler - -// Handler represents the command handler. -type Handler func(cmd *cobra.Command) +var Version = "0.1.0" -// Handle handles the main command. -func Handle(input Handler) { - _handlers = append(_handlers, input) +var RootCommand = &cobra.Command{ + Use: "arana", + Short: "arana is a db proxy server", + Version: Version, } -// Do process the root command with handlers. -func Do(cmd *cobra.Command) { - for _, it := range _handlers { - it(cmd) - } +func Main() error { + return errors.WithStack(RootCommand.Execute()) } diff --git a/cmd/tools/tools.go b/cmd/import.go similarity index 61% rename from cmd/tools/tools.go rename to cmd/import.go index 46f59c84..cfff049a 100644 --- a/cmd/tools/tools.go +++ b/cmd/import.go @@ -15,7 +15,7 @@ * limitations under the License. */ -package tools +package cmd import ( "os" @@ -26,14 +26,13 @@ import ( ) import ( - "github.com/arana-db/arana/cmd/cmds" "github.com/arana-db/arana/pkg/boot" "github.com/arana-db/arana/pkg/constants" ) var ( - sourceConfigPath string - importBootConfPath string + _sourceConfigPath string + _importBootConfPath string ) // init Init startCmd @@ -41,24 +40,18 @@ func init() { cmd := &cobra.Command{ Use: "import", Short: "import arana config", - Example: "./arana import -c ../docker/conf/bootstrap.yaml -s ../docker/conf/config.yaml", - Run: run, + Example: "arana import -c ../docker/conf/bootstrap.yaml -s ../docker/conf/config.yaml", + Run: runTools, } cmd.PersistentFlags(). - StringVarP(&importBootConfPath, constants.ConfigPathKey, "c", os.Getenv(constants.EnvBootstrapPath), "bootstrap configuration file path") + StringVarP(&_importBootConfPath, constants.ConfigPathKey, "c", os.Getenv(constants.EnvBootstrapPath), "bootstrap configuration file path") cmd.PersistentFlags(). - StringVarP(&sourceConfigPath, constants.ImportConfigPathKey, "s", "", "import configuration file path") + StringVarP(&_sourceConfigPath, constants.ImportConfigPathKey, "s", "", "import configuration file path") - cmds.Handle(func(root *cobra.Command) { - root.AddCommand(cmd) - }) + RootCommand.AddCommand(cmd) } -func run(_ *cobra.Command, _ []string) { - Run(importBootConfPath, sourceConfigPath) -} - -func Run(importConfPath, configPath string) { - boot.RunImport(importConfPath, configPath) +func runTools(_ *cobra.Command, _ []string) { + boot.RunImport(_importBootConfPath, _sourceConfigPath) } diff --git a/cmd/start/start.go b/cmd/start.go similarity index 93% rename from cmd/start/start.go rename to cmd/start.go index 475ada47..7fa5da8a 100644 --- a/cmd/start/start.go +++ b/cmd/start.go @@ -15,7 +15,7 @@ * limitations under the License. */ -package start +package cmd import ( "context" @@ -31,7 +31,6 @@ import ( ) import ( - "github.com/arana-db/arana/cmd/cmds" "github.com/arana-db/arana/pkg/boot" "github.com/arana-db/arana/pkg/constants" "github.com/arana-db/arana/pkg/executor" @@ -59,17 +58,34 @@ func init() { Use: "start", Short: "start arana", Example: "arana start -c bootstrap.yaml", - Run: run, + Run: runStart, } cmd.PersistentFlags(). StringP(_keyBootstrap, "c", os.Getenv(constants.EnvBootstrapPath), "bootstrap configuration file path") - cmds.Handle(func(root *cobra.Command) { - root.AddCommand(cmd) - }) + RootCommand.AddCommand(cmd) } -func Run(bootstrapConfigPath string) { +func runStart(cmd *cobra.Command, _ []string) { + bootstrapConfigPath, _ := cmd.PersistentFlags().GetString(_keyBootstrap) + Start(bootstrapConfigPath) +} + +func Start(bootstrapConfigPath string) { + if len(bootstrapConfigPath) < 1 { + // search bootstrap yaml + for _, path := range constants.GetConfigSearchPathList() { + bootstrapConfigPath = filepath.Join(path, "bootstrap.yaml") + if _, err := os.Stat(bootstrapConfigPath); err == nil { + break + } + bootstrapConfigPath = filepath.Join(path, "bootstrap.yml") + if _, err := os.Stat(bootstrapConfigPath); err == nil { + break + } + } + } + // print slogan fmt.Printf("\033[92m%s\033[0m\n", slogan) // 92m: light green @@ -130,25 +146,3 @@ func Run(bootstrapConfigPath string) { <-ctx.Done() } - -func run(cmd *cobra.Command, args []string) { - _ = args - - bootstrapConfigPath, _ := cmd.PersistentFlags().GetString(_keyBootstrap) - - if len(bootstrapConfigPath) < 1 { - // search bootstrap yaml - for _, path := range constants.GetConfigSearchPathList() { - bootstrapConfigPath = filepath.Join(path, "bootstrap.yaml") - if _, err := os.Stat(bootstrapConfigPath); err == nil { - break - } - bootstrapConfigPath = filepath.Join(path, "bootstrap.yml") - if _, err := os.Stat(bootstrapConfigPath); err == nil { - break - } - } - } - - Run(bootstrapConfigPath) -} diff --git a/conf/bootstrap.docker.yaml b/conf/bootstrap.docker.yaml index a556e08d..a19b28e2 100644 --- a/conf/bootstrap.docker.yaml +++ b/conf/bootstrap.docker.yaml @@ -34,3 +34,12 @@ trace: supervisor: username: root password: root + +logging: + level: INFO + path: /var/log/arana + max_size: 128m + max_backups: 3 + max_age: 7 + compress: true + console: true diff --git a/conf/bootstrap.local-etcd.yaml b/conf/bootstrap.local-etcd.yaml index 86c20ef3..bc45a261 100644 --- a/conf/bootstrap.local-etcd.yaml +++ b/conf/bootstrap.local-etcd.yaml @@ -31,12 +31,11 @@ supervisor: username: root password: root -logging_config: - log_name: arana_log - log_path: ./ - log_level: 7 - log_max_size: 10 - log_max_backups: 5 - log_max_age: 30 - log_compress: false - default_log_name: "arana.log" +logging: + level: INFO + path: ~/arana/logs + max_size: 128m + max_backups: 5 + max_age: 30 + compress: false + console: true diff --git a/docker-compose.yaml b/docker-compose.yaml index d43917df..6dc6f0b1 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -50,12 +50,16 @@ services: - "3306:3306" environment: - MYSQL_ROOT_PASSWORD=123456 + - LANG=C.UTF-8 volumes: - ./scripts/init.sql:/docker-entrypoint-initdb.d/0.sql:ro - ./scripts/sequence.sql:/docker-entrypoint-initdb.d/1.sql:ro - ./scripts/sharding.sql:/docker-entrypoint-initdb.d/2.sql:ro - mysql_data:/var/lib/mysql - command: [ "mysqld", "--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci" ] + command: | + --default-authentication-plugin=mysql_native_password + --character-set-server=utf8mb4 + --collation-server=utf8mb4_unicode_ci healthcheck: test: [ "CMD", "mysqladmin", "ping", "-h127.0.0.1", "-uroot", "-p123456" ] interval: 2s diff --git a/example/admin_server/main.go b/example/admin_server/main.go index 9778e0c6..473f8bb3 100644 --- a/example/admin_server/main.go +++ b/example/admin_server/main.go @@ -18,11 +18,25 @@ package main import ( - "github.com/arana-db/arana/cmd/admin" + "os" +) + +import ( + "github.com/arana-db/arana/cmd" "github.com/arana-db/arana/testdata" ) +func init() { + os.Args = append( + os.Args, + "admin", + "-c", + testdata.Path("../conf/bootstrap.local-etcd.yaml"), + "-p", + "8080", + ) +} + func main() { - bootstrap := testdata.Path("../conf/bootstrap.local-etcd.yaml") - _ = admin.Run(bootstrap, ":8080") + _ = cmd.Main() } diff --git a/example/import_config/main.go b/example/import_config/main.go index 6e2d882d..be1dfe15 100644 --- a/example/import_config/main.go +++ b/example/import_config/main.go @@ -18,12 +18,25 @@ package main import ( - "github.com/arana-db/arana/cmd/tools" + "os" +) + +import ( + "github.com/arana-db/arana/cmd" "github.com/arana-db/arana/testdata" ) +func init() { + os.Args = append( + os.Args, + "import", + "-c", + testdata.Path("../conf/bootstrap.yaml"), + "-s", + testdata.Path("../conf/config.yaml"), + ) +} + func main() { - bootstrap := testdata.Path("../conf/bootstrap.yaml") - config := testdata.Path("../conf/config.yaml") - tools.Run(bootstrap, config) + _ = cmd.Main() } diff --git a/example/local_server/main.go b/example/local_server/main.go index 1ebbd2c8..512ec969 100644 --- a/example/local_server/main.go +++ b/example/local_server/main.go @@ -18,11 +18,18 @@ package main import ( - "github.com/arana-db/arana/cmd/start" + "os" +) + +import ( + "github.com/arana-db/arana/cmd" "github.com/arana-db/arana/testdata" ) +func init() { + os.Args = append(os.Args, "start", "-c", testdata.Path("../conf/bootstrap.local-etcd.yaml")) +} + func main() { - bootstrap := testdata.Path("../conf/bootstrap.yaml") - start.Run(bootstrap) + _ = cmd.Main() } diff --git a/go.mod b/go.mod index 489db2bf..c023d0f8 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,7 @@ require ( github.com/bwmarrin/snowflake v0.3.0 github.com/cespare/xxhash/v2 v2.2.0 github.com/creasty/defaults v1.6.0 - github.com/docker/go-units v0.4.0 + github.com/docker/go-units v0.5.0 github.com/dop251/goja v0.0.0-20230427124612-428fc442ff5f github.com/dubbogo/gost v1.12.3 github.com/gin-gonic/gin v1.8.1 diff --git a/go.sum b/go.sum index 8d3ee80b..56c965e8 100644 --- a/go.sum +++ b/go.sum @@ -335,8 +335,9 @@ github.com/docker/go-events v0.0.0-20170721190031-9461782956ad/go.mod h1:Uw6Uezg github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= github.com/docker/go-metrics v0.0.0-20180209012529-399ea8c73916/go.mod h1:/u0gXw0Gay3ceNrsHubL3BtdOL2fHf93USgMTe0W5dI= github.com/docker/go-metrics v0.0.1/go.mod h1:cG1hvH2utMXtqgqqYE9plW6lDxS3/5ayHzueweSI3Vw= -github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw= github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/docker/libtrust v0.0.0-20150114040149-fa567046d9b1/go.mod h1:cyGadeNEkKy96OOhEzfZl+yxihPEzKnqJwvfuSUqbZE= github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= diff --git a/pkg/boot/boot.go b/pkg/boot/boot.go index 2782e8e5..52899b06 100644 --- a/pkg/boot/boot.go +++ b/pkg/boot/boot.go @@ -218,7 +218,7 @@ func buildNamespace(ctx context.Context, tenant string, provider Discovery, clus } initCmds := []namespace.Command{ - namespace.UpdateSlowLogger(provider.GetOptions().SlowLogPath, provider.GetOptions().LoggingConfig), + namespace.UpdateSlowLogger(provider.GetOptions().SlowLogPath, provider.GetOptions().Logging), namespace.UpdateParameters(cluster.Parameters), namespace.UpdateSlowThreshold(), } diff --git a/pkg/config/misc.go b/pkg/config/misc.go index 2b754db7..d5fd0629 100644 --- a/pkg/config/misc.go +++ b/pkg/config/misc.go @@ -23,6 +23,8 @@ import ( ) import ( + "github.com/go-playground/validator/v10" + "github.com/pkg/errors" "gopkg.in/yaml.v3" @@ -47,12 +49,17 @@ func LoadBootOptions(path string) (*BootOptions, error) { } var cfg BootOptions + cfg.Logging = log.DefaultConfig() + if err = yaml.Unmarshal(content, &cfg); err != nil { - err = errors.Wrap(err, "failed to unmarshal config") - return nil, err + return nil, errors.Wrap(err, "failed to unmarshal config") + } + + if err = validator.New().Struct(&cfg); err != nil { + return nil, errors.Wrap(err, "failed to validate boot config") } - log.Init(cfg.LoggingConfig) + log.Init(cfg.Logging) return &cfg, nil } diff --git a/pkg/config/misc_test.go b/pkg/config/misc_test.go index 6b51a62b..b106abc4 100644 --- a/pkg/config/misc_test.go +++ b/pkg/config/misc_test.go @@ -82,16 +82,16 @@ logging_config: assert.Equal(t, "http://localhost:14268/api/traces", cfg.Trace.Address) assert.Equal(t, "admin", cfg.Supervisor.Username) assert.Equal(t, "password", cfg.Supervisor.Password) - assert.Equal(t, "test", cfg.LoggingConfig.LogName) - assert.Equal(t, "/log/path", cfg.LoggingConfig.LogPath) - assert.Equal(t, 1, cfg.LoggingConfig.LogLevel) - assert.Equal(t, 500, cfg.LoggingConfig.LogMaxSize) - assert.Equal(t, 5, cfg.LoggingConfig.LogMaxBackups) - assert.Equal(t, 10, cfg.LoggingConfig.LogMaxAge) - assert.False(t, cfg.LoggingConfig.LogCompress) - assert.Equal(t, "default", cfg.LoggingConfig.DefaultLogName) - assert.Equal(t, "tx", cfg.LoggingConfig.TxLogName) - assert.True(t, cfg.LoggingConfig.SqlLogEnabled) - assert.Equal(t, "sql", cfg.LoggingConfig.SqlLogName) - assert.Equal(t, "physical_sql", cfg.LoggingConfig.PhysicalSqlLogName) + assert.Equal(t, "test", cfg.Logging.LogName) + assert.Equal(t, "/log/path", cfg.Logging.Path) + assert.Equal(t, 1, cfg.Logging.Level) + assert.Equal(t, 500, cfg.Logging.MaxSize) + assert.Equal(t, 5, cfg.Logging.MaxBackups) + assert.Equal(t, 10, cfg.Logging.MaxAge) + assert.False(t, cfg.Logging.Compress) + assert.Equal(t, "default", cfg.Logging.DefaultLogName) + assert.Equal(t, "tx", cfg.Logging.TxLogName) + assert.True(t, cfg.Logging.SqlLogEnabled) + assert.Equal(t, "sql", cfg.Logging.SqlLogName) + assert.Equal(t, "physical_sql", cfg.Logging.PhysicalSqlLogName) } diff --git a/pkg/config/model.go b/pkg/config/model.go index 4922d1ab..d52c81f5 100644 --- a/pkg/config/model.go +++ b/pkg/config/model.go @@ -81,13 +81,13 @@ type ( } BootOptions struct { - Spec `yaml:",inline"` - Config *Options `yaml:"config" json:"config"` - Listeners []*Listener `validate:"required,dive" yaml:"listeners" json:"listeners"` - Registry *Registry `yaml:"registry" json:"registry"` - Trace *Trace `yaml:"trace" json:"trace"` - Supervisor *User `validate:"required,dive" yaml:"supervisor" json:"supervisor"` - LoggingConfig *log.LoggingConfig `validate:"required,dive" yaml:"logging_config" json:"loggingconfig"` + Spec `yaml:",inline"` + Config *Options `yaml:"config" json:"config"` + Listeners []*Listener `validate:"required,dive" yaml:"listeners" json:"listeners"` + Registry *Registry `yaml:"registry" json:"registry"` + Trace *Trace `yaml:"trace" json:"trace"` + Supervisor *User `validate:"required,dive" yaml:"supervisor" json:"supervisor"` + Logging *log.Config `validate:"required,dive" yaml:"logging" json:"logging"` } // Configuration represents an Arana configuration. diff --git a/pkg/executor/redirect.go b/pkg/executor/redirect.go index 6a8aee4f..0d6e97ec 100644 --- a/pkg/executor/redirect.go +++ b/pkg/executor/redirect.go @@ -317,6 +317,15 @@ func (executor *RedirectExecutor) doExecutorComQuery(ctx *proto.Context, act ast } func (executor *RedirectExecutor) ExecutorComQuery(ctx *proto.Context, h func(result proto.Result, warns uint16, failure error) error) error { + wrapParseErr := func(err error) error { + return mysqlErrors.NewSQLError( + mConstants.ERParseError, + mConstants.SS42000, + "You have an error in your SQL syntax; %s", + err.Error(), + ) + } + p := parser.New() query := ctx.GetQuery() @@ -330,19 +339,31 @@ func (executor *RedirectExecutor) ExecutorComQuery(ctx *proto.Context, h func(re switch strings.IndexByte(query, ';') { case -1: // no ';' exists - stmt, err := p.ParseOneStmt(query, charset, collation) - if err != nil { - return err + var ( + stmt ast.StmtNode + result proto.Result + warns uint16 + failure error + ) + if stmt, failure = p.ParseOneStmt(query, charset, collation); failure == nil { + result, warns, failure = executor.doExecutorComQuery(ctx, stmt) + } else { + failure = wrapParseErr(failure) } - result, warns, failure := executor.doExecutorComQuery(ctx, stmt) return h(result, warns, failure) case len(query) - 1: // suffix is ';' ctx.Data = ctx.Data[:len(ctx.Data)-1] - stmt, err := p.ParseOneStmt(query[:len(query)-1], charset, collation) - if err != nil { - return err + var ( + stmt ast.StmtNode + result proto.Result + warns uint16 + failure error + ) + if stmt, failure = p.ParseOneStmt(query[:len(query)-1], charset, collation); failure == nil { + result, warns, failure = executor.doExecutorComQuery(ctx, stmt) + } else { + failure = wrapParseErr(failure) } - result, warns, failure := executor.doExecutorComQuery(ctx, stmt) return h(result, warns, failure) } @@ -350,7 +371,7 @@ func (executor *RedirectExecutor) ExecutorComQuery(ctx *proto.Context, h func(re p = parser.New() stmts, _, err := p.Parse(query, charset, collation) if err != nil { - return h(nil, 0, err) + return h(nil, 0, wrapParseErr(err)) } for i := range stmts { diff --git a/pkg/runtime/namespace/command.go b/pkg/runtime/namespace/command.go index 52859c69..22bdea0a 100644 --- a/pkg/runtime/namespace/command.go +++ b/pkg/runtime/namespace/command.go @@ -249,7 +249,7 @@ func UpdateSlowThreshold() Command { } } -func UpdateSlowLogger(path string, cfg *log.LoggingConfig) Command { +func UpdateSlowLogger(path string, cfg *log.Config) Command { return func(ns *Namespace) error { ns.slowLog = log.NewSlowLogger(path, cfg) return nil diff --git a/pkg/util/log/logging.go b/pkg/util/log/logging.go index be9d40bd..d741d26e 100644 --- a/pkg/util/log/logging.go +++ b/pkg/util/log/logging.go @@ -18,16 +18,20 @@ package log import ( - "bytes" "context" - "errors" - "fmt" "os" "path/filepath" "strconv" + "strings" + "sync" + "sync/atomic" ) import ( + "github.com/creasty/defaults" + + "github.com/docker/go-units" + "github.com/natefinch/lumberjack" "go.uber.org/zap" @@ -35,8 +39,6 @@ import ( ) type ( - // LogLevel represents the level of logging. - LogLevel int8 // LogType represents the type of logging. LogType string // LoggerKey represents the context key of logging. @@ -44,76 +46,28 @@ type ( ) const ( - // DebugLevel logs are typically voluminous, and are usually disabled in - // production. - DebugLevel = LogLevel(zapcore.DebugLevel) - // InfoLevel is the default logging priority. - InfoLevel = LogLevel(zapcore.InfoLevel) - // WarnLevel logs are more important than Info, but don't need individual - // human review. - WarnLevel = LogLevel(zapcore.WarnLevel) - // ErrorLevel logs are high-priority. If an application is running smoothly, - // it shouldn't generate any error-level logs. - ErrorLevel = LogLevel(zapcore.ErrorLevel) - // PanicLevel logs a message, then panics. - PanicLevel = LogLevel(zapcore.PanicLevel) - // FatalLevel logs a message, then calls os.Exit(1). - FatalLevel = LogLevel(zapcore.FatalLevel) - - _minLevel = DebugLevel - _maxLevel = FatalLevel - MainLog = LogType("main") LogicalSqlLog = LogType("logical sql") PhysicalSqlLog = LogType("physical sql") TxLog = LogType("tx") +) - defaultLoggerLevel = InfoLevel +const ( + _defaultLogName = "arana.log" + _sqlLogName = "sql.log" + _txLogName = "tx.log" + _phySqlLogName = "physql.log" ) -type LoggingConfig struct { - LogName string `yaml:"log_name" json:"log_name"` - LogPath string `yaml:"log_path" json:"log_path"` - LogLevel int `yaml:"log_level" json:"log_level"` - LogMaxSize int `yaml:"log_max_size" json:"log_max_size"` - LogMaxBackups int `yaml:"log_max_backups" json:"log_max_backups"` - LogMaxAge int `yaml:"log_max_age" json:"log_max_age"` - LogCompress bool `yaml:"log_compress" json:"log_compress"` - DefaultLogName string `yaml:"default_log_name" json:"default_log_name"` - TxLogName string `yaml:"tx_log_name" json:"tx_log_name"` - SqlLogEnabled bool `yaml:"sql_log_enabled" json:"sql_log_enabled"` - SqlLogName string `yaml:"sql_log_name" json:"sql_log_name"` - PhysicalSqlLogName string `yaml:"physical_sql_log_name" json:"physical_sql_log_name"` -} - -func (l *LogLevel) UnmarshalText(text []byte) error { - if l == nil { - return errors.New("can't unmarshal a nil *Level") - } - if !l.unmarshalText(text) && !l.unmarshalText(bytes.ToLower(text)) { - return fmt.Errorf("unrecognized level: %q", text) - } - return nil -} - -func (l *LogLevel) unmarshalText(text []byte) bool { - switch string(text) { - case "debug", "DEBUG": - *l = DebugLevel - case "info", "INFO", "": // make the zero value useful - *l = InfoLevel - case "warn", "WARN": - *l = WarnLevel - case "error", "ERROR": - *l = ErrorLevel - case "panic", "PANIC": - *l = PanicLevel - case "fatal", "FATAL": - *l = FatalLevel - default: - return false - } - return true +type Config struct { + Path string `default:"~/arana/logs" yaml:"path" json:"path"` + Level string `default:"INFO" yaml:"level" json:"level"` + MaxSize string `default:"128MB" yaml:"max_size" json:"max_size"` + MaxBackups int `default:"3" yaml:"max_backups" json:"max_backups"` + MaxAge int `default:"7" yaml:"max_age" json:"max_age"` + Compress bool `yaml:"compress" json:"compress"` + Console bool `yaml:"console" json:"console"` + SqlLogEnabled bool `yaml:"sql_log_enabled" json:"sql_log_enabled"` } // Logger TODO add methods support LogType @@ -133,49 +87,89 @@ type Logger interface { } var ( - globalLogger *compositeLogger - - // TODO remove in the future - zapLoggerEncoderConfig = zapcore.EncoderConfig{ - TimeKey: "time", - LevelKey: "level", - NameKey: "logger", - CallerKey: "caller", - MessageKey: "message", - StacktraceKey: "stacktrace", - EncodeLevel: zapcore.CapitalColorLevelEncoder, - EncodeTime: zapcore.ISO8601TimeEncoder, - EncodeDuration: zapcore.SecondsDurationEncoder, - EncodeCaller: zapcore.ShortCallerEncoder, + _globalLogger atomic.Value // *CompositeLogger + _globalLoggerMutex sync.Mutex +) + +// DefaultConfig returns a *Config with default settings. +// These settings will be loaded from OS environs automatically. +func DefaultConfig() *Config { + var c Config + defaults.MustSet(&c) + + if s, ok := os.LookupEnv("ARANA_LOG_PATH"); ok { + c.Path = s } - defaultLoggingConfig = &LoggingConfig{ - LogName: "arana.log", - LogPath: "log", - LogLevel: -1, - LogMaxSize: 10, - LogMaxBackups: 5, - LogMaxAge: 30, - LogCompress: false, - DefaultLogName: "arana.log", - TxLogName: "tx.log", - SqlLogEnabled: true, - SqlLogName: "sql.log", - PhysicalSqlLogName: "physql.log", + + if s, ok := os.LookupEnv("ARANA_LOG_LEVEL"); ok { + c.Level = s } - loggerCfg = defaultLoggingConfig -) -func init() { - globalLogger = NewCompositeLogger(defaultLoggingConfig) + if s, ok := os.LookupEnv("ARANA_LOG_MAX_SIZE"); ok { + c.MaxSize = s + } + + if s, ok := os.LookupEnv("ARANA_LOG_MAX_BACKUPS"); ok { + n, _ := strconv.Atoi(s) + c.MaxBackups = n + } + + if s, ok := os.LookupEnv("ARANA_LOG_MAX_AGE"); ok { + n, _ := strconv.Atoi(s) + c.MaxAge = n + } + + isYes := func(s string) bool { + switch strings.TrimSpace(strings.ToLower(s)) { + case "yes", "on", "1", "true": + return true + } + return false + } + + if s, ok := os.LookupEnv("ARANA_LOG_COMPRESS"); ok { + c.Compress = isYes(s) + } + + if s, ok := os.LookupEnv("ARANA_LOG_CONSOLE"); ok { + c.Console = isYes(s) + } + + if s, ok := os.LookupEnv("ARANA_LOG_SQL"); ok { + c.SqlLogEnabled = isYes(s) + } + + return &c } -func Init(cfg *LoggingConfig) { - loggerCfg = cfg - globalLogger = NewCompositeLogger(cfg) +func Init(cfg *Config) { + _globalLoggerMutex.Lock() + defer _globalLoggerMutex.Unlock() + _globalLogger.Store(NewCompositeLogger(cfg)) } -type compositeLogger struct { - loggerCfg *LoggingConfig +func getGlobalLogger() *CompositeLogger { + if l, ok := _globalLogger.Load().(*CompositeLogger); ok { + return l + } + + _globalLoggerMutex.Lock() + defer _globalLoggerMutex.Unlock() + + if l, ok := _globalLogger.Load().(*CompositeLogger); ok { + return l + } + + var c Config + _ = defaults.Set(&c) + l := NewCompositeLogger(&c) + _globalLogger.Store(l) + + return l +} + +type CompositeLogger struct { + loggerCfg *Config mainLog *zap.SugaredLogger logicalSqlLog *zap.SugaredLogger @@ -186,8 +180,8 @@ type compositeLogger struct { slowLog *zap.SugaredLogger } -func NewCompositeLogger(cfg *LoggingConfig) *compositeLogger { - return &compositeLogger{ +func NewCompositeLogger(cfg *Config) *CompositeLogger { + return &CompositeLogger{ loggerCfg: cfg, mainLog: NewLogger(MainLog, cfg), logicalSqlLog: NewLogger(LogicalSqlLog, cfg), @@ -196,8 +190,36 @@ func NewCompositeLogger(cfg *LoggingConfig) *compositeLogger { } } -func NewLogger(logType LogType, cfg *LoggingConfig) *zap.SugaredLogger { - syncer := zapcore.NewMultiWriteSyncer(zapcore.AddSync(buildLumberJack(cfg.LogPath, logType, cfg)), zapcore.AddSync(os.Stdout)) +func scanLevel(s string, l *zapcore.Level) bool { + switch strings.TrimSpace(strings.ToLower(s)) { + case "debug": + *l = zap.DebugLevel + case "info": + *l = zap.InfoLevel + case "warn", "warning": + *l = zap.WarnLevel + case "error", "err": + *l = zap.ErrorLevel + default: + return false + } + return true +} + +func NewLogger(logType LogType, cfg *Config) *zap.SugaredLogger { + var ws []zapcore.WriteSyncer + ws = append(ws, zapcore.AddSync(buildLumberJack(cfg.Path, logType, cfg))) + + level := zap.DebugLevel + switch logType { + case MainLog: + if cfg.Console { + ws = append(ws, zapcore.AddSync(os.Stdout)) + } + _ = scanLevel(cfg.Level, &level) + } + + syncer := zapcore.NewMultiWriteSyncer(ws...) encoderConfig := zap.NewProductionEncoderConfig() encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder @@ -205,16 +227,13 @@ func NewLogger(logType LogType, cfg *LoggingConfig) *zap.SugaredLogger { // notice: can use zapLoggerEncoderConfig directly, because it would write gibberish into the file. encoder := zapcore.NewConsoleEncoder(encoderConfig) - level := zap.DebugLevel - if logType == MainLog { - level = getLoggerLevel(cfg.LogLevel) - } + core := zapcore.NewCore(encoder, syncer, zap.NewAtomicLevelAt(level)) return zap.New(core, zap.AddCaller(), zap.AddCallerSkip(2)).Sugar() } //nolint:staticcheck -func NewSlowLogger(logPath string, cfg *LoggingConfig) *zap.SugaredLogger { +func NewSlowLogger(logPath string, cfg *Config) *zap.SugaredLogger { syncer := zapcore.NewMultiWriteSyncer(zapcore.AddSync(buildLumberJack(logPath, MainLog, cfg)), zapcore.AddSync(os.Stdout)) encoderConfig := zap.NewProductionEncoderConfig() @@ -227,30 +246,41 @@ func NewSlowLogger(logPath string, cfg *LoggingConfig) *zap.SugaredLogger { } //nolint:staticcheck -func buildLumberJack(logPath string, logType LogType, cfg *LoggingConfig) *lumberjack.Logger { +func buildLumberJack(logPath string, logType LogType, cfg *Config) *lumberjack.Logger { var logName string if logPath == "" { - logPath = currentPath() + logPath = "." + } + + if strings.HasPrefix(logPath, "~") { + home, _ := os.UserHomeDir() + if home == "" { + home = "." + } + logPath = home + logPath[1:] } switch logType { case MainLog: - logName = cfg.LogName + logName = _defaultLogName case LogicalSqlLog: - logName = cfg.SqlLogName + logName = _sqlLogName case PhysicalSqlLog: - logName = cfg.PhysicalSqlLogName + logName = _phySqlLogName case TxLog: - logName = cfg.TxLogName + logName = _txLogName } + filename := filepath.Clean(filepath.Join(logPath, logName)) + maxSize, _ := units.FromHumanSize(cfg.MaxSize) + return &lumberjack.Logger{ - Filename: logPath + string(os.PathSeparator) + logName, - MaxSize: cfg.LogMaxSize, - MaxBackups: cfg.LogMaxBackups, - MaxAge: cfg.LogMaxAge, - Compress: cfg.LogCompress, + Filename: filename, + MaxSize: int(maxSize), + MaxBackups: cfg.MaxBackups, + MaxAge: cfg.MaxAge, + Compress: cfg.Compress, } } @@ -258,42 +288,26 @@ func NewContext(ctx context.Context, connectionID uint32, fields ...zapcore.Fiel return context.WithValue(ctx, LoggerKey(strconv.Itoa(int(connectionID))), WithContext(connectionID, ctx).With(fields...)) } -func WithContext(connectionID uint32, ctx context.Context) *compositeLogger { +func WithContext(connectionID uint32, ctx context.Context) *CompositeLogger { if ctx == nil { - return globalLogger + return getGlobalLogger() } - ctxLogger, ok := ctx.Value(LoggerKey(strconv.Itoa(int(connectionID)))).(*compositeLogger) + ctxLogger, ok := ctx.Value(LoggerKey(strconv.Itoa(int(connectionID)))).(*CompositeLogger) if ok { return ctxLogger } - return NewCompositeLogger(loggerCfg) -} - -func getLoggerLevel(level int) zapcore.Level { - logLevel := LogLevel(level) - if logLevel < _minLevel || logLevel > _maxLevel { - return zapcore.Level(defaultLoggerLevel) - } - return zapcore.Level(logLevel) -} - -func currentPath() string { - dir, err := filepath.Abs(filepath.Dir(os.Args[0])) - if err != nil { - globalLogger.Error("can not get current path") - } - return dir + return getGlobalLogger() } -func (c *compositeLogger) Debug(v ...interface{}) { +func (c *CompositeLogger) Debug(v ...interface{}) { c.mainLog.Debug(v...) } -func (c *compositeLogger) Debugf(format string, v ...interface{}) { +func (c *CompositeLogger) Debugf(format string, v ...interface{}) { c.mainLog.Debugf(format, v...) } -func (c *compositeLogger) DebugfWithLogType(logType LogType, format string, v ...interface{}) { +func (c *CompositeLogger) DebugfWithLogType(logType LogType, format string, v ...interface{}) { c.mainLog.Debugf(format, v...) switch logType { case LogicalSqlLog: @@ -307,15 +321,15 @@ func (c *compositeLogger) DebugfWithLogType(logType LogType, format string, v .. } } -func (c *compositeLogger) Info(v ...interface{}) { +func (c *CompositeLogger) Info(v ...interface{}) { c.mainLog.Info(v...) } -func (c *compositeLogger) Infof(format string, v ...interface{}) { +func (c *CompositeLogger) Infof(format string, v ...interface{}) { c.mainLog.Infof(format, v...) } -func (c *compositeLogger) InfofWithLogType(logType LogType, format string, v ...interface{}) { +func (c *CompositeLogger) InfofWithLogType(logType LogType, format string, v ...interface{}) { c.mainLog.Infof(format, v...) switch logType { case LogicalSqlLog: @@ -329,15 +343,15 @@ func (c *compositeLogger) InfofWithLogType(logType LogType, format string, v ... } } -func (c *compositeLogger) Warn(v ...interface{}) { +func (c *CompositeLogger) Warn(v ...interface{}) { c.mainLog.Warn(v...) } -func (c *compositeLogger) Warnf(format string, v ...interface{}) { +func (c *CompositeLogger) Warnf(format string, v ...interface{}) { c.mainLog.Warnf(format, v...) } -func (c *compositeLogger) WarnfWithLogType(logType LogType, format string, v ...interface{}) { +func (c *CompositeLogger) WarnfWithLogType(logType LogType, format string, v ...interface{}) { c.mainLog.Warnf(format, v...) switch logType { case LogicalSqlLog: @@ -351,15 +365,15 @@ func (c *compositeLogger) WarnfWithLogType(logType LogType, format string, v ... } } -func (c *compositeLogger) Error(v ...interface{}) { +func (c *CompositeLogger) Error(v ...interface{}) { c.mainLog.Error(v...) } -func (c *compositeLogger) Errorf(format string, v ...interface{}) { +func (c *CompositeLogger) Errorf(format string, v ...interface{}) { c.mainLog.Errorf(format, v...) } -func (c *compositeLogger) ErrorfWithLogType(logType LogType, format string, v ...interface{}) { +func (c *CompositeLogger) ErrorfWithLogType(logType LogType, format string, v ...interface{}) { c.mainLog.Errorf(format, v...) switch logType { case LogicalSqlLog: @@ -373,15 +387,15 @@ func (c *compositeLogger) ErrorfWithLogType(logType LogType, format string, v .. } } -func (c *compositeLogger) Panic(v ...interface{}) { +func (c *CompositeLogger) Panic(v ...interface{}) { c.mainLog.Panic(v...) } -func (c *compositeLogger) Panicf(format string, v ...interface{}) { +func (c *CompositeLogger) Panicf(format string, v ...interface{}) { c.mainLog.Panicf(format, v...) } -func (c *compositeLogger) PanicfWithLogType(logType LogType, format string, v ...interface{}) { +func (c *CompositeLogger) PanicfWithLogType(logType LogType, format string, v ...interface{}) { c.mainLog.Panicf(format, v...) switch logType { case LogicalSqlLog: @@ -395,15 +409,15 @@ func (c *compositeLogger) PanicfWithLogType(logType LogType, format string, v .. } } -func (c *compositeLogger) Fatal(v ...interface{}) { +func (c *CompositeLogger) Fatal(v ...interface{}) { c.mainLog.Fatal(v...) } -func (c *compositeLogger) Fatalf(format string, v ...interface{}) { +func (c *CompositeLogger) Fatalf(format string, v ...interface{}) { c.mainLog.Fatalf(format, v...) } -func (c *compositeLogger) FatalfWithLogType(logType LogType, format string, v ...interface{}) { +func (c *CompositeLogger) FatalfWithLogType(logType LogType, format string, v ...interface{}) { c.mainLog.Fatalf(format, v...) switch logType { case LogicalSqlLog: @@ -417,7 +431,7 @@ func (c *compositeLogger) FatalfWithLogType(logType LogType, format string, v .. } } -func (c *compositeLogger) With(fields ...zap.Field) *compositeLogger { +func (c *CompositeLogger) With(fields ...zap.Field) *CompositeLogger { args := make([]interface{}, 0, len(fields)) for _, field := range fields { args = append(args, field) @@ -431,90 +445,90 @@ func (c *compositeLogger) With(fields ...zap.Field) *compositeLogger { // Debug ... func Debug(v ...interface{}) { - globalLogger.Debug(v...) + getGlobalLogger().Debug(v...) } // Debugf ... func Debugf(format string, v ...interface{}) { - globalLogger.Debugf(format, v...) + getGlobalLogger().Debugf(format, v...) } // DebugfWithLogType ... func DebugfWithLogType(logType LogType, format string, v ...interface{}) { - globalLogger.DebugfWithLogType(logType, format, v) + getGlobalLogger().DebugfWithLogType(logType, format, v) } // Info ... func Info(v ...interface{}) { - globalLogger.Info(v...) + getGlobalLogger().Info(v...) } // Infof ... func Infof(format string, v ...interface{}) { - globalLogger.Infof(format, v...) + getGlobalLogger().Infof(format, v...) } // InfofWithLogType ... func InfofWithLogType(logType LogType, format string, v ...interface{}) { - globalLogger.InfofWithLogType(logType, format, v) + getGlobalLogger().InfofWithLogType(logType, format, v) } // Warn ... func Warn(v ...interface{}) { - globalLogger.Warn(v...) + getGlobalLogger().Warn(v...) } // Warnf ... func Warnf(format string, v ...interface{}) { - globalLogger.Warnf(format, v...) + getGlobalLogger().Warnf(format, v...) } // WarnfWithLogType ... func WarnfWithLogType(logType LogType, format string, v ...interface{}) { - globalLogger.WarnfWithLogType(logType, format, v) + getGlobalLogger().WarnfWithLogType(logType, format, v) } // Error ... func Error(v ...interface{}) { - globalLogger.Error(v...) + getGlobalLogger().Error(v...) } // Errorf ... func Errorf(format string, v ...interface{}) { - globalLogger.Errorf(format, v...) + getGlobalLogger().Errorf(format, v...) } // ErrorfWithLogType ... func ErrorfWithLogType(logType LogType, format string, v ...interface{}) { - globalLogger.ErrorfWithLogType(logType, format, v) + getGlobalLogger().ErrorfWithLogType(logType, format, v) } // Panic ... func Panic(v ...interface{}) { - globalLogger.Panic(v...) + getGlobalLogger().Panic(v...) } // Panicf ... func Panicf(format string, v ...interface{}) { - globalLogger.Panicf(format, v...) + getGlobalLogger().Panicf(format, v...) } // ErrorfWithLogType ... func PanicfWithLogType(logType LogType, format string, v ...interface{}) { - globalLogger.PanicfWithLogType(logType, format, v) + getGlobalLogger().PanicfWithLogType(logType, format, v) } // Fatal ... func Fatal(v ...interface{}) { - globalLogger.Fatal(v...) + getGlobalLogger().Fatal(v...) } // Fatalf ... func Fatalf(format string, v ...interface{}) { - globalLogger.Fatalf(format, v...) + getGlobalLogger().Fatalf(format, v...) } // FatalfWithLogType ... func FatalfWithLogType(logType LogType, format string, v ...interface{}) { - globalLogger.FatalfWithLogType(logType, format, v) + getGlobalLogger().FatalfWithLogType(logType, format, v) } diff --git a/test/suite.go b/test/suite.go index 8d3a640d..830e62cc 100644 --- a/test/suite.go +++ b/test/suite.go @@ -38,7 +38,7 @@ import ( ) import ( - "github.com/arana-db/arana/cmd/start" + "github.com/arana-db/arana/cmd" "github.com/arana-db/arana/pkg/constants" "github.com/arana-db/arana/pkg/util/rand2" "github.com/arana-db/arana/testdata" @@ -236,7 +236,7 @@ func (ms *MySuite) SetupSuite() { } go func() { _ = os.Setenv(constants.EnvConfigPath, ms.tmpFile) - start.Run(ms.tmpBootFile) + cmd.Start(ms.tmpBootFile) }() // waiting for arana server started