feat(workers): Add metrics for worker server-side grpc connections, refactor repeated code into common location (#2367)

* feat(workers): added latencies histogram for server side multihop workers

* refactor(daemon): combine common grpc metric functions into daemon/internal/metric

Co-authored-by: Todd <github@quaddi.com>
This commit is contained in:
HaotianandTodd authored and GitHub committed 2022-09-06 13:40:52 -07:00
1 parent 25f7caa3bf
commit 5c715478e4
12 files changed
+473 -388

No files matched your search

@@ -7,10 +7,10 @@ import (
"net/http"
"path"
"regexp"
"strconv"
"strings"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/daemon/internal/metric"
"github.com/hashicorp/boundary/internal/gen/controller/api/services"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
@@ -26,6 +26,11 @@ var (
expectedPathsToMethods map[string][]string
)
const (
invalidPathValue = "invalid"
apiSubSystem = "controller_api"
)
func init() {
expectedPathsToMethods = apiPathsAndMethods()
pathRegex = make(map[*regexp.Regexp]string)
@@ -109,15 +114,6 @@ func buildRegexFromPath(p string) *regexp.Regexp {
return regexp.MustCompile(fmt.Sprintf("^%s$", escapedPathRegex))
}
const (
invalidPathValue = "invalid"
labelHttpCode = "code"
labelHttpPath = "path"
labelHttpMethod = "method"
apiSubSystem = "controller_api"
)
var (
// 100 bytes, 1kb, 10kb, 100kb, 1mb, 10mb, 100mb, 1gb
msgSizeBuckets = prometheus.ExponentialBuckets(100, 10, 8)
@@ -133,7 +129,7 @@ var (
Help: "Histogram of latencies for HTTP requests.",
Buckets: prometheus.DefBuckets,
},
[]string{labelHttpCode, labelHttpPath, labelHttpMethod},
metric.ListHttpLabels,
)
// httpRequestSize collections measurements of how large each request
@@ -146,7 +142,7 @@ var (
Help: "Histogram of request sizes for HTTP requests.",
Buckets: msgSizeBuckets,
},
[]string{labelHttpCode, labelHttpPath, labelHttpMethod},
metric.ListHttpLabels,
)
// httpRequestSize collections measurements of how large each response
@@ -159,7 +155,7 @@ var (
Help: "Histogram of response sizes for HTTP responses.",
Buckets: msgSizeBuckets,
},
[]string{labelHttpCode, labelHttpPath, labelHttpMethod},
metric.ListHttpLabels,
)
)
@@ -223,7 +219,7 @@ func pathLabel(incomingPath string) string {
func InstrumentApiHandler(wrapped http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
l := prometheus.Labels{
labelHttpPath: pathLabel(req.URL.Path),
metric.LabelHttpPath: pathLabel(req.URL.Path),
}
promhttp.InstrumentHandlerDuration(
httpRequestLatency.MustCurryWith(l),
@@ -242,31 +238,7 @@ func InstrumentApiHandler(wrapped http.Handler) http.Handler {
// prometheus register and initializes them to 0 for all possible label
// combinations.
func InitializeApiCollectors(r prometheus.Registerer) {
if r == nil {
return
}
r.MustRegister(httpResponseSize, httpRequestSize, httpRequestLatency)
for p, methods := range expectedPathsToMethods {
for _, m := range methods {
for _, sc := range expectedStatusCodesPerMethod[m] {
l := prometheus.Labels{labelHttpCode: strconv.Itoa(sc), labelHttpPath: p, labelHttpMethod: strings.ToLower(m)}
httpResponseSize.With(l)
httpRequestSize.With(l)
httpRequestLatency.With(l)
}
}
}
// When an invalid path is found, any method is possible both we expect
// an error response.
p := invalidPathValue
for m := range expectedStatusCodesPerMethod {
for _, sc := range []int{http.StatusNotFound, http.StatusMethodNotAllowed} {
l := prometheus.Labels{labelHttpCode: strconv.Itoa(sc), labelHttpPath: p, labelHttpMethod: strings.ToLower(m)}
httpResponseSize.With(l)
httpRequestSize.With(l)
httpRequestLatency.With(l)
}
for _, v := range []prometheus.ObserverVec{httpRequestLatency, httpRequestSize, httpResponseSize} {
metric.InitializeApiCollectors(r, v, expectedPathsToMethods, expectedStatusCodesPerMethod)
}
}
@@ -2,28 +2,27 @@ package metric
import (
"context"
"strings"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/errors"
metric "github.com/hashicorp/boundary/internal/daemon/internal/metric"
"github.com/prometheus/client_golang/prometheus"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/stats"
"google.golang.org/grpc/status"
)
const (
labelGRpcCode = "grpc_code"
labelGRpcService = "grpc_service"
labelGRpcMethod = "grpc_method"
clusterSubSystem = "controller_cluster"
)
// gRpcRequestLatency collects measurements of how long it takes
// Because we use grpc's stats.Handler to track close-to-the-wire server-side communication over grpc,
// there is no easy way to measure request and response size as we are recording latency. Thus we only
// track the request latency for server-side grpc connections.
// grpcRequestLatency collects measurements of how long it takes
// the boundary system to reply to a request to the controller cluster
// from the time that boundary received the request.
var gRpcRequestLatency prometheus.ObserverVec = prometheus.NewHistogramVec(
var grpcRequestLatency prometheus.ObserverVec = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: globals.MetricNamespace,
Subsystem: clusterSubSystem,
@@ -31,69 +30,12 @@ var gRpcRequestLatency prometheus.ObserverVec = prometheus.NewHistogramVec(
Help: "Histogram of latencies for gRPC requests.",
Buckets: prometheus.DefBuckets,
},
[]string{labelGRpcCode, labelGRpcService, labelGRpcMethod},
metric.ListGrpcLabels,
)
// statusFromError retrieves the *status.Status from the provided error. It'll
// attempt to unwrap the *status.Error, which is something status.FromError
// does not do.
func statusFromError(err error) *status.Status {
if s, ok := status.FromError(err); ok {
return s
}
type gRPCStatus interface {
GRPCStatus() *status.Status
}
var unwrappedStatus gRPCStatus
if ok := errors.As(err, &unwrappedStatus); ok {
return unwrappedStatus.GRPCStatus()
}
return status.New(codes.Unknown, "Unknown Code")
}
func splitMethodName(fullMethodName string) (string, string) {
fullMethodName = strings.TrimPrefix(fullMethodName, "/") // remove leading slash
if i := strings.Index(fullMethodName, "/"); i >= 0 {
return fullMethodName[:i], fullMethodName[i+1:]
}
return "unknown", "unknown"
}
type metricMethodNameContextKey struct{}
type statsHandler struct{}
func (sh statsHandler) TagRPC(ctx context.Context, i *stats.RPCTagInfo) context.Context {
return context.WithValue(ctx, metricMethodNameContextKey{}, i.FullMethodName)
}
func (sh statsHandler) TagConn(ctx context.Context, _ *stats.ConnTagInfo) context.Context {
return ctx
}
func (sh statsHandler) HandleConn(context.Context, stats.ConnStats) {
}
func (sh statsHandler) HandleRPC(ctx context.Context, s stats.RPCStats) {
switch v := s.(type) {
case *stats.End:
// Accept the ok, but ignore it. This code doesn't need to panic
// and if "fullName" is an empty string splitMethodName will
// set service and method to "unknown".
fullName, _ := ctx.Value(metricMethodNameContextKey{}).(string)
service, method := splitMethodName(fullName)
l := prometheus.Labels{
labelGRpcMethod: method,
labelGRpcService: service,
labelGRpcCode: statusFromError(v.Error).Code().String(),
}
gRpcRequestLatency.With(l).Observe(v.EndTime.Sub(v.BeginTime).Seconds())
}
}
var allCodes = []codes.Code{
// All the codes expected to be returned by boundary or the grpc framework to
// requests to the cluster server.
var expectedGrpcCodes = []codes.Code{
codes.OK, codes.InvalidArgument, codes.PermissionDenied,
codes.FailedPrecondition,
@@ -105,29 +47,13 @@ var allCodes = []codes.Code{
// InstrumentClusterStatsHandler returns a gRPC stats.Handler which observes
// cluster specific metrics. Use with the cluster gRPC server.
func InstrumentClusterStatsHandler() statsHandler {
return statsHandler{}
func InstrumentClusterStatsHandler(ctx context.Context) (stats.Handler, error) {
return metric.NewStatsHandler(ctx, grpcRequestLatency)
}
// InitializeClusterCollectors registers the cluster metrics to the default
// prometheus register and initializes them to 0 for all possible label
// combinations.
func InitializeClusterCollectors(r prometheus.Registerer, server *grpc.Server) {
if r == nil {
return
}
r.MustRegister(gRpcRequestLatency)
for serviceName, info := range server.GetServiceInfo() {
for _, mInfo := range info.Methods {
for _, c := range allCodes {
l := prometheus.Labels{
labelGRpcMethod: mInfo.Name,
labelGRpcService: serviceName,
labelGRpcCode: c.String(),
}
gRpcRequestLatency.With(l)
}
}
}
metric.InitializeGrpcCollectorsFromServer(r, grpcRequestLatency, server, expectedGrpcCodes)
}
@@ -1,169 +0,0 @@
package metric
import (
"context"
"fmt"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/stats"
"google.golang.org/grpc/status"
)
func TestStatsHandler(t *testing.T) {
bkpLatency := gRpcRequestLatency
defer func() {
gRpcRequestLatency = bkpLatency
}()
handler := InstrumentClusterStatsHandler()
cases := []struct {
name string
stats []stats.RPCStats
fullMethodName string
wantedLabels prometheus.Labels
wantedLatency float64
}{
{
name: "basic",
fullMethodName: "/some.service.path/method",
stats: []stats.RPCStats{
&stats.End{
BeginTime: time.Time{}.Add(time.Second),
EndTime: time.Time{}.Add(5 * time.Second),
},
},
wantedLabels: map[string]string{
labelGRpcCode: "OK",
labelGRpcMethod: "method",
labelGRpcService: "some.service.path",
},
wantedLatency: (4 * time.Second).Seconds(),
},
{
name: "ignored stats",
fullMethodName: "/some.service.path/method",
stats: []stats.RPCStats{
&stats.Begin{
BeginTime: time.Time{},
IsTransparentRetryAttempt: true,
},
&stats.InPayload{
Length: 5,
WireLength: 15,
RecvTime: time.Time{}.Add(time.Second).Add(500 * time.Millisecond),
},
&stats.OutPayload{
Length: 5,
WireLength: 15,
SentTime: time.Time{}.Add(2 * time.Second),
},
&stats.End{
BeginTime: time.Time{}.Add(time.Second),
EndTime: time.Time{}.Add(5 * time.Second),
},
},
wantedLabels: map[string]string{
labelGRpcCode: "OK",
labelGRpcMethod: "method",
labelGRpcService: "some.service.path",
},
wantedLatency: (4 * time.Second).Seconds(),
},
{
name: "bad method name",
fullMethodName: "",
stats: []stats.RPCStats{
&stats.End{
BeginTime: time.Time{}.Add(time.Second),
EndTime: time.Time{}.Add(5 * time.Second),
},
},
wantedLabels: map[string]string{
labelGRpcCode: "OK",
labelGRpcMethod: "unknown",
labelGRpcService: "unknown",
},
wantedLatency: (4 * time.Second).Seconds(),
},
{
name: "error code",
fullMethodName: "/some.service.path/method",
stats: []stats.RPCStats{
&stats.End{
BeginTime: time.Time{}.Add(time.Second),
EndTime: time.Time{}.Add(5 * time.Second),
Error: status.Error(codes.Canceled, "test"),
},
},
wantedLabels: map[string]string{
labelGRpcCode: "Canceled",
labelGRpcMethod: "method",
labelGRpcService: "some.service.path",
},
wantedLatency: (4 * time.Second).Seconds(),
},
{
name: "wrapped error",
fullMethodName: "/some.service.path/method",
stats: []stats.RPCStats{
&stats.End{
BeginTime: time.Time{}.Add(time.Second),
EndTime: time.Time{}.Add(5 * time.Second),
Error: fmt.Errorf("%w", status.Error(codes.InvalidArgument, "test")),
},
},
wantedLabels: map[string]string{
labelGRpcCode: "InvalidArgument",
labelGRpcMethod: "method",
labelGRpcService: "some.service.path",
},
wantedLatency: (4 * time.Second).Seconds(),
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
testableLatency := &testableObserverVec{}
gRpcRequestLatency = testableLatency
ctx := context.Background()
ctx = handler.TagRPC(ctx, &stats.RPCTagInfo{
FullMethodName: tc.fullMethodName,
})
for _, i := range tc.stats {
handler.HandleRPC(ctx, i)
}
assert.Len(t, testableLatency.observations, 1)
assert.Equal(t, testableLatency.observations[0].observation, tc.wantedLatency)
assert.Equal(t, testableLatency.observations[0].labels, tc.wantedLabels)
})
}
}
// testableObserverVec allows us to assert which observations are being made
// with which labels.
type testableObserverVec struct {
observations []*testableObserver
prometheus.ObserverVec
}
func (v *testableObserverVec) With(l prometheus.Labels) prometheus.Observer {
ret := &testableObserver{labels: l}
v.observations = append(v.observations, ret)
return ret
}
type testableObserver struct {
labels prometheus.Labels
observation float64
}
func (o *testableObserver) Observe(f float64) {
o.observation = f
}