Skip to content

Commit

Permalink
Add support for port reuse by implementing multiplexing listener
Browse files Browse the repository at this point in the history
  • Loading branch information
Shibo Wang committed May 26, 2021
1 parent 1292bf4 commit 02728d8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
13 changes: 13 additions & 0 deletions config/configgrpc/configgrpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,10 @@ type GRPCServerSettings struct {

// Auth for this receiver
Auth *configauth.Authentication `mapstructure:"auth,omitempty"`

// MuxListener is the multiplexing listener for the Endpoint of NetAddr. Through multiplexing, we can
// support many sockets on the same port with the same listener.
MuxListener net.Listener `mapstructure:"multiplexing_listener"`
}

// ToDialOptions maps configgrpc.GRPCClientSettings to a slice of dial options for gRPC
Expand Down Expand Up @@ -237,6 +241,15 @@ func validateBalancerName(balancerName string) bool {

// ToListener returns the net.Listener constructed from the settings.
func (gss *GRPCServerSettings) ToListener() (net.Listener, error) {
if gss.MuxListener != nil && strings.EqualFold(gss.NetAddr.Endpoint, gss.MuxListener.Addr().String()) {
return gss.MuxListener, nil
}
if gss.MuxListener != nil {
err := gss.MuxListener.Close()
if err != nil {
return nil, err
}
}
return gss.NetAddr.Listen()
}

Expand Down
24 changes: 21 additions & 3 deletions config/confighttp/confighttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"crypto/tls"
"net"
"net/http"
"strings"
"time"

"github.com/rs/cors"
Expand Down Expand Up @@ -123,13 +124,30 @@ type HTTPServerSettings struct {
// CORS needs to be enabled first by providing a non-empty list in CorsOrigins
// A wildcard (*) can be used to match any header.
CorsHeaders []string `mapstructure:"cors_allowed_headers"`

// MuxListener is the multiplexing listener for the Endpoint. Through multiplexing, we can
// support many sockets on the same port with the same listener.
MuxListener net.Listener `mapstructure:"multiplexing_listener"`
}

// ToListener creates a net.Listener.
func (hss *HTTPServerSettings) ToListener() (net.Listener, error) {
listener, err := net.Listen("tcp", hss.Endpoint)
if err != nil {
return nil, err
var listener net.Listener
var err error

if hss.MuxListener != nil && strings.EqualFold(hss.Endpoint, hss.MuxListener.Addr().String()) {
listener = hss.MuxListener
} else {
if hss.MuxListener != nil {
err = hss.MuxListener.Close()
if err != nil {
return nil, err
}
}
listener, err = net.Listen("tcp", hss.Endpoint)
if err != nil {
return nil, err
}
}

if hss.TLSSetting != nil {
Expand Down

0 comments on commit 02728d8

Please sign in to comment.