Skip to content

Commit

Permalink
Fix etcd-io#15402 by moving grpc server from under http server
Browse files Browse the repository at this point in the history
Signed-off-by: Marek Siarkowicz <siarkowicz@google.com>
  • Loading branch information
serathius committed Mar 7, 2023
1 parent 911d77d commit 36d5f4b
Showing 1 changed file with 7 additions and 32 deletions.
39 changes: 7 additions & 32 deletions server/embed/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func (sctx *serveCtx) serve(
return err
}
}
gs := v3rpc.Server(s, tlscfg, nil, gopts...)
gs := v3rpc.Server(s, nil, nil, gopts...)
defer func() {
sctx.lg.Warn("stopping grpc server due to error", zap.Error(err))
gs.Stop()
Expand Down Expand Up @@ -160,7 +160,6 @@ func (sctx *serveCtx) serve(
}
listener := sctx.l
if sctx.secure {
handler = grpcHandlerFunc(gs, handler)
listener, err = transport.NewTLSListener(listener, tlsinfo)
if err != nil {
return err
Expand All @@ -170,21 +169,14 @@ func (sctx *serveCtx) serve(
// TODO: add debug flag; enable logging when debug flag is set
httpmux := sctx.createMux(gwmux, handler)
srv = &http.Server{
Handler: createAccessController(sctx.lg, s, httpmux),
TLSConfig: tlscfg,
ErrorLog: logger, // do not log user error
}
if sctx.insecure {
grpcl := m.Match(cmux.HTTP2())
go func() { errHandler(gs.Serve(grpcl)) }()

httpl := m.Match(cmux.HTTP1())
go func() { errHandler(srv.Serve(httpl)) }()
Handler: createAccessController(sctx.lg, s, httpmux),
ErrorLog: logger, // do not log user error
}
grpcl := m.MatchWithWriters(cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc"))
go func() { errHandler(gs.Serve(grpcl)) }()

if sctx.secure {
go func() { errHandler(srv.Serve(listener)) }()
}
httpl := m.Match(cmux.Any())
go func() { errHandler(srv.Serve(httpl)) }()
if err := configureHttpServer(srv, s.Cfg); err != nil {
sctx.lg.Error("Configure https server failed", zap.Error(err))
return err
Expand All @@ -208,23 +200,6 @@ func configureHttpServer(srv *http.Server, cfg config.ServerConfig) error {
})
}

// grpcHandlerFunc returns an http.Handler that delegates to grpcServer on incoming gRPC
// connections or otherHandler otherwise. Given in gRPC docs.
func grpcHandlerFunc(grpcServer *grpc.Server, otherHandler http.Handler) http.Handler {
if otherHandler == nil {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
grpcServer.ServeHTTP(w, r)
})
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
grpcServer.ServeHTTP(w, r)
} else {
otherHandler.ServeHTTP(w, r)
}
})
}

type registerHandlerFunc func(context.Context, *gw.ServeMux, *grpc.ClientConn) error

func (sctx *serveCtx) registerGateway(opts []grpc.DialOption) (*gw.ServeMux, error) {
Expand Down

0 comments on commit 36d5f4b

Please sign in to comment.