Defines the controller api metrics and registers them at controller startup (#1917)
Co-authored-by: Hugo Vieira <hugoamvieira@users.noreply.github.com>
This commit is contained in:
1 parent
1bb2c5983d
commit
3eb22b073a
16 files changed
+1128
-16
No files matched your search
@@ -26,6 +26,7 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/servers"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/common"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/health"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/internal/metric"
|
||||
"github.com/hashicorp/boundary/internal/session"
|
||||
"github.com/hashicorp/boundary/internal/target"
|
||||
"github.com/hashicorp/boundary/internal/types/scope"
|
||||
@@ -88,6 +89,7 @@ type Controller struct {
|
||||
}
|
||||
|
||||
func New(ctx context.Context, conf *Config) (*Controller, error) {
|
||||
metric.InitializeApiCollectors(conf.PrometheusRegisterer)
|
||||
c := &Controller{
|
||||
conf: conf,
|
||||
logger: conf.Logger.Named("controller"),
|
||||
|
||||
@@ -38,6 +38,7 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/sessions"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/targets"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/users"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/internal/metric"
|
||||
"github.com/hashicorp/go-cleanhttp"
|
||||
"github.com/hashicorp/go-secure-stdlib/listenerutil"
|
||||
"github.com/hashicorp/go-secure-stdlib/strutil"
|
||||
@@ -72,8 +73,12 @@ func (c *Controller) apiHandler(props HandlerProperties) (http.Handler, error) {
|
||||
callbackInterceptingHandler := wrapHandlerWithCallbackInterceptor(commonWrappedHandler, c)
|
||||
printablePathCheckHandler := cleanhttp.PrintablePathCheckHandler(callbackInterceptingHandler, nil)
|
||||
eventsHandler, err := common.WrapWithEventsHandler(printablePathCheckHandler, c.conf.Eventer, c.kms, props.ListenerConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metricsHandler := metric.InstrumentApiHandler(eventsHandler)
|
||||
|
||||
return eventsHandler, err
|
||||
return metricsHandler, nil
|
||||
}
|
||||
|
||||
// GetHealthHandler returns a gRPC Gateway mux that is registered against the
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
// Package metric provides functions to initialize the controller specific
|
||||
// collectors and hooks to measure metrics and update the relevant collectors.
|
||||
package metric
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/boundary/globals"
|
||||
"github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
grpcpb "google.golang.org/genproto/googleapis/api/annotations"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
"google.golang.org/protobuf/reflect/protoregistry"
|
||||
"google.golang.org/protobuf/types/descriptorpb"
|
||||
)
|
||||
|
||||
var (
|
||||
pathRegex map[*regexp.Regexp]string
|
||||
expectedPathsToMethods map[string][]string
|
||||
)
|
||||
|
||||
func init() {
|
||||
expectedPathsToMethods = apiPathsAndMethods()
|
||||
pathRegex = make(map[*regexp.Regexp]string)
|
||||
for p := range expectedPathsToMethods {
|
||||
pathRegex[buildRegexFromPath(p)] = p
|
||||
}
|
||||
}
|
||||
|
||||
// gatherPathInfo populates the provided map with the paths associated with
|
||||
// the provided HttpRule proto option as well as the path information contained
|
||||
// in any embedded AdditionalBindings in that HttpRule.
|
||||
func gatherPathInfo(rule *grpcpb.HttpRule, paths map[string][]string) {
|
||||
switch r := rule.GetPattern().(type) {
|
||||
case *grpcpb.HttpRule_Get:
|
||||
paths[r.Get] = append(paths[r.Get], http.MethodGet)
|
||||
case *grpcpb.HttpRule_Post:
|
||||
paths[r.Post] = append(paths[r.Post], http.MethodPost)
|
||||
case *grpcpb.HttpRule_Patch:
|
||||
paths[r.Patch] = append(paths[r.Patch], http.MethodPatch)
|
||||
case *grpcpb.HttpRule_Put:
|
||||
paths[r.Put] = append(paths[r.Put], http.MethodPut)
|
||||
case *grpcpb.HttpRule_Delete:
|
||||
paths[r.Delete] = append(paths[r.Delete], http.MethodDelete)
|
||||
default:
|
||||
panic("unknown rule of ")
|
||||
}
|
||||
for _, additional := range rule.AdditionalBindings {
|
||||
gatherPathInfo(additional, paths)
|
||||
}
|
||||
}
|
||||
|
||||
func gatherServicePathsAndMethods(fd protoreflect.FileDescriptor, paths map[string][]string) error {
|
||||
for j := 0; j < fd.Services().Len(); j++ {
|
||||
sd := fd.Services().Get(j)
|
||||
for i := 0; i < sd.Methods().Len(); i++ {
|
||||
r := sd.Methods().Get(i)
|
||||
opts := r.Options().(*descriptorpb.MethodOptions)
|
||||
httpRule := proto.GetExtension(opts, grpcpb.E_Http).(*grpcpb.HttpRule)
|
||||
if proto.Equal(httpRule, &grpcpb.HttpRule{}) || httpRule == nil {
|
||||
return fmt.Errorf("empty or no http rule found on service method %q", r.FullName())
|
||||
}
|
||||
gatherPathInfo(httpRule, paths)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// apiPathsAndMethods provides the pathing information for all services
|
||||
// registered to the controller API. This does not include any paths that are
|
||||
// defined outside of the protobufs such as anything using the OPTION method
|
||||
// or any other paths registered like the dev UI passthrough path.
|
||||
func apiPathsAndMethods() map[string][]string {
|
||||
paths := make(map[string][]string)
|
||||
protoregistry.GlobalFiles.RangeFilesByPackage(
|
||||
services.File_controller_api_services_v1_user_service_proto.Package(),
|
||||
func(f protoreflect.FileDescriptor) bool {
|
||||
if err := gatherServicePathsAndMethods(f, paths); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return true
|
||||
})
|
||||
return paths
|
||||
}
|
||||
|
||||
func buildRegexFromPath(p string) *regexp.Regexp {
|
||||
// a public id in boundary consists of a some prefix, an underscore and
|
||||
// at least 10 alphanumerical characters like "h_1234567890".
|
||||
const idRegexp = "[[:alnum:]]{1,}_[[:alnum:]]{10,}"
|
||||
|
||||
// Replace any tag in the form of {id} or {auth_method_id} with the above
|
||||
// regex so we can match paths to that when measuring requests.
|
||||
pWithId := string(regexp.MustCompile("\\{[^\\}]*id\\}").ReplaceAll([]byte(p), []byte(idRegexp)))
|
||||
|
||||
// Escape everything except for our id regexp.
|
||||
var seg []string
|
||||
for _, s := range strings.Split(pWithId, idRegexp) {
|
||||
seg = append(seg, regexp.QuoteMeta(s))
|
||||
}
|
||||
escapedPathRegex := strings.Join(seg, idRegexp)
|
||||
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)
|
||||
|
||||
// httpRequestLatency collects measurements of how long it takes
|
||||
// the boundary system to reply to a request to the controller api
|
||||
// from the time that boundary received the request.
|
||||
httpRequestLatency prometheus.ObserverVec = prometheus.NewHistogramVec(
|
||||
prometheus.HistogramOpts{
|
||||
Namespace: globals.MetricNamespace,
|
||||
Subsystem: apiSubSystem,
|
||||
Name: "http_request_duration_seconds",
|
||||
Help: "Histogram of latencies for HTTP requests.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
},
|
||||
[]string{labelHttpCode, labelHttpPath, labelHttpMethod},
|
||||
)
|
||||
|
||||
// httpRequestSize collections measurements of how large each request
|
||||
// to the boundary controller api is.
|
||||
httpRequestSize prometheus.ObserverVec = prometheus.NewHistogramVec(
|
||||
prometheus.HistogramOpts{
|
||||
Namespace: globals.MetricNamespace,
|
||||
Subsystem: apiSubSystem,
|
||||
Name: "http_request_size_bytes",
|
||||
Help: "Histogram of request sizes for HTTP requests.",
|
||||
Buckets: msgSizeBuckets,
|
||||
},
|
||||
[]string{labelHttpCode, labelHttpPath, labelHttpMethod},
|
||||
)
|
||||
|
||||
// httpRequestSize collections measurements of how large each response
|
||||
// from the boundary controller api is.
|
||||
httpResponseSize prometheus.ObserverVec = prometheus.NewHistogramVec(
|
||||
prometheus.HistogramOpts{
|
||||
Namespace: globals.MetricNamespace,
|
||||
Subsystem: apiSubSystem,
|
||||
Name: "http_response_size_bytes",
|
||||
Help: "Histogram of response sizes for HTTP responses.",
|
||||
Buckets: msgSizeBuckets,
|
||||
},
|
||||
[]string{labelHttpCode, labelHttpPath, labelHttpMethod},
|
||||
)
|
||||
)
|
||||
|
||||
var universalStatusCodes = []int{
|
||||
http.StatusUnauthorized,
|
||||
http.StatusForbidden,
|
||||
http.StatusNotFound,
|
||||
http.StatusMethodNotAllowed,
|
||||
http.StatusBadRequest,
|
||||
|
||||
http.StatusInternalServerError,
|
||||
http.StatusGatewayTimeout,
|
||||
}
|
||||
|
||||
// Codes which are only currently used in the authentication flow
|
||||
var authenticationStatusCodes = []int{
|
||||
http.StatusAccepted,
|
||||
http.StatusFound,
|
||||
}
|
||||
|
||||
var expectedStatusCodesPerMethod = map[string][]int{
|
||||
http.MethodGet: append(universalStatusCodes,
|
||||
http.StatusOK),
|
||||
http.MethodPost: append(universalStatusCodes,
|
||||
append(authenticationStatusCodes, http.StatusOK)...),
|
||||
http.MethodPatch: append(universalStatusCodes,
|
||||
http.StatusOK),
|
||||
|
||||
// delete methods always returns no content instead of a StatusOK
|
||||
http.MethodDelete: append(universalStatusCodes,
|
||||
http.StatusNoContent),
|
||||
|
||||
http.MethodOptions: {
|
||||
http.StatusNoContent,
|
||||
http.StatusForbidden,
|
||||
http.StatusMethodNotAllowed,
|
||||
},
|
||||
}
|
||||
|
||||
// pathLabel maps the requested path the the label value recorded for metrics
|
||||
func pathLabel(incomingPath string) string {
|
||||
if incomingPath == "" || incomingPath[0] != '/' {
|
||||
incomingPath = fmt.Sprintf("/%s", incomingPath)
|
||||
}
|
||||
incomingPath = path.Clean(incomingPath)
|
||||
|
||||
for r, ep := range pathRegex {
|
||||
if r.Match([]byte(incomingPath)) {
|
||||
return ep
|
||||
}
|
||||
}
|
||||
return invalidPathValue
|
||||
}
|
||||
|
||||
// InstrumentApiHandler provides a handler which measures api
|
||||
// 1. The response size
|
||||
// 2. The request size
|
||||
// 3. The request latency
|
||||
// and attaches status code, method, and path labels for each of these
|
||||
// measurements.
|
||||
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),
|
||||
}
|
||||
promhttp.InstrumentHandlerDuration(
|
||||
httpRequestLatency.MustCurryWith(l),
|
||||
promhttp.InstrumentHandlerRequestSize(
|
||||
httpResponseSize.MustCurryWith(l),
|
||||
promhttp.InstrumentHandlerResponseSize(
|
||||
httpResponseSize.MustCurryWith(l),
|
||||
wrapped,
|
||||
),
|
||||
),
|
||||
).ServeHTTP(rw, req)
|
||||
})
|
||||
}
|
||||
|
||||
// InitializeApiCollectors registers the api collectors to the default
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package metric
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/gen/testing/protooptions"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBuildRegexFromPath(t *testing.T) {
|
||||
cases := []struct {
|
||||
path string
|
||||
match []string
|
||||
dont []string
|
||||
}{
|
||||
{
|
||||
path: "/v1/pathsomething/{id}:test-thing",
|
||||
match: []string{
|
||||
"/v1/pathsomething/a4s_aKsdFh723018djsa:test-thing",
|
||||
"/v1/pathsomething/h_1234567890:test-thing",
|
||||
},
|
||||
dont: []string{
|
||||
"/v1/pathsomething/{id}:test-thing",
|
||||
"/v1/pathsomething/{any_old_id}:test-thing",
|
||||
"/v1/pathsomething:test-thing",
|
||||
"/v1/pathsomething/not-an-id:test-thing",
|
||||
"/v1/pathsomething/a4s_aKsdFh723018djsa:other-thing",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "/v1/pathsomething/{auth_method_id}:authenticate",
|
||||
match: []string{
|
||||
"/v1/pathsomething/a4s_aKsdFh723018djsa:authenticate",
|
||||
"/v1/pathsomething/am_1234567890:authenticate",
|
||||
},
|
||||
dont: []string{
|
||||
"/v1/pathsomething/{id}:authenticate",
|
||||
"/v1/pathsomething/{auth_method}:authenticate",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "/v1/pathsomething/{non_id_tag}:test",
|
||||
match: []string{
|
||||
"/v1/pathsomething/{non_id_tag}:test",
|
||||
},
|
||||
dont: []string{
|
||||
"/v1/pathsomething/h_1234567890:test",
|
||||
"/v1/pathsomething/.*:test",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "/v1/pathsomething/a?",
|
||||
match: []string{
|
||||
"/v1/pathsomething/a?",
|
||||
},
|
||||
dont: []string{
|
||||
"/v1/pathsomething/",
|
||||
"/v1/pathsomething/a",
|
||||
"/v1/pathsomething/aa",
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.path, func(t *testing.T) {
|
||||
r := buildRegexFromPath(tc.path)
|
||||
for _, m := range tc.match {
|
||||
assert.True(t, r.Match([]byte(m)))
|
||||
}
|
||||
for _, d := range tc.dont {
|
||||
assert.False(t, r.Match([]byte(d)))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathLabel(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
in: "/v1/accounts",
|
||||
want: "/v1/accounts",
|
||||
},
|
||||
{
|
||||
in: "v1/accounts",
|
||||
want: "/v1/accounts",
|
||||
},
|
||||
{
|
||||
in: "/v1/hosts",
|
||||
want: "/v1/hosts",
|
||||
},
|
||||
{
|
||||
in: "/v2/accounts",
|
||||
want: "invalid",
|
||||
},
|
||||
{
|
||||
in: "/v1/accounts/a_1234567890",
|
||||
want: "/v1/accounts/{id}",
|
||||
},
|
||||
{
|
||||
in: "v1/accounts/a_1234567890",
|
||||
want: "/v1/accounts/{id}",
|
||||
},
|
||||
{
|
||||
in: "/v1/accounts/a_1234567890:set-password",
|
||||
want: "/v1/accounts/{id}:set-password",
|
||||
},
|
||||
{
|
||||
in: "v1/accounts/a_1234567890:set-password",
|
||||
want: "/v1/accounts/{id}:set-password",
|
||||
},
|
||||
{
|
||||
// mistype the custom action
|
||||
in: "/v1/accounts/a_1234567890:set-passwords",
|
||||
want: "invalid",
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.in, func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, pathLabel(tc.in))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServicePathsAndMethods(t *testing.T) {
|
||||
paths := make(map[string][]string)
|
||||
require.NoError(t, gatherServicePathsAndMethods(protooptions.File_testing_options_v1_service_proto, paths))
|
||||
assert.Equal(t, map[string][]string{
|
||||
"/v1/test/{id}": {http.MethodGet},
|
||||
"/v2/test": {http.MethodGet},
|
||||
}, paths)
|
||||
}
|
||||
@@ -10,8 +10,6 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/session"
|
||||
|
||||
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
|
||||
"github.com/hashicorp/boundary/api"
|
||||
"github.com/hashicorp/boundary/api/authmethods"
|
||||
@@ -27,10 +25,12 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"github.com/hashicorp/boundary/internal/observability/event"
|
||||
"github.com/hashicorp/boundary/internal/servers"
|
||||
"github.com/hashicorp/boundary/internal/session"
|
||||
"github.com/hashicorp/go-hclog"
|
||||
wrapping "github.com/hashicorp/go-kms-wrapping/v2"
|
||||
"github.com/hashicorp/go-secure-stdlib/base62"
|
||||
"github.com/hashicorp/go-secure-stdlib/strutil"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
@@ -393,6 +393,10 @@ type TestControllerOpts struct {
|
||||
// The logger to use, or one will be created
|
||||
Logger hclog.Logger
|
||||
|
||||
// The registerer to use for registering all the collectors. Nil means
|
||||
// no metrics are registered.
|
||||
PrometheusRegisterer prometheus.Registerer
|
||||
|
||||
// A cluster address for overriding the advertised controller listener
|
||||
// (overrides address provided in config, if any)
|
||||
PublicClusterAddr string
|
||||
@@ -519,6 +523,7 @@ func TestControllerConfig(t *testing.T, ctx context.Context, tc *TestController,
|
||||
})
|
||||
}
|
||||
|
||||
tc.b.PrometheusRegisterer = opts.PrometheusRegisterer
|
||||
if opts.Config.Controller == nil {
|
||||
opts.Config.Controller = new(config.Controller)
|
||||
}
|
||||
|
||||
@@ -10,4 +10,11 @@ func Test_TestController(t *testing.T) {
|
||||
tc := NewTestController(t, nil)
|
||||
defer tc.Shutdown()
|
||||
})
|
||||
t.Run("start 2 controllers", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
tc1 := NewTestController(t, nil)
|
||||
tc2 := NewTestController(t, nil)
|
||||
defer tc1.Shutdown()
|
||||
defer tc2.Shutdown()
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user