diff --git a/Gopkg.lock b/Gopkg.lock index 531a0c4fc71..5b8a0cb30f8 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -903,6 +903,7 @@ "google.golang.org/grpc/keepalive", "google.golang.org/grpc/metadata", "google.golang.org/grpc/peer", + "google.golang.org/grpc/stats", "google.golang.org/grpc/status", "gopkg.in/alecthomas/kingpin.v2", "gopkg.in/cheggaaa/pb.v1", diff --git a/core/comm/serverstatshandler.go b/core/comm/serverstatshandler.go new file mode 100644 index 00000000000..10ccf7be4f1 --- /dev/null +++ b/core/comm/serverstatshandler.go @@ -0,0 +1,38 @@ +/* +Copyright IBM Corp. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 +*/ + +package comm + +import ( + "context" + + "github.com/go-kit/kit/metrics" + "google.golang.org/grpc/stats" +) + +type ServerStatsHandler struct { + OpenConnCounter metrics.Counter + ClosedConnCounter metrics.Counter +} + +func (h *ServerStatsHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { + return ctx +} + +func (h *ServerStatsHandler) HandleRPC(ctx context.Context, s stats.RPCStats) { + switch s.(type) { + case *stats.Begin: + h.OpenConnCounter.Add(1) + case *stats.End: + h.ClosedConnCounter.Add(1) + } +} + +func (h *ServerStatsHandler) TagConn(ctx context.Context, info *stats.ConnTagInfo) context.Context { + return ctx +} + +func (h *ServerStatsHandler) HandleConn(ctx context.Context, s stats.ConnStats) {} diff --git a/core/comm/serverstatshandler_test.go b/core/comm/serverstatshandler_test.go new file mode 100644 index 00000000000..d88922ecc51 --- /dev/null +++ b/core/comm/serverstatshandler_test.go @@ -0,0 +1,37 @@ +/* +Copyright IBM Corp. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 +*/ + +package comm_test + +import ( + "context" + "testing" + + "github.com/hyperledger/fabric/common/metrics/metricsfakes" + "github.com/hyperledger/fabric/core/comm" + "github.com/stretchr/testify/assert" + "google.golang.org/grpc/stats" +) + +func TestConnectionCounters(t *testing.T) { + openConn := &metricsfakes.Counter{} + closedConn := &metricsfakes.Counter{} + sh := &comm.ServerStatsHandler{ + OpenConnCounter: openConn, + ClosedConnCounter: closedConn, + } + + for i := 1; i <= 10; i++ { + sh.HandleRPC(context.Background(), &stats.Begin{}) + } + assert.Equal(t, 10, openConn.AddCallCount()) + + for i := 1; i <= 5; i++ { + sh.HandleRPC(context.Background(), &stats.End{}) + } + assert.Equal(t, 5, closedConn.AddCallCount()) + +}