From ea3cd6f48bbb9048f652650af7bee5b2e74f3460 Mon Sep 17 00:00:00 2001 From: xhe Date: Mon, 19 Sep 2022 10:38:37 +0800 Subject: [PATCH] *: apply some lint (#87) --- .github/workflows/build.yml | 82 --------------------- .github/workflows/common.yml | 64 ++++++++++++++++ .github/workflows/main.yml | 15 +++- .github/workflows/test.yml | 41 ----------- cmd/tiproxy/main.go | 2 +- lib/cli/main.go | 2 +- lib/cli/namespace.go | 4 +- lib/cli/util.go | 2 +- lib/config/proxy.go | 16 ++-- lib/util/cmd/encoder.go | 6 +- lib/util/errors/merror.go | 2 +- pkg/manager/config/manager.go | 17 ++--- pkg/manager/config/manager_test.go | 2 +- pkg/manager/router/backend_observer_test.go | 1 + pkg/proxy/backend/authenticator.go | 8 +- pkg/proxy/backend/backend_conn_mgr.go | 18 ++--- pkg/proxy/backend/backend_conn_mgr_test.go | 8 +- pkg/proxy/backend/cmd_processor.go | 6 +- pkg/proxy/backend/mock_backend_test.go | 33 ++++----- pkg/proxy/backend/mock_client_test.go | 32 ++++---- pkg/proxy/backend/mock_proxy_test.go | 2 +- pkg/proxy/net/mysql.go | 6 +- pkg/proxy/net/packetio.go | 2 +- pkg/proxy/net/proxy.go | 6 +- pkg/proxy/proxy.go | 4 +- pkg/server/api/api.go | 3 +- pkg/server/server.go | 6 +- 27 files changed, 169 insertions(+), 221 deletions(-) delete mode 100644 .github/workflows/build.yml create mode 100644 .github/workflows/common.yml delete mode 100644 .github/workflows/test.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml deleted file mode 100644 index 77f56014..00000000 --- a/.github/workflows/build.yml +++ /dev/null @@ -1,82 +0,0 @@ -name: build -on: - workflow_call: - inputs: - debug: - type: boolean - description: "set tmate on failure" - required: true - ref: - type: string - description: "checkout specific ref" - required: true - -jobs: - cmd: - strategy: - matrix: - platform: [ubuntu-latest, macos-latest, windows-latest] - runs-on: ${{ matrix.platform }} - steps: - - if: ${{ runner.os == 'Windows' }} - name: Use GNU tar for faster cache restore - shell: cmd - run: | - echo "Adding GNU tar to PATH" - echo C:\Program Files\Git\usr\bin>>"%GITHUB_PATH%" - - name: "checkout repo" - uses: actions/checkout@v3 - with: - ref: ${{ inputs.ref }} - - name: "setup golang" - uses: actions/setup-go@v3 - with: - go-version-file: go.mod - - name: "try to use build cache" - uses: actions/cache@v3 - with: - path: | - ~/.cache/go-build - ~/go/pkg/mod - ~/Library/Caches/go-build - ~\AppData\Local\go-build - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- - - name: "build cmd" - run: make - - name: "set up tmate session if necessary" - if: ${{ failure() && inputs.debug }} - uses: mxschmitt/action-tmate@v3 - - all: - needs: cmd - runs-on: ubuntu-latest - steps: - - name: "checkout repo" - uses: actions/checkout@v3 - with: - ref: ${{ inputs.ref }} - - name: "setup golang" - uses: actions/setup-go@v3 - with: - go-version: 1.18 - - name: "try to use build cache" - uses: actions/cache@v3 - with: - path: | - ~/.cache/go-build - ~/go/pkg/mod - ~/Library/Caches/go-build - ~\AppData\Local\go-build - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- - - name: "build all" - run: make build - - name: "set up tmate session if necessary" - if: ${{ failure() && inputs.debug }} - uses: mxschmitt/action-tmate@v3 - - name: "set up tmate session if necessary" - if: ${{ failure() && inputs.debug }} - uses: mxschmitt/action-tmate@v3 diff --git a/.github/workflows/common.yml b/.github/workflows/common.yml new file mode 100644 index 00000000..a1b35db5 --- /dev/null +++ b/.github/workflows/common.yml @@ -0,0 +1,64 @@ +name: make +on: + workflow_call: + inputs: + debug: + type: boolean + description: "set tmate on failure" + required: true + target: + type: string + description: "makefile target" + required: true + ref: + type: string + description: "checkout specific ref" + required: true + all_platform: + type: boolean + description: "test on all platforms or not" + default: false + +defaults: + run: + shell: bash + +jobs: + make: + strategy: + matrix: + platform: ${{ inputs.all_platform && fromJSON('["ubuntu-latest", "macos-latest", "windows-latest"]') || fromJSON('["ubuntu-latest"]') }} + runs-on: ${{ matrix.platform }} + steps: + - if: ${{ runner.os == 'Windows' }} + name: Use GNU tar for faster cache restore + shell: cmd + run: | + echo "Adding GNU tar to PATH" + echo C:\Program Files\Git\usr\bin>>"%GITHUB_PATH%" + - name: "checkout repo" + uses: actions/checkout@v3 + with: + ref: ${{ inputs.ref }} + - name: "setup golang" + uses: actions/setup-go@v3 + with: + go-version-file: go.mod + check-latest: true + - name: "set vars" + run: | + echo "GOCACHE=$(go env GOCACHE)" >> $GITHUB_ENV + echo "GOMODCACHE=$(go env GOMODCACHE)" >> $GITHUB_ENV + - name: "try to use build cache" + uses: actions/cache@v3 + with: + path: | + ${{ env.GOCACHE }} + ${{ env.GOMODCACHE }} + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + - run: make ${{ inputs.target }} + - name: "set up tmate session if necessary" + if: ${{ failure() && inputs.debug }} + uses: mxschmitt/action-tmate@v3 diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 88deb3b9..9ed681b2 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -27,15 +27,26 @@ concurrency: cancel-in-progress: true jobs: + cmd: + uses: ./.github/workflows/common.yml + with: + debug: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug }} + ref: ${{ inputs.ref || github.ref }} + target: "cmd" + all_platform: true + build: - uses: ./.github/workflows/build.yml + needs: cmd + uses: ./.github/workflows/common.yml with: debug: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug }} ref: ${{ inputs.ref || github.ref }} + target: "build" test: needs: build - uses: ./.github/workflows/test.yml + uses: ./.github/workflows/common.yml with: debug: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug }} ref: ${{ inputs.ref || github.ref }} + target: "test" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml deleted file mode 100644 index 7f13a57b..00000000 --- a/.github/workflows/test.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: test -on: - workflow_call: - inputs: - debug: - type: boolean - description: "set tmate on failure" - required: true - ref: - type: string - description: "checkout specific ref" - required: true - -jobs: - ut: - runs-on: ubuntu-latest - steps: - - name: "checkout repo" - uses: actions/checkout@v3 - with: - ref: ${{ inputs.ref }} - - name: "setup golang" - uses: actions/setup-go@v3 - with: - go-version-file: go.mod - - name: "try to use build cache" - uses: actions/cache@v3 - with: - path: | - ~/.cache/go-build - ~/go/pkg/mod - ~/Library/Caches/go-build - ~\AppData\Local\go-build - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- - - name: "test all" - run: make test - - name: "set up tmate session if necessary" - if: ${{ failure() && inputs.debug }} - uses: mxschmitt/action-tmate@v3 diff --git a/cmd/tiproxy/main.go b/cmd/tiproxy/main.go index 6ce17045..4d709a5a 100644 --- a/cmd/tiproxy/main.go +++ b/cmd/tiproxy/main.go @@ -39,7 +39,7 @@ func main() { logEncoder := rootCmd.PersistentFlags().String("log_encoder", "", "log in format of tidb, console, or json") logLevel := rootCmd.PersistentFlags().String("log_level", "", "log level") - rootCmd.RunE = func(cmd *cobra.Command, args []string) error { + rootCmd.RunE = func(cmd *cobra.Command, _ []string) error { proxyConfigData, err := ioutil.ReadFile(*configFile) if err != nil { return err diff --git a/lib/cli/main.go b/lib/cli/main.go index b1cd7784..4a8bd5af 100644 --- a/lib/cli/main.go +++ b/lib/cli/main.go @@ -33,7 +33,7 @@ func GetRootCmd() *cobra.Command { logEncoder := rootCmd.PersistentFlags().String("log_encoder", "tidb", "log in format of tidb, console, or json") logLevel := rootCmd.PersistentFlags().String("log_level", "info", "log level") rootCmd.PersistentFlags().Bool("indent", true, "whether indent the returned json") - rootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error { + rootCmd.PersistentPreRunE = func(_ *cobra.Command, _ []string) error { zapcfg := zap.NewDevelopmentConfig() zapcfg.Encoding = *logEncoder if level, err := zap.ParseAtomicLevel(*logLevel); err == nil { diff --git a/lib/cli/namespace.go b/lib/cli/namespace.go index 1f9ba2c6..48b30aa5 100644 --- a/lib/cli/namespace.go +++ b/lib/cli/namespace.go @@ -60,7 +60,7 @@ func GetNamespaceCmd(ctx *Context) *cobra.Command { rootCmd.AddCommand( &cobra.Command{ Use: "list", - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(cmd *cobra.Command, _ []string) error { resp, err := doRequest(cmd.Context(), ctx, http.MethodGet, namespacePrefix, nil) if err != nil { return err @@ -132,7 +132,7 @@ func GetNamespaceCmd(ctx *Context) *cobra.Command { Use: "put", } ns := putNamespace.Flags().String("ns", "-", "file") - putNamespace.RunE = func(cmd *cobra.Command, args []string) error { + putNamespace.RunE = func(cmd *cobra.Command, _ []string) error { in := cmd.InOrStdin() if *ns != "-" { f, err := os.Open(*ns) diff --git a/lib/cli/util.go b/lib/cli/util.go index a52319ab..a887ce8f 100644 --- a/lib/cli/util.go +++ b/lib/cli/util.go @@ -26,9 +26,9 @@ import ( ) type Context struct { - CUrls []string Logger *zap.Logger Client *http.Client + CUrls []string } func doRequest(ctx context.Context, bctx *Context, method string, url string, rd io.Reader) (string, error) { diff --git a/lib/config/proxy.go b/lib/config/proxy.go index e8429b39..7cf56d30 100644 --- a/lib/config/proxy.go +++ b/lib/config/proxy.go @@ -23,13 +23,13 @@ import ( ) type Config struct { - Workdir string `yaml:"workdir,omitempty" toml:"workdir,omitempty" json:"workdir,omitempty"` Proxy ProxyServer `yaml:"proxy,omitempty" toml:"proxy,omitempty" json:"proxy,omitempty"` API API `yaml:"api,omitempty" toml:"api,omitempty" json:"api,omitempty"` + Advance Advance `yaml:"advance,omitempty" toml:"advance,omitempty" json:"advance,omitempty"` + Workdir string `yaml:"workdir,omitempty" toml:"workdir,omitempty" json:"workdir,omitempty"` + Security Security `yaml:"security,omitempty" toml:"security,omitempty" json:"security,omitempty"` Metrics Metrics `yaml:"metrics,omitempty" toml:"metrics,omitempty" json:"metrics,omitempty"` Log Log `yaml:"log,omitempty" toml:"log,omitempty" json:"log,omitempty"` - Security Security `yaml:"security,omitempty" toml:"security,omitempty" json:"security,omitempty"` - Advance Advance `yaml:"advance,omitempty" toml:"advance,omitempty" json:"advance,omitempty"` } type Metrics struct { @@ -43,23 +43,23 @@ type ProxyServerOnline struct { } type ProxyServer struct { - ProxyServerOnline Addr string `yaml:"addr,omitempty" toml:"addr,omitempty" json:"addr,omitempty"` PDAddrs string `yaml:"pd-addrs,omitempty" toml:"pd-addrs,omitempty" json:"pd-addrs,omitempty"` ProxyProtocol string `yaml:"proxy-protocol,omitempty" toml:"proxy-protocol,omitempty" json:"proxy-protocol,omitempty"` + ProxyServerOnline } type API struct { Addr string `yaml:"addr,omitempty" toml:"addr,omitempty" json:"addr,omitempty"` - EnableBasicAuth bool `yaml:"enable-basic-auth,omitempty" toml:"enable-basic-auth,omitempty" json:"enable-basic-auth,omitempty"` User string `yaml:"user,omitempty" toml:"user,omitempty" json:"user,omitempty"` Password string `yaml:"password,omitempty" toml:"password,omitempty" json:"password,omitempty"` + EnableBasicAuth bool `yaml:"enable-basic-auth,omitempty" toml:"enable-basic-auth,omitempty" json:"enable-basic-auth,omitempty"` } type Advance struct { PeerPort string `yaml:"peer-port,omitempty" toml:"peer-port,omitempty" json:"peer-port,omitempty"` - IgnoreWrongNamespace bool `yaml:"ignore-wrong-namespace,omitempty" toml:"ignore-wrong-namespace,omitempty" json:"ignore-wrong-namespace,omitempty"` WatchInterval string `yaml:"watch-interval,omitempty" toml:"watch-interval,omitempty" json:"watch-interval,omitempty"` + IgnoreWrongNamespace bool `yaml:"ignore-wrong-namespace,omitempty" toml:"ignore-wrong-namespace,omitempty" json:"ignore-wrong-namespace,omitempty"` } type Log struct { @@ -78,8 +78,8 @@ type LogFile struct { type TLSConfig struct { Cert string `yaml:"cert,omitempty" toml:"cert,omitempty" json:"cert,omitempty"` Key string `yaml:"key,omitempty" toml:"key,omitempty" json:"key,omitempty"` - AutoCerts bool `yaml:"auto-certs,omitempty" toml:"auto-certs,omitempty" json:"auto-certs,omitempty"` CA string `yaml:"ca,omitempty" toml:"ca,omitempty" json:"ca,omitempty"` + AutoCerts bool `yaml:"auto-certs,omitempty" toml:"auto-certs,omitempty" json:"auto-certs,omitempty"` SkipCA bool `yaml:"skip-ca,omitempty" toml:"skip-ca,omitempty" json:"skip-ca,omitempty"` } @@ -92,11 +92,11 @@ func (c TLSConfig) HasCA() bool { } type Security struct { - RSAKeySize int `yaml:"rsa-key-size,omitempty" toml:"rsa-key-size,omitempty" json:"rsa-key-size,omitempty"` ServerTLS TLSConfig `yaml:"server-tls,omitempty" toml:"server-tls,omitempty" json:"server-tls,omitempty"` PeerTLS TLSConfig `yaml:"peer-tls,omitempty" toml:"peer-tls,omitempty" json:"peer-tls,omitempty"` ClusterTLS TLSConfig `yaml:"cluster-tls,omitempty" toml:"cluster-tls,omitempty" json:"cluster-tls,omitempty"` SQLTLS TLSConfig `yaml:"sql-tls,omitempty" toml:"sql-tls,omitempty" json:"sql-tls,omitempty"` + RSAKeySize int `yaml:"rsa-key-size,omitempty" toml:"rsa-key-size,omitempty" json:"rsa-key-size,omitempty"` } func NewConfig(data []byte) (*Config, error) { diff --git a/lib/util/cmd/encoder.go b/lib/util/cmd/encoder.go index 8258fa36..8ebe738f 100644 --- a/lib/util/cmd/encoder.go +++ b/lib/util/cmd/encoder.go @@ -30,9 +30,9 @@ var ( ) type tidbEncoder struct { + line *buffer.Buffer zapcore.EncoderConfig openNamespaces int - line *buffer.Buffer } func NewTiDBEncoder(cfg zapcore.EncoderConfig) zapcore.Encoder { @@ -42,11 +42,11 @@ func NewTiDBEncoder(cfg zapcore.EncoderConfig) zapcore.Encoder { if cfg.LineEnding == "" { cfg.LineEnding = zapcore.DefaultLineEnding } - return &tidbEncoder{cfg, 0, _pool.Get()} + return &tidbEncoder{_pool.Get(), cfg, 0} } func (c tidbEncoder) clone() *tidbEncoder { - return &tidbEncoder{c.EncoderConfig, 0, _pool.Get()} + return &tidbEncoder{_pool.Get(), c.EncoderConfig, 0} } func (c tidbEncoder) Clone() zapcore.Encoder { diff --git a/lib/util/errors/merror.go b/lib/util/errors/merror.go index 64f65771..d8cccfd1 100644 --- a/lib/util/errors/merror.go +++ b/lib/util/errors/merror.go @@ -24,8 +24,8 @@ var ( ) type MError struct { - uerr []error cerr error + uerr []error } func (e *MError) Format(st fmt.State, verb rune) { diff --git a/pkg/manager/config/manager.go b/pkg/manager/config/manager.go index ed84af9c..7103d612 100644 --- a/pkg/manager/config/manager.go +++ b/pkg/manager/config/manager.go @@ -42,17 +42,14 @@ var ( ) type ConfigManager struct { - wg waitgroup.WaitGroup - cancel context.CancelFunc - logger *zap.Logger - kv mvcc.WatchableKV - basePath string - - // config - ignoreWrongNamespace bool + wg waitgroup.WaitGroup + kv mvcc.WatchableKV + cancel context.CancelFunc + logger *zap.Logger + chProxy chan *config.ProxyServerOnline + basePath string watchInterval time.Duration - - chProxy chan *config.ProxyServerOnline + ignoreWrongNamespace bool } func NewConfigManager() *ConfigManager { diff --git a/pkg/manager/config/manager_test.go b/pkg/manager/config/manager_test.go index 267c7b4a..7d0fe651 100644 --- a/pkg/manager/config/manager_test.go +++ b/pkg/manager/config/manager_test.go @@ -170,7 +170,7 @@ func TestBaseWatch(t *testing.T) { cfgmgr, ctx := testConfigManager(t, &config.Config{}) ch := make(chan string, 1) - cfgmgr.watch(ctx, "test", "t", func(l *zap.Logger, e mvccpb.Event) { + cfgmgr.watch(ctx, "test", "t", func(_ *zap.Logger, e mvccpb.Event) { ch <- string(e.Kv.Value) }) diff --git a/pkg/manager/router/backend_observer_test.go b/pkg/manager/router/backend_observer_test.go index d11cb328..8a93ea1e 100644 --- a/pkg/manager/router/backend_observer_test.go +++ b/pkg/manager/router/backend_observer_test.go @@ -228,6 +228,7 @@ func createEtcdServer(t *testing.T, addr string) *embed.Etcd { cfg.Dir = t.TempDir() cfg.LCUrls = []url.URL{*serverURL} cfg.LPUrls = []url.URL{*serverURL} + cfg.ZapLoggerBuilder = embed.NewZapLoggerBuilder(logger.CreateLoggerForTest(t)) cfg.LogLevel = "fatal" etcd, err := embed.StartEtcd(cfg) require.NoError(t, err) diff --git a/pkg/proxy/backend/authenticator.go b/pkg/proxy/backend/authenticator.go index 37667210..ea223266 100644 --- a/pkg/proxy/backend/authenticator.go +++ b/pkg/proxy/backend/authenticator.go @@ -36,13 +36,13 @@ const supportedServerCapabilities = mysql.ClientLongPassword | mysql.ClientFound // Authenticator handshakes with the client and the backend. type Authenticator struct { - user string + backendTLSConfig *tls.Config dbname string // default database name - capability uint32 // client capability - collation uint8 serverAddr string + user string attrs []byte // no need to parse - backendTLSConfig *tls.Config + capability uint32 // client capability + collation uint8 } func (auth *Authenticator) String() string { diff --git a/pkg/proxy/backend/backend_conn_mgr.go b/pkg/proxy/backend/backend_conn_mgr.go index 12c40176..0bbf0de4 100644 --- a/pkg/proxy/backend/backend_conn_mgr.go +++ b/pkg/proxy/backend/backend_conn_mgr.go @@ -48,9 +48,9 @@ type signalRedirect struct { } type redirectResult struct { + err error from string to string - err error } // BackendConnManager migrates a session from one BackendConnection to another. @@ -63,24 +63,24 @@ type redirectResult struct { // - If it retries after each command: the latency will be unacceptable afterwards if it always fails. // - If it stops receiving signals: the previous new backend may be abnormal but the next new backend may be good. type BackendConnManager struct { - logger *zap.Logger - connectionID uint64 - authenticator *Authenticator - cmdProcessor *CmdProcessor - eventReceiver unsafe.Pointer - backendConn *BackendConnection // processLock makes redirecting and command processing exclusive. processLock sync.Mutex + wg waitgroup.WaitGroup // signalReceived is used to notify the signal processing goroutine. signalReceived chan struct{} + authenticator *Authenticator + cmdProcessor *CmdProcessor + eventReceiver unsafe.Pointer + logger *zap.Logger // type *signalRedirect, it saves the last signal if there are multiple signals. // It will be set to nil after migration. signal unsafe.Pointer // redirectResCh is used to notify the event receiver asynchronously. redirectResCh chan *redirectResult // cancelFunc is used to cancel the signal processing goroutine. - cancelFunc context.CancelFunc - wg waitgroup.WaitGroup + cancelFunc context.CancelFunc + backendConn *BackendConnection + connectionID uint64 } // NewBackendConnManager creates a BackendConnManager. diff --git a/pkg/proxy/backend/backend_conn_mgr_test.go b/pkg/proxy/backend/backend_conn_mgr_test.go index 1d833cc9..1bef9600 100644 --- a/pkg/proxy/backend/backend_conn_mgr_test.go +++ b/pkg/proxy/backend/backend_conn_mgr_test.go @@ -225,7 +225,7 @@ func TestNormalRedirect(t *testing.T) { // 2nd handshake: redirect immediately after connection { client: nil, - proxy: func(clientIO, backendIO *pnet.PacketIO) error { + proxy: func(_, _ *pnet.PacketIO) error { backend1 := ts.mp.backendConn ts.mp.Redirect(ts.tc.backendListener.Addr().String()) ts.mp.getEventReceiver().(*mockEventReceiver).checkEvent(t, eventSucceed) @@ -362,7 +362,7 @@ func TestConnectFail(t *testing.T) { proxy: func(clientIO, backendIO *pnet.PacketIO) error { return ts.mp.Connect(context.Background(), ts.tc.backendListener.Addr().String(), clientIO, ts.mp.frontendTLSConfig, ts.mp.backendTLSConfig) }, - backend: func(packetIO *pnet.PacketIO) error { + backend: func(_ *pnet.PacketIO) error { conn, err := ts.tc.backendListener.Accept() require.NoError(ts.t, err) ts.tc.backendIO = pnet.NewPacketIO(conn) @@ -476,7 +476,7 @@ func TestSpecialCmds(t *testing.T) { // 2nd handshake { client: nil, - proxy: func(clientIO, backendIO *pnet.PacketIO) error { + proxy: func(_, _ *pnet.PacketIO) error { backend1 := ts.mp.backendConn ts.mp.Redirect(ts.tc.backendListener.Addr().String()) ts.mp.getEventReceiver().(*mockEventReceiver).checkEvent(t, eventSucceed) @@ -507,7 +507,7 @@ func TestCloseWhileRedirect(t *testing.T) { }, // close and redirect concurrently { - proxy: func(clientIO, backendIO *pnet.PacketIO) error { + proxy: func(_, _ *pnet.PacketIO) error { // Send an event to make Close() block at notifying. addr := ts.tc.backendListener.Addr().String() eventReceiver := ts.mp.getEventReceiver().(*mockEventReceiver) diff --git a/pkg/proxy/backend/cmd_processor.go b/pkg/proxy/backend/cmd_processor.go index dd0e26ba..5b4317c9 100644 --- a/pkg/proxy/backend/cmd_processor.go +++ b/pkg/proxy/backend/cmd_processor.go @@ -31,11 +31,11 @@ const ( // CmdProcessor maintains the transaction and prepared statement status and decides whether the session can be redirected. type CmdProcessor struct { - capability uint32 - // Only includes in_trans or quit status. - serverStatus uint32 // Each prepared statement has an independent status. preparedStmtStatus map[int]uint32 + capability uint32 + // Only includes in_trans or quit status. + serverStatus uint32 } func NewCmdProcessor() *CmdProcessor { diff --git a/pkg/proxy/backend/mock_backend_test.go b/pkg/proxy/backend/mock_backend_test.go index b915d1da..ef2e44b0 100644 --- a/pkg/proxy/backend/mock_backend_test.go +++ b/pkg/proxy/backend/mock_backend_test.go @@ -24,23 +24,22 @@ import ( ) type backendConfig struct { + // for auth + tlsConfig *tls.Config + authPlugin string + salt []byte + columns int + loops int + params int + rows int + respondType respondType // for cmd + stmtNum int + capability uint32 + status uint16 + authSucceed bool + switchAuth bool // for both auth and cmd abnormalExit bool - // for auth - tlsConfig *tls.Config - capability uint32 - salt []byte - authPlugin string - switchAuth bool - authSucceed bool - // for cmd - respondType respondType - columns int - rows int - params int - status uint16 - loops int - stmtNum int } func newBackendConfig() *backendConfig { @@ -56,15 +55,15 @@ func newBackendConfig() *backendConfig { } type mockBackend struct { + err error // Inputs that assigned by the test and will be sent to the client. *backendConfig // Outputs that received from the client and will be checked by the test. username string - authData []byte db string + authData []byte attrs []byte clientCapability uint32 - err error } func newMockBackend(cfg *backendConfig) *mockBackend { diff --git a/pkg/proxy/backend/mock_client_test.go b/pkg/proxy/backend/mock_client_test.go index ad4d7e52..08040337 100644 --- a/pkg/proxy/backend/mock_client_test.go +++ b/pkg/proxy/backend/mock_client_test.go @@ -23,23 +23,23 @@ import ( ) type clientConfig struct { - // for both auth and cmd - abnormalExit bool // for auth - tlsConfig *tls.Config - capability uint32 - username string - dbName string - collation uint8 - authPlugin string - authData []byte - attrs []byte + tlsConfig *tls.Config + sql string + username string + dbName string + authPlugin string + dataBytes []byte + attrs []byte + authData []byte + filePkts int + prepStmtID int + capability uint32 + collation uint8 // for cmd - cmd byte - dataBytes []byte - filePkts int - prepStmtID int - sql string + cmd byte + // for both auth and cmd + abnormalExit bool } func newClientConfig() *clientConfig { @@ -57,11 +57,11 @@ func newClientConfig() *clientConfig { } type mockClient struct { + err error // Inputs that assigned by the test and will be sent to the server. *clientConfig // Outputs that received from the server and will be checked by the test. authSucceed bool - err error } func newMockClient(cfg *clientConfig) *mockClient { diff --git a/pkg/proxy/backend/mock_proxy_test.go b/pkg/proxy/backend/mock_proxy_test.go index dbcb3d37..759c29a8 100644 --- a/pkg/proxy/backend/mock_proxy_test.go +++ b/pkg/proxy/backend/mock_proxy_test.go @@ -26,8 +26,8 @@ import ( type proxyConfig struct { frontendTLSConfig *tls.Config backendTLSConfig *tls.Config - capability uint32 sessionToken string + capability uint32 waitRedirect bool } diff --git a/pkg/proxy/net/mysql.go b/pkg/proxy/net/mysql.go index dd4b09c4..a7d974c9 100644 --- a/pkg/proxy/net/mysql.go +++ b/pkg/proxy/net/mysql.go @@ -64,13 +64,13 @@ func ParseInitialHandshake(data []byte) uint32 { // HandshakeResp indicates the response read from the client. type HandshakeResp struct { - Capability uint32 - Collation uint8 User string DB string - AuthData []byte AuthPlugin string Attrs []byte + AuthData []byte + Capability uint32 + Collation uint8 } func ParseHandshakeResponse(data []byte) *HandshakeResp { diff --git a/pkg/proxy/net/packetio.go b/pkg/proxy/net/packetio.go index e171c84d..cd49b378 100644 --- a/pkg/proxy/net/packetio.go +++ b/pkg/proxy/net/packetio.go @@ -76,9 +76,9 @@ func (f *rdbufConn) Read(b []byte) (int, error) { type PacketIO struct { conn net.Conn buf *bufio.ReadWriter - sequence uint8 proxyInited *atomic.Bool proxy *Proxy + sequence uint8 } func NewPacketIO(conn net.Conn) *PacketIO { diff --git a/pkg/proxy/net/proxy.go b/pkg/proxy/net/proxy.go index 0e2da6cb..bd8ea19b 100644 --- a/pkg/proxy/net/proxy.go +++ b/pkg/proxy/net/proxy.go @@ -69,16 +69,16 @@ const ( ) type ProxyTlv struct { - typ ProxyTlvType content []byte + typ ProxyTlvType } type Proxy struct { - Version ProxyVersion - Command ProxyCommand SrcAddress net.Addr DstAddress net.Addr TLV []ProxyTlv + Version ProxyVersion + Command ProxyCommand } func (p *Proxy) ToBytes() []byte { diff --git a/pkg/proxy/proxy.go b/pkg/proxy/proxy.go index 7cfaedd2..74f56a5b 100644 --- a/pkg/proxy/proxy.go +++ b/pkg/proxy/proxy.go @@ -34,10 +34,10 @@ import ( type serverState struct { sync.RWMutex - tcpKeepAlive bool + clients map[uint64]*client.ClientConnection connID uint64 maxConnections uint64 - clients map[uint64]*client.ClientConnection + tcpKeepAlive bool } type SQLServer struct { diff --git a/pkg/server/api/api.go b/pkg/server/api/api.go index 945675a9..963cda03 100644 --- a/pkg/server/api/api.go +++ b/pkg/server/api/api.go @@ -19,11 +19,10 @@ import ( "github.com/pingcap/TiProxy/lib/config" mgrcfg "github.com/pingcap/TiProxy/pkg/manager/config" mgrns "github.com/pingcap/TiProxy/pkg/manager/namespace" - "go.uber.org/atomic" "go.uber.org/zap" ) -func Register(group *gin.RouterGroup, ready *atomic.Bool, cfg config.API, logger *zap.Logger, nsmgr *mgrns.NamespaceManager, cfgmgr *mgrcfg.ConfigManager) { +func Register(group *gin.RouterGroup, cfg config.API, logger *zap.Logger, nsmgr *mgrns.NamespaceManager, cfgmgr *mgrcfg.ConfigManager) { { adminGroup := group.Group("admin") if cfg.EnableBasicAuth { diff --git a/pkg/server/server.go b/pkg/server/server.go index d37a9ef4..416fbdc2 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -106,9 +106,9 @@ func NewServer(ctx context.Context, cfg *config.Config, logger *zap.Logger, pubA // We have some alternative solution, for example: // 1. globally lazily creation of managers. It introduced racing/chaos-management/hard-code-reading as in TiDB. // 2. pass down '*Server' struct such that the underlying relies on the pointer only. But it does not work well for golang. To avoid cyclic imports between 'api' and `server` packages, two packages needs to be merged. That is basically what happened to TiDB '*Session'. - api.Register(engine.Group("/api"), ready, cfg.API, logger.Named("api"), srv.NamespaceManager, srv.ConfigManager) + api.Register(engine.Group("/api"), cfg.API, logger.Named("api"), srv.NamespaceManager, srv.ConfigManager) - srv.Etcd, err = buildEtcd(ctx, cfg, logger.Named("etcd"), pubAddr, engine) + srv.Etcd, err = buildEtcd(cfg, logger.Named("etcd"), pubAddr, engine) if err != nil { err = errors.WithStack(err) return @@ -246,7 +246,7 @@ func (s *Server) Close() error { return errors.Collect(ErrCloseServer, errs...) } -func buildEtcd(ctx context.Context, cfg *config.Config, logger *zap.Logger, pubAddr string, engine *gin.Engine) (srv *embed.Etcd, err error) { +func buildEtcd(cfg *config.Config, logger *zap.Logger, pubAddr string, engine *gin.Engine) (srv *embed.Etcd, err error) { etcd_cfg := embed.NewConfig() if etcd_cfg.ClientTLSInfo, etcd_cfg.PeerTLSInfo, err = security.BuildEtcdTLSConfig(logger, cfg.Security.ServerTLS, cfg.Security.PeerTLS); err != nil {