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

proxy: reject connection after graceful wait (#525) #526

Merged
merged 1 commit into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 28 additions & 30 deletions pkg/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,41 +148,39 @@ func (s *SQLServer) Run(ctx context.Context, cfgch <-chan *config.Config) {
}

func (s *SQLServer) onConn(ctx context.Context, conn net.Conn, addr string) {
s.mu.Lock()

if s.mu.status >= statusWaitShutdown {
s.mu.Unlock()
s.logger.Warn("server is shutting down while creating the connection", zap.String("client_addr", conn.RemoteAddr().Network()), zap.Error(conn.Close()))
return
}
tcpKeepAlive, logger, connID, clientConn := func() (bool, *zap.Logger, uint64, *client.ClientConnection) {
s.mu.Lock()
defer s.mu.Unlock()

conns := uint64(len(s.mu.clients))
maxConns := s.mu.maxConnections
// 'maxConns == 0' => unlimited connections
if maxConns != 0 && conns >= maxConns {
s.logger.Warn("too many connections", zap.Uint64("max connections", maxConns), zap.String("client_addr", conn.RemoteAddr().Network()), zap.Error(conn.Close()))
return false, nil, 0, nil
}

conns := uint64(len(s.mu.clients))
maxConns := s.mu.maxConnections
tcpKeepAlive := s.mu.tcpKeepAlive
connID := s.mu.connID
s.mu.connID++
logger := s.logger.With(zap.Uint64("connID", connID), zap.String("client_addr", conn.RemoteAddr().String()),
zap.String("addr", addr))
clientConn := client.NewClientConnection(logger.Named("conn"), conn, s.certMgr.ServerSQLTLS(), s.certMgr.SQLTLS(),
s.hsHandler, connID, addr, &backend.BCConfig{
ProxyProtocol: s.mu.proxyProtocol,
RequireBackendTLS: s.mu.requireBackendTLS,
HealthyKeepAlive: s.mu.healthyKeepAlive,
UnhealthyKeepAlive: s.mu.unhealthyKeepAlive,
ConnBufferSize: s.mu.connBufferSize,
})
s.mu.clients[connID] = clientConn
logger.Debug("new connection", zap.Bool("proxy-protocol", s.mu.proxyProtocol), zap.Bool("require_backend_tls", s.mu.requireBackendTLS))
return s.mu.tcpKeepAlive, logger, connID, clientConn
}()

// 'maxConns == 0' => unlimited connections
if maxConns != 0 && conns >= maxConns {
s.mu.Unlock()
s.logger.Warn("too many connections", zap.Uint64("max connections", maxConns), zap.String("client_addr", conn.RemoteAddr().Network()), zap.Error(conn.Close()))
if clientConn == nil {
return
}

connID := s.mu.connID
s.mu.connID++
logger := s.logger.With(zap.Uint64("connID", connID), zap.String("client_addr", conn.RemoteAddr().String()),
zap.String("addr", addr))
clientConn := client.NewClientConnection(logger.Named("conn"), conn, s.certMgr.ServerSQLTLS(), s.certMgr.SQLTLS(),
s.hsHandler, connID, addr, &backend.BCConfig{
ProxyProtocol: s.mu.proxyProtocol,
RequireBackendTLS: s.mu.requireBackendTLS,
HealthyKeepAlive: s.mu.healthyKeepAlive,
UnhealthyKeepAlive: s.mu.unhealthyKeepAlive,
ConnBufferSize: s.mu.connBufferSize,
})
s.mu.clients[connID] = clientConn
logger.Debug("new connection", zap.Bool("proxy-protocol", s.mu.proxyProtocol), zap.Bool("require_backend_tls", s.mu.requireBackendTLS))
s.mu.Unlock()

metrics.ConnGauge.Inc()
metrics.CreateConnCounter.Inc()

Expand Down
41 changes: 27 additions & 14 deletions pkg/proxy/proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func TestCreateConn(t *testing.T) {
cfg := &config.Config{}
certManager := cert.NewCertManager()
require.NoError(t, certManager.Init(cfg, lg, nil))
server, err := NewSQLServer(lg, cfg, certManager, &panicHsHandler{})
server, err := NewSQLServer(lg, cfg, certManager, &mockHsHandler{})
require.NoError(t, err)
server.Run(context.Background(), nil)
defer func() {
Expand Down Expand Up @@ -149,7 +149,9 @@ func TestGracefulCloseConn(t *testing.T) {

func TestGracefulShutDown(t *testing.T) {
lg, _ := logger.CreateLoggerForTest(t)
hsHandler := backend.NewDefaultHandshakeHandler(nil)
certManager := cert.NewCertManager()
err := certManager.Init(&config.Config{}, lg, nil)
require.NoError(t, err)
cfg := &config.Config{
Proxy: config.ProxyServer{
ProxyServerOnline: config.ProxyServerOnline{
Expand All @@ -158,16 +160,20 @@ func TestGracefulShutDown(t *testing.T) {
},
},
}
server, err := NewSQLServer(lg, cfg, nil, hsHandler)
server, err := NewSQLServer(lg, cfg, certManager, &mockHsHandler{})
require.NoError(t, err)
server.Run(context.Background(), nil)

var wg waitgroup.WaitGroup
wg.Run(func() {
// Wait until the server begins to shut down.
require.Eventually(t, server.IsClosing, 500*time.Millisecond, 10*time.Millisecond)
// The listener should be open.
conn1, err := net.Dial("tcp", server.listeners[0].Addr().String())
// The listener should be open and handshake should proceed.
_, port, err := net.SplitHostPort(server.listeners[0].Addr().String())
require.NoError(t, err)
mdb, err := sql.Open("mysql", fmt.Sprintf("root@tcp(localhost:%s)/test", port))
require.NoError(t, err)
require.ErrorContains(t, mdb.Ping(), "no router")
// The listener should be closed after GracefulWaitBeforeShutdown.
require.Eventually(t, func() bool {
conn, err := net.Dial("tcp", server.listeners[0].Addr().String())
Expand All @@ -176,7 +182,6 @@ func TestGracefulShutDown(t *testing.T) {
}
return err != nil
}, 3*time.Second, 100*time.Millisecond)
require.NoError(t, conn1.Close())
})
require.NoError(t, server.Close())
wg.Wait()
Expand All @@ -191,7 +196,7 @@ func TestMultiAddr(t *testing.T) {
Proxy: config.ProxyServer{
Addr: "0.0.0.0:0,0.0.0.0:0",
},
}, certManager, &panicHsHandler{})
}, certManager, &mockHsHandler{})
require.NoError(t, err)
server.Run(context.Background(), nil)

Expand Down Expand Up @@ -244,7 +249,14 @@ func TestRecoverPanic(t *testing.T) {
certManager := cert.NewCertManager()
err := certManager.Init(&config.Config{}, lg, nil)
require.NoError(t, err)
server, err := NewSQLServer(lg, &config.Config{}, certManager, &panicHsHandler{})
server, err := NewSQLServer(lg, &config.Config{}, certManager, &mockHsHandler{
handshakeResp: func(ctx backend.ConnContext, _ *pnet.HandshakeResp) error {
if ctx.Value(backend.ConnContextKeyConnID).(uint64) == 0 {
panic("HandleHandshakeResp panic")
}
return nil
},
})
require.NoError(t, err)
server.Run(context.Background(), nil)

Expand All @@ -264,23 +276,24 @@ func TestRecoverPanic(t *testing.T) {
certManager.Close()
}

type panicHsHandler struct {
type mockHsHandler struct {
backend.DefaultHandshakeHandler
handshakeResp func(ctx backend.ConnContext, _ *pnet.HandshakeResp) error
}

// HandleHandshakeResp only panics for the first connections.
func (handler *panicHsHandler) HandleHandshakeResp(ctx backend.ConnContext, _ *pnet.HandshakeResp) error {
if ctx.Value(backend.ConnContextKeyConnID).(uint64) == 0 {
panic("HandleHandshakeResp panic")
func (handler *mockHsHandler) HandleHandshakeResp(ctx backend.ConnContext, resp *pnet.HandshakeResp) error {
if handler.handshakeResp != nil {
return handler.handshakeResp(ctx, resp)
}
return nil
}

func (handler *panicHsHandler) GetServerVersion() string {
func (handler *mockHsHandler) GetServerVersion() string {
return "5.7"
}

// GetRouter returns an error for the second connection.
func (handler *panicHsHandler) GetRouter(backend.ConnContext, *pnet.HandshakeResp) (router.Router, error) {
func (handler *mockHsHandler) GetRouter(backend.ConnContext, *pnet.HandshakeResp) (router.Router, error) {
return nil, errors.New("no router")
}