From 2bbc426bef21e78ddb5576693a84173f49f5237d Mon Sep 17 00:00:00 2001 From: Maxim Merzhanov Date: Fri, 22 Nov 2019 16:53:40 +0300 Subject: [PATCH] implement tcp/http mux --- Gopkg.lock | 4 +- cluster/leader_client.go | 3 - codes/codes.go | 4 +- config_service_integration_test.go | 4 +- main.go | 45 ++++--- mux/matchers.go | 44 +++++++ mux/mux.go | 186 +++++++++++++++++++++++++++++ mux/mux_test.go | 118 ++++++++++++++++++ mux/pool.go | 22 ++++ 9 files changed, 396 insertions(+), 34 deletions(-) create mode 100644 mux/matchers.go create mode 100644 mux/mux.go create mode 100644 mux/mux_test.go create mode 100644 mux/pool.go diff --git a/Gopkg.lock b/Gopkg.lock index 8e31543..b01271b 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -277,9 +277,10 @@ version = "v2.0.0" [[projects]] - digest = "1:9d9e6b448c424b4997af848f202fab57a57d1f3e54c856e92cc90750265bce0b" + digest = "1:8c3ec5a8ef8f4db927ab30671f00486a2d0ef4e03345f261cf9369a2ae27877a" name = "github.com/integration-system/isp-lib" packages = [ + "atomic", "backend", "bootstrap", "config", @@ -755,6 +756,7 @@ "github.com/integration-system/isp-lib-test/docker", "github.com/integration-system/isp-lib-test/utils", "github.com/integration-system/isp-lib-test/utils/postgres", + "github.com/integration-system/isp-lib/atomic", "github.com/integration-system/isp-lib/backend", "github.com/integration-system/isp-lib/bootstrap", "github.com/integration-system/isp-lib/config", diff --git a/cluster/leader_client.go b/cluster/leader_client.go index 24a1f1a..0f14519 100644 --- a/cluster/leader_client.go +++ b/cluster/leader_client.go @@ -95,9 +95,6 @@ func getUrl(address string) string { } cfg := config.Get().(*conf.Configuration) - // REMOVE - addr.Port = addr.Port + 5 - params := url.Values{} params.Add(ClusterParam, "true") // TODO выпилить instance_uuid ? diff --git a/codes/codes.go b/codes/codes.go index a604922..7939012 100644 --- a/codes/codes.go +++ b/codes/codes.go @@ -34,6 +34,6 @@ const ( RoutesServiceSendRoutesError = 1020 ConfigServiceBroadcastConfigError = 1021 - // Cmux - InitCmuxError = 1022 + // Mux + InitMuxError = 1022 ) diff --git a/config_service_integration_test.go b/config_service_integration_test.go index 358c34c..77e573b 100644 --- a/config_service_integration_test.go +++ b/config_service_integration_test.go @@ -97,9 +97,7 @@ func setup(testCtx *ctx.TestContext, runTest func() int) int { }, } configsGrpcAddrs[i] = grpcAddr - //configsHttpAddrs[i] = httpAddr - // REMOVE - configsHttpAddrs[i] = getConfigServiceAddress(i, "9006") + configsHttpAddrs[i] = httpAddr configs[i] = cfg peersAddrs[i] = httpAddr.GetAddress() } diff --git a/main.go b/main.go index ac3fc31..d818602 100644 --- a/main.go +++ b/main.go @@ -18,6 +18,7 @@ import ( "isp-config-service/helper" "isp-config-service/holder" "isp-config-service/model" + "isp-config-service/mux" "isp-config-service/raft" "isp-config-service/service" "isp-config-service/store" @@ -37,6 +38,7 @@ var ( date = "undefined" shutdownChan = make(chan struct{}) + muxer mux.Mux ) func init() { @@ -79,7 +81,7 @@ func main() { httpListener, raftListener, err := initMultiplexer(cfg.WS.Rest) if err != nil { - log.Fatalf(codes.InitCmuxError, "init cmux: %v", err) + log.Fatalf(codes.InitMuxError, "init mux: %v", err) } _, raftStore := initRaft(raftListener, cfg.Cluster, declaration) @@ -103,24 +105,16 @@ func initMultiplexer(addressConfiguration structure.AddressConfiguration) (net.L return nil, nil, fmt.Errorf("create tcp transport: %v", err) } - // REMOVE - outerAddr.Port = outerAddr.Port + 5 - httpListener, err := net.ListenTCP("tcp4", outerAddr) - if err != nil { - return nil, nil, fmt.Errorf("create tcp transport: %v", err) - } - return httpListener, tcpListener, nil + muxer = mux.New(tcpListener) + httpListener := muxer.Match(mux.HTTP1()) + raftListener := muxer.Match(mux.Any()) - //m := cmux.New(tcpListener) - //httpListener := m.Match(cmux.HTTP1Fast()) - //raftListener := m.Match(cmux.Any()) - // - //go func() { - // if err := m.Serve(); err != nil && !strings.Contains(err.Error(), "use of closed network connection") { - // log.Fatalf(codes.InitCmuxError, "serve cmux: %v", err) - // } - //}() - //return httpListener, raftListener, nil + go func() { + if err := muxer.Serve(); err != nil { + log.Fatalf(codes.InitMuxError, "serve mux: %v", err) + } + }() + return httpListener, raftListener, nil } func initWebsocket(ctx context.Context, listener net.Listener, raftStore *store.Store) { @@ -190,24 +184,25 @@ func initGrpc(bindAddress structure.AddressConfiguration, raftStore *store.Store backend.StartBackendGrpcServer(bindAddress, defaultService) } -func onShutdown(ctx context.Context, sig os.Signal) { - log.Debugf(0, "received shutdown signal: %s", sig.String()) +func onShutdown(ctx context.Context, _ os.Signal) { defer close(shutdownChan) backend.StopGrpcServer() holder.EtpServer.Close() + if err := holder.HttpServer.Shutdown(ctx); err != nil { + log.Warnf(codes.ShutdownHttpServerError, "http server shutdown err: %v", err) + } else { + log.Info(codes.ShutdownHttpServerInfo, "http server shutdown success") + } + if err := holder.ClusterClient.Shutdown(); err != nil { log.Warnf(codes.RaftShutdownError, "raft shutdown err: %v", err) } else { log.Info(codes.RaftShutdownInfo, "raft shutdown success") } - if err := holder.HttpServer.Shutdown(ctx); err != nil { - log.Warnf(codes.ShutdownHttpServerError, "http server shutdown err: %v", err) - } else { - log.Info(codes.ShutdownHttpServerInfo, "http server shutdown success") - } + _ = muxer.Close() } func getOutboundIp() (string, error) { diff --git a/mux/matchers.go b/mux/matchers.go new file mode 100644 index 0000000..cdc365f --- /dev/null +++ b/mux/matchers.go @@ -0,0 +1,44 @@ +package mux + +import ( + "strings" +) + +type Matcher func([]byte) bool + +// Any is a Matcher that matches any connection. +func Any() Matcher { + return func(_ []byte) bool { + return true + } +} + +var httpMethods = map[string]struct{}{ + "OPTIONS": {}, + "HEAD": {}, + "GET": {}, + "POST": {}, + "PUT": {}, + "PATCH": {}, + "DELETE": {}, + "TRACE": {}, + "CONNECT": {}, +} + +// HTTP1 only matches the methods in the HTTP request. +func HTTP1() Matcher { + return func(data []byte) bool { + // max length of method + l := 7 + if len(data) < l { + l = len(data) + } + methodB := data[:l] + ss := strings.Split(string(methodB), " ") + if len(ss) == 0 { + return false + } + _, knownMethod := httpMethods[ss[0]] + return knownMethod + } +} diff --git a/mux/mux.go b/mux/mux.go new file mode 100644 index 0000000..c2e4588 --- /dev/null +++ b/mux/mux.go @@ -0,0 +1,186 @@ +package mux + +import ( + "errors" + "github.com/integration-system/isp-lib/atomic" + "net" + "sync" +) + +var ( + ErrListenerClosed = errors.New("mux: listener closed") + ErrNotMatched = errors.New("mux: connection not matched by a matcher") +) + +type Mux interface { + Match(Matcher) net.Listener + Serve() error + OnError(func(error)) + Close() error +} + +type matchersListener struct { + matcher Matcher + listener *muxListener +} + +type mux struct { + listener net.Listener + ml []matchersListener + connBufLen int + doneCh chan struct{} + errHandler func(error) +} + +func (m *mux) Match(matcher Matcher) net.Listener { + ml := newMuxListener(m.listener, m.connBufLen) + m.ml = append(m.ml, matchersListener{matcher: matcher, listener: ml}) + return ml +} + +func (m *mux) Serve() error { + var wg sync.WaitGroup + + defer func() { + close(m.doneCh) + wg.Wait() + + for _, sl := range m.ml { + _ = sl.listener.Close() + for c := range sl.listener.connCh { + _ = c.Close() + } + close(sl.listener.connCh) + } + }() + + for { + c, err := m.listener.Accept() + if err != nil { + if ne, ok := err.(net.Error); ok && ne.Temporary() { + continue + } + return err + } + + wg.Add(1) + go m.serve(c, &wg) + } +} + +func (m *mux) Close() error { + return m.listener.Close() +} + +func (m *mux) OnError(f func(error)) { + m.errHandler = f +} + +func (m *mux) serve(c net.Conn, wg *sync.WaitGroup) { + defer wg.Done() + + buf := getBuffer() + n, err := c.Read(buf) + data := buf[:n] + for _, matcher := range m.ml { + matched := matcher.matcher(data) + if matched { + if matcher.listener.closed.Get() { + break + } + muc := newMuxConn(c, data, err) + select { + case matcher.listener.connCh <- muc: + case <-m.doneCh: + putBuffer(buf) + _ = c.Close() + } + return + } + } + + putBuffer(buf) + _ = c.Close() + if m.errHandler != nil { + m.errHandler(ErrNotMatched) + } +} + +func (m *mux) handleErr(err error) bool { + if ne, ok := err.(net.Error); ok { + return ne.Temporary() + } + return false +} + +func New(l net.Listener) Mux { + return &mux{ + listener: l, + connBufLen: 1024, + doneCh: make(chan struct{}), + } +} + +type muxListener struct { + root net.Listener + connCh chan net.Conn + closed *atomic.AtomicBool +} + +func (l *muxListener) Accept() (net.Conn, error) { + if l.closed.Get() { + return nil, ErrListenerClosed + } + c, ok := <-l.connCh + if !ok || l.closed.Get() { + return nil, ErrListenerClosed + } + return c, nil +} + +// Close stops listening on address. +// Already Accepted connections are not closed. +func (l *muxListener) Close() error { + l.closed.Set(true) + return nil +} + +func (l *muxListener) Addr() net.Addr { + return l.root.Addr() +} + +func newMuxListener(root net.Listener, connBufLen int) *muxListener { + return &muxListener{ + root: root, + connCh: make(chan net.Conn, connBufLen), + closed: atomic.NewAtomicBool(false), + } +} + +type muxConn struct { + net.Conn + buf []byte + lastErr error +} + +func newMuxConn(c net.Conn, buf []byte, lastErr error) *muxConn { + return &muxConn{ + Conn: c, + buf: buf, + lastErr: lastErr, + } +} + +func (m *muxConn) Read(p []byte) (int, error) { + if m.buf != nil { + n := copy(p, m.buf) + if len(m.buf) == n { + putBuffer(m.buf) + m.buf = nil + } else { + m.buf = m.buf[n:] + } + return n, m.lastErr + } + return m.Conn.Read(p) +} diff --git a/mux/mux_test.go b/mux/mux_test.go new file mode 100644 index 0000000..5370a41 --- /dev/null +++ b/mux/mux_test.go @@ -0,0 +1,118 @@ +package mux + +import ( + "fmt" + "github.com/stretchr/testify/assert" + "io/ioutil" + "log" + "net" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestHTTP1(t *testing.T) { + a := assert.New(t) + path := "/test/" + method := "GET" + mockResData := []byte("948 res") + var responseData []byte + + rootListener := newLocalListener() + mux := New(rootListener) + httpListener := mux.Match(HTTP1()) + mux.OnError(func(err error) { + a.Fail("connection not matched by a http matcher") + }) + + go func() { + err := mux.Serve() + log.Println(err) + }() + + handler := func(writer http.ResponseWriter, request *http.Request) { + var err error + a.Equal(method, request.Method) + n, err := writer.Write(mockResData) + a.NoError(err) + a.Len(mockResData, n) + } + httpMux := http.NewServeMux() + httpMux.HandleFunc(path, handler) + httpServer := httptest.NewUnstartedServer(httpMux) + httpServer.Listener = httpListener + httpServer.Start() + + url := httpServer.URL + path + httpClient := httpServer.Client() + req, _ := http.NewRequest(method, url, nil) + res, err := httpClient.Do(req) + a.NoError(err) + if a.NotNil(res) { + a.Equal(200, res.StatusCode) + responseData, err = ioutil.ReadAll(res.Body) + } + + time.Sleep(10 * time.Millisecond) + a.Equal(mockResData, responseData) +} + +func TestAny(t *testing.T) { + a := assert.New(t) + mockReqData := []byte("1 somre") + requestData := make([]byte, len(mockReqData)) + + rootListener := newLocalListener() + mux := New(rootListener) + httpListener := mux.Match(HTTP1()) + tcpListener := mux.Match(Any()) + go func() { + err := mux.Serve() + log.Println(err) + }() + + handler := func(writer http.ResponseWriter, request *http.Request) { + a.Fail("matched http handler") + } + httpMux := http.NewServeMux() + httpMux.HandleFunc("/", handler) + httpServer := httptest.NewUnstartedServer(httpMux) + httpServer.Listener = httpListener + httpServer.Start() + + hadTcpConn := false + go func() { + for { + conn, err := tcpListener.Accept() + if hadTcpConn { + a.Fail("more than one tcp conn") + return + } + hadTcpConn = true + a.NoError(err) + _, err = conn.Read(requestData) + a.NoError(err) + a.Equal(mockReqData, requestData) + } + }() + + tcpAddr := tcpListener.Addr().String() + conn, err := net.Dial("tcp", tcpAddr) + a.NoError(err) + n, err := conn.Write(mockReqData) + a.Len(mockReqData, n) + a.NoError(err) + + time.Sleep(10 * time.Millisecond) + a.Equal(mockReqData, requestData) + a.True(hadTcpConn) +} + +func newLocalListener() net.Listener { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + panic(fmt.Sprintf("failed to listen on a port: %v", err)) + } + return l +} diff --git a/mux/pool.go b/mux/pool.go new file mode 100644 index 0000000..03bbcef --- /dev/null +++ b/mux/pool.go @@ -0,0 +1,22 @@ +package mux + +import ( + "sync" +) + +// could be increased if needed for new matchers +const bufferSize = 10 + +var pool sync.Pool + +func getBuffer() []byte { + b, ok := pool.Get().([]byte) + if !ok { + b = make([]byte, bufferSize) + } + return b +} + +func putBuffer(b []byte) { + pool.Put(b[:cap(b)]) +}