Merge pull request #54098 from renovate-bot/renovate/github.com-moby-swarmkit-v2-digest

fix(deps): update github.com/moby/swarmkit/v2 digest to 49925db
This commit is contained in:
Sebastiaan van Stijn authored and GitHub committed 2026-11-03 09:23:47 +01:00
commit b1bf12766e
49 files changed
+3968 -1315

No files matched your search

+3 -2
View File
@@ -77,7 +77,7 @@ require (
github.com/moby/profiles/apparmor v0.3.0
github.com/moby/profiles/seccomp v0.3.0
github.com/moby/pubsub v1.0.0
github.com/moby/swarmkit/v2 v2.1.3-0.20261016144904-5d8dbdc21997
github.com/moby/swarmkit/v2 v2.1.3-0.20261102175146-49925db4331f
github.com/moby/sys/atomicwriter v0.1.0
github.com/moby/sys/mount v0.3.5
github.com/moby/sys/mountinfo v0.7.3
@@ -216,7 +216,8 @@ require (
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.23 // indirect
github.com/googleapis/gax-go/v2 v2.27.0 // indirect
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect
github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.1 // indirect
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
+6 -4
View File
@@ -358,8 +358,10 @@ github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI=
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0/go.mod h1:g5qyo/la0ALbONm6Vbp88Yd8NsDy6rZz+RcrMPxvld8=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.1 h1:E4CBXV5a/63B3ugXigjU28gr4HHM/BuMa1DtOYWhEz8=
github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.1/go.mod h1:4c5LkgQnrWyJl9pvs2+nPRS12n3g/93FAQg8IzhEgnY=
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 h1:B+8ClL/kCQkRiU82d9xajRPKYMrB7E0MbtzWVi1K4ns=
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3/go.mod h1:NbCUVmiS4foBGBHOYlCT25+YmGpJ32dZPi75pGEUpj4=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0 h1:Bd7KaOxzULLxtZ/K5s1aLbWhR0+5RToO65TXHsf3bqQ=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0/go.mod h1:nN7ts3dFXKtCZWc//yfkpcQNKJABg16/uDVAZpLDalo=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
@@ -489,8 +491,8 @@ github.com/moby/profiles/seccomp v0.3.0 h1:1vJ94fIWXz206DLWq7ddPD6qLP82N7351JI/9
github.com/moby/profiles/seccomp v0.3.0/go.mod h1:H3JkVP4MWq+Q87sSWRUEdiZvK52WErUbcxr+mJHKVoM=
github.com/moby/pubsub v1.0.0 h1:jkp/imWsmJz2f6LyFsk7EkVeN2HxR/HTTOY8kHrsxfA=
github.com/moby/pubsub v1.0.0/go.mod h1:bXSO+3h5MNXXCaEG+6/NlAIk7MMZbySZlnB+cUQhKKc=
github.com/moby/swarmkit/v2 v2.1.3-0.20261016144904-5d8dbdc21997 h1:yiMG+P8CPG92oGjHjirVO6cURT8pkdEAumEMlYS5gB8=
github.com/moby/swarmkit/v2 v2.1.3-0.20261016144904-5d8dbdc21997/go.mod h1:do/2I3HPSCc87UA8pgbhCSlPf0/3tRSQVKSpBUS/pO8=
github.com/moby/swarmkit/v2 v2.1.3-0.20261102175146-49925db4331f h1:9aNKBbp9jQCn57EtaEjdVdu+qfjS5oJwv/1LMIy+IWo=
github.com/moby/swarmkit/v2 v2.1.3-0.20261102175146-49925db4331f/go.mod h1:KhkxT93Hm4wHoNUPJ4JRD384pS7OODFGzJWoDRj9bLE=
github.com/moby/sys/atomicwriter v0.1.0 h1:kw5D/EqkBwsBFi0ss9v1VG3wIkVhzGvLklJ+w3A14Sw=
github.com/moby/sys/atomicwriter v0.1.0/go.mod h1:Ul8oqv2ZMNHOceF643P6FKPXeCmYtlQMvpizfsSoaWs=
github.com/moby/sys/mount v0.3.5 h1:eS3fsZTjHaBihwjp4/+5Z3jxqLXYsbwxqpVSfFv3M00=
@@ -0,0 +1,139 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
package prometheus
import (
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors"
"github.com/prometheus/client_golang/prometheus"
"google.golang.org/grpc"
)
// ClientMetrics represents a collection of metrics to be registered on a
// Prometheus metrics registry for a gRPC client.
type ClientMetrics struct {
clientStartedCounter *prometheus.CounterVec
clientHandledCounter *prometheus.CounterVec
clientStreamMsgReceived *prometheus.CounterVec
clientStreamMsgSent *prometheus.CounterVec
// clientHandledHistogram can be nil
clientHandledHistogram *prometheus.HistogramVec
// clientStreamRecvHistogram can be nil
clientStreamRecvHistogram *prometheus.HistogramVec
// clientStreamSendHistogram can be nil
clientStreamSendHistogram *prometheus.HistogramVec
// contextLabelNames stores the names of context labels
contextLabelNames []string
}
// NewClientMetrics returns a new ClientMetrics object.
// NOTE: Remember to register ClientMetrics object using prometheus registry
// e.g. prometheus.MustRegister(myClientMetrics).
func NewClientMetrics(opts ...ClientMetricsOption) *ClientMetrics {
config := &clientMetricsConfig{
clientHandledHistogramFn: func() *prometheus.HistogramVec { return nil },
clientStreamRecvHistogramFn: func() *prometheus.HistogramVec { return nil },
clientStreamSendHistogramFn: func() *prometheus.HistogramVec { return nil },
}
config.apply(opts)
// Build label names by combining default labels with context labels
defaultLabels := []string{"grpc_type", "grpc_service", "grpc_method"}
defaultLabelsWithCode := []string{"grpc_type", "grpc_service", "grpc_method", "grpc_code"}
startedLabels := append(defaultLabels, config.contextLabels...)
handledLabels := append(defaultLabelsWithCode, config.contextLabels...)
streamLabels := append(defaultLabels, config.contextLabels...)
return &ClientMetrics{
clientStartedCounter: prometheus.NewCounterVec(
config.counterOpts.apply(prometheus.CounterOpts{
Name: "grpc_client_started_total",
Help: "Total number of RPCs started on the client.",
}), startedLabels,
),
clientHandledCounter: prometheus.NewCounterVec(
config.counterOpts.apply(prometheus.CounterOpts{
Name: "grpc_client_handled_total",
Help: "Total number of RPCs completed by the client, regardless of success or failure.",
}), handledLabels,
),
clientStreamMsgReceived: prometheus.NewCounterVec(
config.counterOpts.apply(prometheus.CounterOpts{
Name: "grpc_client_msg_received_total",
Help: "Total number of RPC stream messages received by the client.",
}), streamLabels,
),
clientStreamMsgSent: prometheus.NewCounterVec(
config.counterOpts.apply(prometheus.CounterOpts{
Name: "grpc_client_msg_sent_total",
Help: "Total number of gRPC stream messages sent by the client.",
}), streamLabels,
),
clientHandledHistogram: config.clientHandledHistogramFn(),
clientStreamRecvHistogram: config.clientStreamRecvHistogramFn(),
clientStreamSendHistogram: config.clientStreamSendHistogramFn(),
contextLabelNames: config.contextLabels,
}
}
// Describe sends the super-set of all possible descriptors of metrics
// collected by this Collector to the provided channel and returns once
// the last descriptor has been sent.
func (m *ClientMetrics) Describe(ch chan<- *prometheus.Desc) {
m.clientStartedCounter.Describe(ch)
m.clientHandledCounter.Describe(ch)
m.clientStreamMsgReceived.Describe(ch)
m.clientStreamMsgSent.Describe(ch)
if m.clientHandledHistogram != nil {
m.clientHandledHistogram.Describe(ch)
}
if m.clientStreamRecvHistogram != nil {
m.clientStreamRecvHistogram.Describe(ch)
}
if m.clientStreamSendHistogram != nil {
m.clientStreamSendHistogram.Describe(ch)
}
}
// Collect is called by the Prometheus registry when collecting
// metrics. The implementation sends each collected metric via the
// provided channel and returns once the last metric has been sent.
func (m *ClientMetrics) Collect(ch chan<- prometheus.Metric) {
m.clientStartedCounter.Collect(ch)
m.clientHandledCounter.Collect(ch)
m.clientStreamMsgReceived.Collect(ch)
m.clientStreamMsgSent.Collect(ch)
if m.clientHandledHistogram != nil {
m.clientHandledHistogram.Collect(ch)
}
if m.clientStreamRecvHistogram != nil {
m.clientStreamRecvHistogram.Collect(ch)
}
if m.clientStreamSendHistogram != nil {
m.clientStreamSendHistogram.Collect(ch)
}
}
// UnaryClientInterceptor is a gRPC client-side interceptor that provides Prometheus monitoring for Unary RPCs.
func (m *ClientMetrics) UnaryClientInterceptor(opts ...Option) grpc.UnaryClientInterceptor {
return interceptors.UnaryClientInterceptor(&reportable{
opts: opts,
clientMetrics: m,
})
}
// StreamClientInterceptor is a gRPC client-side interceptor that provides Prometheus monitoring for Streaming RPCs.
func (m *ClientMetrics) StreamClientInterceptor(opts ...Option) grpc.StreamClientInterceptor {
return interceptors.StreamClientInterceptor(&reportable{
opts: opts,
clientMetrics: m,
})
}
@@ -0,0 +1,103 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
package prometheus
import (
"github.com/prometheus/client_golang/prometheus"
)
type clientMetricsConfig struct {
counterOpts counterOptions
// clientHandledHistogramFn can be nil.
clientHandledHistogramFn func() *prometheus.HistogramVec
// clientStreamRecvHistogramFn can be nil.
clientStreamRecvHistogramFn func() *prometheus.HistogramVec
// clientStreamSendHistogramFn can be nil.
clientStreamSendHistogramFn func() *prometheus.HistogramVec
// contextLabels defines the names of dynamic labels to be extracted from context
contextLabels []string
}
type ClientMetricsOption func(*clientMetricsConfig)
func (c *clientMetricsConfig) apply(opts []ClientMetricsOption) {
for _, o := range opts {
o(c)
}
}
func WithClientCounterOptions(opts ...CounterOption) ClientMetricsOption {
return func(o *clientMetricsConfig) {
o.counterOpts = opts
}
}
// WithClientHandlingTimeHistogram turns on recording of handling time of RPCs.
// Histogram metrics can be very expensive for Prometheus to retain and query.
func WithClientHandlingTimeHistogram(opts ...HistogramOption) ClientMetricsOption {
return func(o *clientMetricsConfig) {
o.clientHandledHistogramFn = func() *prometheus.HistogramVec {
defaultLabels := []string{"grpc_type", "grpc_service", "grpc_method"}
allLabels := append(defaultLabels, o.contextLabels...)
return prometheus.NewHistogramVec(
histogramOptions(opts).apply(&prometheus.HistogramOpts{
Name: "grpc_client_handling_seconds",
Help: "Histogram of response latency (seconds) of the gRPC until it is finished by the application.",
Buckets: prometheus.DefBuckets,
}),
allLabels,
)
}
}
}
// WithClientStreamRecvHistogram turns on recording of single message receive time of streaming RPCs.
// Histogram metrics can be very expensive for Prometheus to retain and query.
func WithClientStreamRecvHistogram(opts ...HistogramOption) ClientMetricsOption {
return func(o *clientMetricsConfig) {
o.clientStreamRecvHistogramFn = func() *prometheus.HistogramVec {
defaultLabels := []string{"grpc_type", "grpc_service", "grpc_method"}
allLabels := append(defaultLabels, o.contextLabels...)
return prometheus.NewHistogramVec(
histogramOptions(opts).apply(&prometheus.HistogramOpts{
Name: "grpc_client_msg_recv_handling_seconds",
Help: "Histogram of response latency (seconds) of the gRPC single message receive.",
Buckets: prometheus.DefBuckets,
}),
allLabels,
)
}
}
}
// WithClientStreamSendHistogram turns on recording of single message send time of streaming RPCs.
// Histogram metrics can be very expensive for Prometheus to retain and query.
func WithClientStreamSendHistogram(opts ...HistogramOption) ClientMetricsOption {
return func(o *clientMetricsConfig) {
o.clientStreamSendHistogramFn = func() *prometheus.HistogramVec {
defaultLabels := []string{"grpc_type", "grpc_service", "grpc_method"}
allLabels := append(defaultLabels, o.contextLabels...)
return prometheus.NewHistogramVec(
histogramOptions(opts).apply(&prometheus.HistogramOpts{
Name: "grpc_client_msg_send_handling_seconds",
Help: "Histogram of response latency (seconds) of the gRPC single message send.",
Buckets: prometheus.DefBuckets,
}),
allLabels,
)
}
}
}
// WithClientContextLabels configures the server metrics to include dynamic labels extracted from context.
// The provided label names will be added to all server metrics as dynamic labels.
// Use WithLabelsFromContext in the interceptor options to specify how to extract these labels from context.
func WithClientContextLabels(labelNames ...string) ClientMetricsOption {
return func(o *clientMetricsConfig) {
o.contextLabels = labelNames
}
}
@@ -0,0 +1,23 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
package prometheus
type grpcType string
// grpcType describes all types of grpc connection.
const (
Unary grpcType = "unary"
ClientStream grpcType = "client_stream"
ServerStream grpcType = "server_stream"
BidiStream grpcType = "bidi_stream"
)
// Kind describes whether interceptor is a client or server type.
type Kind string
// Enum for Client and Server Kind.
const (
KindClient Kind = "client"
KindServer Kind = "server"
)
@@ -0,0 +1,8 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
/*
Package prometheus provides a standalone interceptor for metrics. It's next iteration of deprecated https://github.com/grpc-ecosystem/go-grpc-prometheus.
See https://github.com/grpc-ecosystem/go-grpc-middleware/tree/main/examples for example.
*/
package prometheus
@@ -0,0 +1,152 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
package prometheus
import (
"github.com/prometheus/client_golang/prometheus"
"google.golang.org/grpc"
"google.golang.org/grpc/status"
)
// FromError returns a grpc status. If the error code is neither a valid grpc status nor a context error, codes.Unknown
// will be set.
func FromError(err error) *status.Status {
s, ok := status.FromError(err)
// Mirror what the grpc server itself does, i.e. also convert context errors to status
if !ok {
s = status.FromContextError(err)
}
return s
}
// A CounterOption lets you add options to Counter metrics using With* funcs.
type CounterOption func(*prometheus.CounterOpts)
type counterOptions []CounterOption
func (co counterOptions) apply(o prometheus.CounterOpts) prometheus.CounterOpts {
for _, f := range co {
f(&o)
}
return o
}
// WithConstLabels allows you to add ConstLabels to Counter metrics.
func WithConstLabels(labels prometheus.Labels) CounterOption {
return func(o *prometheus.CounterOpts) {
o.ConstLabels = labels
}
}
// WithSubsystem allows you to add a Subsystem to Counter metrics.
func WithSubsystem(subsystem string) CounterOption {
return func(o *prometheus.CounterOpts) {
o.Subsystem = subsystem
}
}
// WithNamespace allows you to add a Namespace to Counter metrics.
func WithNamespace(namespace string) CounterOption {
return func(o *prometheus.CounterOpts) {
o.Namespace = namespace
}
}
// A HistogramOption lets you add options to Histogram metrics using With*
// funcs.
type HistogramOption func(*prometheus.HistogramOpts)
type histogramOptions []HistogramOption
func (ho histogramOptions) apply(o *prometheus.HistogramOpts) prometheus.HistogramOpts {
for _, f := range ho {
f(o)
}
return *o
}
// WithHistogramBuckets allows you to specify custom bucket ranges for histograms if EnableHandlingTimeHistogram is on.
func WithHistogramBuckets(buckets []float64) HistogramOption {
return func(o *prometheus.HistogramOpts) { o.Buckets = buckets }
}
// WithHistogramOpts allows you to specify HistogramOpts but makes sure the correct name and label is used.
// This function is helpful when specifying more than just the buckets, like using NativeHistograms.
func WithHistogramOpts(opts *prometheus.HistogramOpts) HistogramOption {
// TODO: This isn't ideal either if new fields are added to prometheus.HistogramOpts.
// Maybe we can change the interface to accept arbitrary HistogramOpts and
// only make sure to overwrite the necessary fields (name, labels).
return func(o *prometheus.HistogramOpts) {
o.Buckets = opts.Buckets
o.NativeHistogramBucketFactor = opts.NativeHistogramBucketFactor
o.NativeHistogramZeroThreshold = opts.NativeHistogramZeroThreshold
o.NativeHistogramMaxBucketNumber = opts.NativeHistogramMaxBucketNumber
o.NativeHistogramMinResetDuration = opts.NativeHistogramMinResetDuration
o.NativeHistogramMaxZeroThreshold = opts.NativeHistogramMaxZeroThreshold
}
}
// WithHistogramConstLabels allows you to add custom ConstLabels to
// histograms metrics.
func WithHistogramConstLabels(labels prometheus.Labels) HistogramOption {
return func(o *prometheus.HistogramOpts) {
o.ConstLabels = labels
}
}
// WithHistogramSubsystem allows you to add a Subsystem to histograms metrics.
func WithHistogramSubsystem(subsystem string) HistogramOption {
return func(o *prometheus.HistogramOpts) {
o.Subsystem = subsystem
}
}
// WithHistogramNamespace allows you to add a Namespace to histograms metrics.
func WithHistogramNamespace(namespace string) HistogramOption {
return func(o *prometheus.HistogramOpts) {
o.Namespace = namespace
}
}
func typeFromMethodInfo(mInfo *grpc.MethodInfo) grpcType {
if !mInfo.IsClientStream && !mInfo.IsServerStream {
return Unary
}
if mInfo.IsClientStream && !mInfo.IsServerStream {
return ClientStream
}
if !mInfo.IsClientStream && mInfo.IsServerStream {
return ServerStream
}
return BidiStream
}
// An Option lets you add options to prometheus interceptors using With* funcs.
type Option func(*config)
type config struct {
exemplarFn exemplarFromCtxFn
labelsFn labelsFromCtxFn
}
func (c *config) apply(opts []Option) {
for _, o := range opts {
o(c)
}
}
// WithExemplarFromContext sets function that will be used to deduce exemplar for all counter and histogram metrics.
func WithExemplarFromContext(exemplarFn exemplarFromCtxFn) Option {
return func(o *config) {
o.exemplarFn = exemplarFn
}
}
// WithLabelsFromContext sets function that will be used to extract labels from context for metrics.
// This should be used in conjunction with WithContextLabels to define which labels to extract.
func WithLabelsFromContext(labelsFn labelsFromCtxFn) Option {
return func(o *config) {
o.labelsFn = labelsFn
}
}
@@ -0,0 +1,164 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
package prometheus
import (
"context"
"time"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors"
"github.com/prometheus/client_golang/prometheus"
)
type reporter struct {
clientMetrics *ClientMetrics
serverMetrics *ServerMetrics
typ interceptors.GRPCType
service, method string
kind Kind
exemplar prometheus.Labels
contextLabels []string
}
func (r *reporter) PostCall(err error, rpcDuration time.Duration) {
// get status code from error
status := FromError(err)
code := status.Code()
// perform handling of metrics from code
switch r.kind {
case KindServer:
baseLabels := []string{string(r.typ), r.service, r.method, code.String()}
allLabels := append(baseLabels, r.contextLabels...)
r.incrementWithExemplar(r.serverMetrics.serverHandledCounter, allLabels...)
if r.serverMetrics.serverHandledHistogram != nil {
histLabels := []string{string(r.typ), r.service, r.method}
allHistLabels := append(histLabels, r.contextLabels...)
r.observeWithExemplar(r.serverMetrics.serverHandledHistogram, rpcDuration.Seconds(), allHistLabels...)
}
case KindClient:
baseLabels := []string{string(r.typ), r.service, r.method, code.String()}
allLabels := append(baseLabels, r.contextLabels...)
r.incrementWithExemplar(r.clientMetrics.clientHandledCounter, allLabels...)
if r.clientMetrics.clientHandledHistogram != nil {
histLabels := []string{string(r.typ), r.service, r.method}
allHistLabels := append(histLabels, r.contextLabels...)
r.observeWithExemplar(r.clientMetrics.clientHandledHistogram, rpcDuration.Seconds(), allHistLabels...)
}
}
}
func (r *reporter) PostMsgSend(_ any, err error, sendDuration time.Duration) {
switch r.kind {
case KindServer:
baseLabels := []string{string(r.typ), r.service, r.method}
allLabels := append(baseLabels, r.contextLabels...)
if err == nil {
r.incrementWithExemplar(r.serverMetrics.serverStreamMsgSent, allLabels...)
}
case KindClient:
baseLabels := []string{string(r.typ), r.service, r.method}
allLabels := append(baseLabels, r.contextLabels...)
if err == nil {
r.incrementWithExemplar(r.clientMetrics.clientStreamMsgSent, allLabels...)
}
if r.clientMetrics.clientStreamSendHistogram != nil {
r.observeWithExemplar(r.clientMetrics.clientStreamSendHistogram, sendDuration.Seconds(), allLabels...)
}
}
}
func (r *reporter) PostMsgReceive(_ any, err error, recvDuration time.Duration) {
switch r.kind {
case KindServer:
baseLabels := []string{string(r.typ), r.service, r.method}
allLabels := append(baseLabels, r.contextLabels...)
if err == nil {
r.incrementWithExemplar(r.serverMetrics.serverStreamMsgReceived, allLabels...)
}
case KindClient:
baseLabels := []string{string(r.typ), r.service, r.method}
allLabels := append(baseLabels, r.contextLabels...)
if err == nil {
r.incrementWithExemplar(r.clientMetrics.clientStreamMsgReceived, allLabels...)
}
if r.clientMetrics.clientStreamRecvHistogram != nil {
r.observeWithExemplar(r.clientMetrics.clientStreamRecvHistogram, recvDuration.Seconds(), allLabels...)
}
}
}
type reportable struct {
clientMetrics *ClientMetrics
serverMetrics *ServerMetrics
opts []Option
}
func (rep *reportable) ServerReporter(ctx context.Context, meta interceptors.CallMeta) (interceptors.Reporter, context.Context) {
return rep.reporter(ctx, rep.serverMetrics, nil, meta, KindServer)
}
func (rep *reportable) ClientReporter(ctx context.Context, meta interceptors.CallMeta) (interceptors.Reporter, context.Context) {
return rep.reporter(ctx, nil, rep.clientMetrics, meta, KindClient)
}
func (rep *reportable) reporter(ctx context.Context, sm *ServerMetrics, cm *ClientMetrics, meta interceptors.CallMeta, kind Kind) (interceptors.Reporter, context.Context) {
var c config
c.apply(rep.opts)
r := &reporter{
clientMetrics: cm,
serverMetrics: sm,
typ: meta.Typ,
service: meta.Service,
method: meta.Method,
kind: kind,
}
if c.exemplarFn != nil {
r.exemplar = c.exemplarFn(ctx)
}
// Extract context labels if labelsFn is configured and we're on server side
if c.labelsFn != nil {
var contextLabelNames []string
if kind == KindServer && sm != nil {
contextLabelNames = sm.contextLabelNames
} else if kind == KindClient && cm != nil {
contextLabelNames = cm.contextLabelNames
}
contextLabelMap := c.labelsFn(ctx)
// Extract context label values in the order defined by the server metrics
r.contextLabels = make([]string, len(contextLabelNames))
for i, labelName := range contextLabelNames {
if value, exists := contextLabelMap[labelName]; exists {
r.contextLabels[i] = value
} else {
// Use empty string if label not found in context
r.contextLabels[i] = ""
}
}
}
switch kind {
case KindClient:
baseLabels := []string{string(r.typ), r.service, r.method}
allLabels := append(baseLabels, r.contextLabels...)
r.incrementWithExemplar(r.clientMetrics.clientStartedCounter, allLabels...)
case KindServer:
baseLabels := []string{string(r.typ), r.service, r.method}
allLabels := append(baseLabels, r.contextLabels...)
r.incrementWithExemplar(r.serverMetrics.serverStartedCounter, allLabels...)
}
return r, ctx
}
func (r *reporter) incrementWithExemplar(c *prometheus.CounterVec, lvals ...string) {
c.WithLabelValues(lvals...).(prometheus.ExemplarAdder).AddWithExemplar(1, r.exemplar)
}
func (r *reporter) observeWithExemplar(h *prometheus.HistogramVec, value float64, lvals ...string) {
h.WithLabelValues(lvals...).(prometheus.ExemplarObserver).ObserveWithExemplar(value, r.exemplar)
}
@@ -0,0 +1,166 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
package prometheus
import (
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors"
"github.com/prometheus/client_golang/prometheus"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
// ServerMetrics represents a collection of metrics to be registered on a
// Prometheus metrics registry for a gRPC server.
type ServerMetrics struct {
serverStartedCounter *prometheus.CounterVec
serverHandledCounter *prometheus.CounterVec
serverStreamMsgReceived *prometheus.CounterVec
serverStreamMsgSent *prometheus.CounterVec
// serverHandledHistogram can be nil.
serverHandledHistogram *prometheus.HistogramVec
// contextLabelNames stores the names of context labels
contextLabelNames []string
}
// NewServerMetrics returns a new ServerMetrics object that has server interceptor methods.
// NOTE: Remember to register ServerMetrics object by using prometheus registry
// e.g. prometheus.MustRegister(myServerMetrics).
func NewServerMetrics(opts ...ServerMetricsOption) *ServerMetrics {
var config serverMetricsConfig
config.apply(opts)
// Build label names by combining default labels with context labels
defaultLabels := []string{"grpc_type", "grpc_service", "grpc_method"}
defaultLabelsWithCode := []string{"grpc_type", "grpc_service", "grpc_method", "grpc_code"}
startedLabels := append(defaultLabels, config.contextLabels...)
handledLabels := append(defaultLabelsWithCode, config.contextLabels...)
streamLabels := append(defaultLabels, config.contextLabels...)
// Create histogram if enabled
var serverHandledHistogram *prometheus.HistogramVec
if config.enableHistogram {
histogramLabels := append(defaultLabels, config.contextLabels...)
serverHandledHistogram = prometheus.NewHistogramVec(
histogramOptions(config.histogramOpts).apply(&prometheus.HistogramOpts{
Name: "grpc_server_handling_seconds",
Help: "Histogram of response latency (seconds) of gRPC that had been application-level handled by the server.",
Buckets: prometheus.DefBuckets,
}),
histogramLabels,
)
}
return &ServerMetrics{
serverStartedCounter: prometheus.NewCounterVec(
config.counterOpts.apply(prometheus.CounterOpts{
Name: "grpc_server_started_total",
Help: "Total number of RPCs started on the server.",
}), startedLabels,
),
serverHandledCounter: prometheus.NewCounterVec(
config.counterOpts.apply(prometheus.CounterOpts{
Name: "grpc_server_handled_total",
Help: "Total number of RPCs completed on the server, regardless of success or failure.",
}), handledLabels,
),
serverStreamMsgReceived: prometheus.NewCounterVec(
config.counterOpts.apply(prometheus.CounterOpts{
Name: "grpc_server_msg_received_total",
Help: "Total number of RPC stream messages received on the server.",
}), streamLabels,
),
serverStreamMsgSent: prometheus.NewCounterVec(
config.counterOpts.apply(prometheus.CounterOpts{
Name: "grpc_server_msg_sent_total",
Help: "Total number of gRPC stream messages sent by the server.",
}), streamLabels,
),
serverHandledHistogram: serverHandledHistogram,
contextLabelNames: config.contextLabels,
}
}
// Describe sends the super-set of all possible descriptors of metrics
// collected by this Collector to the provided channel and returns once
// the last descriptor has been sent.
func (m *ServerMetrics) Describe(ch chan<- *prometheus.Desc) {
m.serverStartedCounter.Describe(ch)
m.serverHandledCounter.Describe(ch)
m.serverStreamMsgReceived.Describe(ch)
m.serverStreamMsgSent.Describe(ch)
if m.serverHandledHistogram != nil {
m.serverHandledHistogram.Describe(ch)
}
}
// Collect is called by the Prometheus registry when collecting
// metrics. The implementation sends each collected metric via the
// provided channel and returns once the last metric has been sent.
func (m *ServerMetrics) Collect(ch chan<- prometheus.Metric) {
m.serverStartedCounter.Collect(ch)
m.serverHandledCounter.Collect(ch)
m.serverStreamMsgReceived.Collect(ch)
m.serverStreamMsgSent.Collect(ch)
if m.serverHandledHistogram != nil {
m.serverHandledHistogram.Collect(ch)
}
}
// InitializeMetrics initializes all metrics, with their appropriate null
// value, for all gRPC methods registered on a gRPC server. This is useful, to
// ensure that all metrics exist when collecting and querying.
// NOTE: This might add significant cardinality and might not be needed in future version of Prometheus (created timestamp).
func (m *ServerMetrics) InitializeMetrics(server reflection.ServiceInfoProvider) {
serviceInfo := server.GetServiceInfo()
for serviceName, info := range serviceInfo {
for _, mInfo := range info.Methods {
m.preRegisterMethod(serviceName, &mInfo)
}
}
}
// preRegisterMethod is invoked on Register of a Server, allowing all gRPC services labels to be pre-populated.
func (m *ServerMetrics) preRegisterMethod(serviceName string, mInfo *grpc.MethodInfo) {
methodName := mInfo.Name
methodType := string(typeFromMethodInfo(mInfo))
// Create empty context label values for pre-registration
contextLabels := make([]string, len(m.contextLabelNames))
for i := range contextLabels {
contextLabels[i] = ""
}
// Build complete label value arrays
startedLabels := append([]string{methodType, serviceName, methodName}, contextLabels...)
streamLabels := append([]string{methodType, serviceName, methodName}, contextLabels...)
// These are just references (no increments), as just referencing will create the labels but not set values.
_, _ = m.serverStartedCounter.GetMetricWithLabelValues(startedLabels...)
_, _ = m.serverStreamMsgReceived.GetMetricWithLabelValues(streamLabels...)
_, _ = m.serverStreamMsgSent.GetMetricWithLabelValues(streamLabels...)
if m.serverHandledHistogram != nil {
_, _ = m.serverHandledHistogram.GetMetricWithLabelValues(streamLabels...)
}
for _, code := range interceptors.AllCodes {
handledLabelsWithCode := append([]string{methodType, serviceName, methodName, code.String()}, contextLabels...)
_, _ = m.serverHandledCounter.GetMetricWithLabelValues(handledLabelsWithCode...)
}
}
// UnaryServerInterceptor is a gRPC server-side interceptor that provides Prometheus monitoring for Unary RPCs.
func (m *ServerMetrics) UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor {
return interceptors.UnaryServerInterceptor(&reportable{
opts: opts,
serverMetrics: m,
})
}
// StreamServerInterceptor is a gRPC server-side interceptor that provides Prometheus monitoring for Streaming RPCs.
func (m *ServerMetrics) StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor {
return interceptors.StreamServerInterceptor(&reportable{
opts: opts,
serverMetrics: m,
})
}
@@ -0,0 +1,58 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
package prometheus
import (
"context"
"github.com/prometheus/client_golang/prometheus"
)
type (
exemplarFromCtxFn func(ctx context.Context) prometheus.Labels
labelsFromCtxFn func(metadata context.Context) prometheus.Labels
)
type serverMetricsConfig struct {
counterOpts counterOptions
// histogramOpts stores the options for creating the histogram with dynamic labels
histogramOpts histogramOptions
// enableHistogram indicates whether histogram should be created
enableHistogram bool
// contextLabels defines the names of dynamic labels to be extracted from context
contextLabels []string
}
type ServerMetricsOption func(*serverMetricsConfig)
func (c *serverMetricsConfig) apply(opts []ServerMetricsOption) {
for _, o := range opts {
o(c)
}
}
// WithServerCounterOptions sets counter options.
func WithServerCounterOptions(opts ...CounterOption) ServerMetricsOption {
return func(o *serverMetricsConfig) {
o.counterOpts = opts
}
}
// WithServerHandlingTimeHistogram turns on recording of handling time of RPCs.
// Histogram metrics can be very expensive for Prometheus to retain and query.
func WithServerHandlingTimeHistogram(opts ...HistogramOption) ServerMetricsOption {
return func(o *serverMetricsConfig) {
o.histogramOpts = opts
o.enableHistogram = true
}
}
// WithContextLabels configures the server metrics to include dynamic labels extracted from context.
// The provided label names will be added to all server metrics as dynamic labels.
// Use WithLabelsFromContext in the interceptor options to specify how to extract these labels from context.
func WithContextLabels(labelNames ...string) ServerMetricsOption {
return func(o *serverMetricsConfig) {
o.contextLabels = labelNames
}
}
+2
View File
@@ -0,0 +1,2 @@
Copyright (c) The go-grpc-middleware Authors.
Licensed under the Apache License 2.0.
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,67 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
package interceptors
import (
"fmt"
"strings"
"google.golang.org/grpc"
)
func splitFullMethodName(fullMethod string) (string, string) {
fullMethod = strings.TrimPrefix(fullMethod, "/") // remove leading slash
if i := strings.Index(fullMethod, "/"); i >= 0 {
return fullMethod[:i], fullMethod[i+1:]
}
return "unknown", "unknown"
}
type CallMeta struct {
ReqOrNil any
Typ GRPCType
Service string
Method string
IsClient bool
}
func NewClientCallMeta(fullMethod string, streamDesc *grpc.StreamDesc, reqOrNil any) CallMeta {
c := CallMeta{IsClient: true, ReqOrNil: reqOrNil, Typ: Unary}
if streamDesc != nil {
c.Typ = clientStreamType(streamDesc)
}
c.Service, c.Method = splitFullMethodName(fullMethod)
return c
}
func NewServerCallMeta(fullMethod string, streamInfo *grpc.StreamServerInfo, reqOrNil any) CallMeta {
c := CallMeta{IsClient: false, ReqOrNil: reqOrNil, Typ: Unary}
if streamInfo != nil {
c.Typ = serverStreamType(streamInfo)
}
c.Service, c.Method = splitFullMethodName(fullMethod)
return c
}
func (c CallMeta) FullMethod() string {
return fmt.Sprintf("/%s/%s", c.Service, c.Method)
}
func clientStreamType(desc *grpc.StreamDesc) GRPCType {
if desc.ClientStreams && !desc.ServerStreams {
return ClientStream
} else if !desc.ClientStreams && desc.ServerStreams {
return ServerStream
}
return BidiStream
}
func serverStreamType(info *grpc.StreamServerInfo) GRPCType {
if info.IsClientStream && !info.IsServerStream {
return ClientStream
} else if !info.IsClientStream && info.IsServerStream {
return ServerStream
}
return BidiStream
}
@@ -0,0 +1,80 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
// Go gRPC Middleware monitoring interceptors for client-side gRPC.
package interceptors
import (
"context"
"errors"
"io"
"time"
"google.golang.org/grpc"
)
// UnaryClientInterceptor is a gRPC client-side interceptor that provides reporting for Unary RPCs.
func UnaryClientInterceptor(reportable ClientReportable) grpc.UnaryClientInterceptor {
return func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
r := newReport(NewClientCallMeta(method, nil, req))
reporter, newCtx := reportable.ClientReporter(ctx, r.callMeta)
reporter.PostMsgSend(req, nil, time.Since(r.startTime))
err := invoker(newCtx, method, req, reply, cc, opts...)
reporter.PostMsgReceive(reply, err, time.Since(r.startTime))
reporter.PostCall(err, time.Since(r.startTime))
return err
}
}
// StreamClientInterceptor is a gRPC client-side interceptor that provides reporting for Stream RPCs.
func StreamClientInterceptor(reportable ClientReportable) grpc.StreamClientInterceptor {
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
r := newReport(NewClientCallMeta(method, desc, nil))
reporter, newCtx := reportable.ClientReporter(ctx, r.callMeta)
clientStream, err := streamer(newCtx, desc, cc, method, opts...)
if err != nil {
reporter.PostCall(err, time.Since(r.startTime))
return nil, err
}
return &monitoredClientStream{ClientStream: clientStream, startTime: r.startTime, hasServerStream: desc.ServerStreams, reporter: reporter}, nil
}
}
// monitoredClientStream wraps grpc.ClientStream allowing each Sent/Recv of message to report.
type monitoredClientStream struct {
grpc.ClientStream
startTime time.Time
hasServerStream bool
reporter Reporter
}
func (s *monitoredClientStream) SendMsg(m any) error {
start := time.Now()
err := s.ClientStream.SendMsg(m)
s.reporter.PostMsgSend(m, err, time.Since(start))
return err
}
func (s *monitoredClientStream) RecvMsg(m any) error {
start := time.Now()
err := s.ClientStream.RecvMsg(m)
s.reporter.PostMsgReceive(m, err, time.Since(start))
if s.hasServerStream {
if err == nil {
return nil
}
var postErr error
if !errors.Is(err, io.EOF) {
postErr = err
}
s.reporter.PostCall(postErr, time.Since(s.startTime))
} else {
s.reporter.PostCall(err, time.Since(s.startTime))
}
return err
}
@@ -0,0 +1,12 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
//
/*
interceptor is an internal package used by higher level middlewares. It allows injecting custom code in various
places of the gRPC lifecycle.
This particular package is intended for use by other middleware, metric, logging or otherwise.
This allows code to be shared between different implementations.
*/
package interceptors
@@ -0,0 +1,73 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
package interceptors
import (
"context"
"time"
"google.golang.org/grpc/codes"
)
type GRPCType string
const (
Unary GRPCType = "unary"
ClientStream GRPCType = "client_stream"
ServerStream GRPCType = "server_stream"
BidiStream GRPCType = "bidi_stream"
)
var AllCodes = []codes.Code{
codes.OK, codes.Canceled, codes.Unknown, codes.InvalidArgument, codes.DeadlineExceeded, codes.NotFound,
codes.AlreadyExists, codes.PermissionDenied, codes.Unauthenticated, codes.ResourceExhausted,
codes.FailedPrecondition, codes.Aborted, codes.OutOfRange, codes.Unimplemented, codes.Internal,
codes.Unavailable, codes.DataLoss,
}
type ClientReportable interface {
ClientReporter(context.Context, CallMeta) (Reporter, context.Context)
}
type ServerReportable interface {
ServerReporter(context.Context, CallMeta) (Reporter, context.Context)
}
// CommonReportableFunc helper allows an easy way to implement reporter with common client and server logic.
type CommonReportableFunc func(ctx context.Context, c CallMeta) (Reporter, context.Context)
func (f CommonReportableFunc) ClientReporter(ctx context.Context, c CallMeta) (Reporter, context.Context) {
return f(ctx, c)
}
func (f CommonReportableFunc) ServerReporter(ctx context.Context, c CallMeta) (Reporter, context.Context) {
return f(ctx, c)
}
type Reporter interface {
PostCall(err error, rpcDuration time.Duration)
PostMsgSend(reqProto any, err error, sendDuration time.Duration)
PostMsgReceive(replyProto any, err error, recvDuration time.Duration)
}
var _ Reporter = NoopReporter{}
type NoopReporter struct{}
func (NoopReporter) PostCall(error, time.Duration) {}
func (NoopReporter) PostMsgSend(any, error, time.Duration) {}
func (NoopReporter) PostMsgReceive(any, error, time.Duration) {}
type report struct {
callMeta CallMeta
startTime time.Time
}
func newReport(callMeta CallMeta) report {
r := report{
startTime: time.Now(),
callMeta: callMeta,
}
return r
}
@@ -0,0 +1,65 @@
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
// Go gRPC Middleware monitoring interceptors for server-side gRPC.
package interceptors
import (
"context"
"time"
"google.golang.org/grpc"
)
// UnaryServerInterceptor is a gRPC server-side interceptor that provides reporting for Unary RPCs.
func UnaryServerInterceptor(reportable ServerReportable) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
r := newReport(NewServerCallMeta(info.FullMethod, nil, req))
reporter, newCtx := reportable.ServerReporter(ctx, r.callMeta)
reporter.PostMsgReceive(req, nil, time.Since(r.startTime))
resp, err := handler(newCtx, req)
reporter.PostMsgSend(resp, err, time.Since(r.startTime))
reporter.PostCall(err, time.Since(r.startTime))
return resp, err
}
}
// StreamServerInterceptor is a gRPC server-side interceptor that provides reporting for Streaming RPCs.
func StreamServerInterceptor(reportable ServerReportable) grpc.StreamServerInterceptor {
return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
r := newReport(NewServerCallMeta(info.FullMethod, info, nil))
reporter, newCtx := reportable.ServerReporter(ss.Context(), r.callMeta)
err := handler(srv, &monitoredServerStream{ServerStream: ss, newCtx: newCtx, reporter: reporter})
reporter.PostCall(err, time.Since(r.startTime))
return err
}
}
// monitoredStream wraps grpc.ServerStream allowing each Sent/Recv of message to report.
type monitoredServerStream struct {
grpc.ServerStream
newCtx context.Context
reporter Reporter
}
func (s *monitoredServerStream) Context() context.Context {
return s.newCtx
}
func (s *monitoredServerStream) SendMsg(m any) error {
start := time.Now()
err := s.ServerStream.SendMsg(m)
s.reporter.PostMsgSend(m, err, time.Since(start))
return err
}
func (s *monitoredServerStream) RecvMsg(m any) error {
start := time.Now()
err := s.ServerStream.RecvMsg(m)
s.reporter.PostMsgReceive(m, err, time.Since(start))
return err
}
@@ -1,201 +0,0 @@
#vendor
vendor/
# Created by .ignore support plugin (hsz.mobi)
coverage.txt
### Go template
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
### Windows template
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
### Kate template
# Swap Files #
.*.kate-swp
.swp.*
### SublimeText template
# cache files for sublime text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
# workspace files are user-specific
*.sublime-workspace
# project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using SublimeText
# *.sublime-project
# sftp configuration file
sftp-config.json
### Linux template
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml
# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
# Gradle:
.idea/gradle.xml
.idea/libraries
# Mongo Explorer plugin:
.idea/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Xcode template
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
## Build generated
build/
DerivedData/
## Various settings
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata/
## Other
*.moved-aside
*.xccheckout
*.xcscmblueprint
### Eclipse template
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders
# Eclipse Core
.project
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# PyDev specific (Python IDE for Eclipse)
*.pydevproject
# CDT-specific (C/C++ Development Tooling)
.cproject
# JDT-specific (Eclipse Java Development Tools)
.classpath
# Java annotation processor (APT)
.factorypath
# PDT-specific (PHP Development Tools)
.buildpath
# sbteclipse plugin
.target
# Tern plugin
.tern-project
# TeXlipse plugin
.texlipse
# STS (Spring Tool Suite)
.springBeans
# Code Recommenders
.recommenders/
-25
View File
@@ -1,25 +0,0 @@
sudo: false
language: go
# * github.com/grpc/grpc-go still supports go1.6
# - When we drop support for go1.6 we can remove golang.org/x/net/context
# below as it is part of the Go std library since go1.7
# * github.com/prometheus/client_golang already requires at least go1.7 since
# September 2017
go:
- 1.6.x
- 1.7.x
- 1.8.x
- 1.9.x
- 1.10.x
- master
install:
- go get github.com/prometheus/client_golang/prometheus
- go get google.golang.org/grpc
- go get golang.org/x/net/context
- go get github.com/stretchr/testify
script:
- make test
after_success:
- bash <(curl -s https://codecov.io/bash)
-24
View File
@@ -1,24 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [1.2.0](https://github.com/grpc-ecosystem/go-grpc-prometheus/releases/tag/v1.2.0) - 2018-06-04
### Added
* Provide metrics object as `prometheus.Collector`, for conventional metric registration.
* Support non-default/global Prometheus registry.
* Allow configuring counters with `prometheus.CounterOpts`.
### Changed
* Remove usage of deprecated `grpc.Code()`.
* Remove usage of deprecated `grpc.Errorf` and replace with `status.Errorf`.
---
This changelog was started with version `v1.2.0`, for earlier versions refer to the respective [GitHub releases](https://github.com/grpc-ecosystem/go-grpc-prometheus/releases).
-247
View File
@@ -1,247 +0,0 @@
# Go gRPC Interceptors for Prometheus monitoring
[![Travis Build](https://travis-ci.org/grpc-ecosystem/go-grpc-prometheus.svg)](https://travis-ci.org/grpc-ecosystem/go-grpc-prometheus)
[![Go Report Card](https://goreportcard.com/badge/github.com/grpc-ecosystem/go-grpc-prometheus)](http://goreportcard.com/report/grpc-ecosystem/go-grpc-prometheus)
[![GoDoc](http://img.shields.io/badge/GoDoc-Reference-blue.svg)](https://godoc.org/github.com/grpc-ecosystem/go-grpc-prometheus)
[![SourceGraph](https://sourcegraph.com/github.com/grpc-ecosystem/go-grpc-prometheus/-/badge.svg)](https://sourcegraph.com/github.com/grpc-ecosystem/go-grpc-prometheus/?badge)
[![codecov](https://codecov.io/gh/grpc-ecosystem/go-grpc-prometheus/branch/master/graph/badge.svg)](https://codecov.io/gh/grpc-ecosystem/go-grpc-prometheus)
[![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[Prometheus](https://prometheus.io/) monitoring for your [gRPC Go](https://github.com/grpc/grpc-go) servers and clients.
A sister implementation for [gRPC Java](https://github.com/grpc/grpc-java) (same metrics, same semantics) is in [grpc-ecosystem/java-grpc-prometheus](https://github.com/grpc-ecosystem/java-grpc-prometheus).
## Interceptors
[gRPC Go](https://github.com/grpc/grpc-go) recently acquired support for Interceptors, i.e. middleware that is executed
by a gRPC Server before the request is passed onto the user's application logic. It is a perfect way to implement
common patterns: auth, logging and... monitoring.
To use Interceptors in chains, please see [`go-grpc-middleware`](https://github.com/mwitkow/go-grpc-middleware).
## Usage
There are two types of interceptors: client-side and server-side. This package provides monitoring Interceptors for both.
### Server-side
```go
import "github.com/grpc-ecosystem/go-grpc-prometheus"
...
// Initialize your gRPC server's interceptor.
myServer := grpc.NewServer(
grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor),
grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor),
)
// Register your gRPC service implementations.
myservice.RegisterMyServiceServer(s.server, &myServiceImpl{})
// After all your registrations, make sure all of the Prometheus metrics are initialized.
grpc_prometheus.Register(myServer)
// Register Prometheus metrics handler.
http.Handle("/metrics", promhttp.Handler())
...
```
### Client-side
```go
import "github.com/grpc-ecosystem/go-grpc-prometheus"
...
clientConn, err = grpc.Dial(
address,
grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor),
grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor)
)
client = pb_testproto.NewTestServiceClient(clientConn)
resp, err := client.PingEmpty(s.ctx, &myservice.Request{Msg: "hello"})
...
```
# Metrics
## Labels
All server-side metrics start with `grpc_server` as Prometheus subsystem name. All client-side metrics start with `grpc_client`. Both of them have mirror-concepts. Similarly all methods
contain the same rich labels:
* `grpc_service` - the [gRPC service](http://www.grpc.io/docs/#defining-a-service) name, which is the combination of protobuf `package` and
the `grpc_service` section name. E.g. for `package = mwitkow.testproto` and
`service TestService` the label will be `grpc_service="mwitkow.testproto.TestService"`
* `grpc_method` - the name of the method called on the gRPC service. E.g.
`grpc_method="Ping"`
* `grpc_type` - the gRPC [type of request](http://www.grpc.io/docs/guides/concepts.html#rpc-life-cycle).
Differentiating between the two is important especially for latency measurements.
- `unary` is single request, single response RPC
- `client_stream` is a multi-request, single response RPC
- `server_stream` is a single request, multi-response RPC
- `bidi_stream` is a multi-request, multi-response RPC
Additionally for completed RPCs, the following labels are used:
* `grpc_code` - the human-readable [gRPC status code](https://github.com/grpc/grpc-go/blob/master/codes/codes.go).
The list of all statuses is to long, but here are some common ones:
- `OK` - means the RPC was successful
- `IllegalArgument` - RPC contained bad values
- `Internal` - server-side error not disclosed to the clients
## Counters
The counters and their up to date documentation is in [server_reporter.go](server_reporter.go) and [client_reporter.go](client_reporter.go)
the respective Prometheus handler (usually `/metrics`).
For the purpose of this documentation we will only discuss `grpc_server` metrics. The `grpc_client` ones contain mirror concepts.
For simplicity, let's assume we're tracking a single server-side RPC call of [`mwitkow.testproto.TestService`](examples/testproto/test.proto),
calling the method `PingList`. The call succeeds and returns 20 messages in the stream.
First, immediately after the server receives the call it will increment the
`grpc_server_started_total` and start the handling time clock (if histograms are enabled).
```jsoniq
grpc_server_started_total{grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1
```
Then the user logic gets invoked. It receives one message from the client containing the request
(it's a `server_stream`):
```jsoniq
grpc_server_msg_received_total{grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1
```
The user logic may return an error, or send multiple messages back to the client. In this case, on
each of the 20 messages sent back, a counter will be incremented:
```jsoniq
grpc_server_msg_sent_total{grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 20
```
After the call completes, its status (`OK` or other [gRPC status code](https://github.com/grpc/grpc-go/blob/master/codes/codes.go))
and the relevant call labels increment the `grpc_server_handled_total` counter.
```jsoniq
grpc_server_handled_total{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1
```
## Histograms
[Prometheus histograms](https://prometheus.io/docs/concepts/metric_types/#histogram) are a great way
to measure latency distributions of your RPCs. However, since it is bad practice to have metrics
of [high cardinality](https://prometheus.io/docs/practices/instrumentation/#do-not-overuse-labels)
the latency monitoring metrics are disabled by default. To enable them please call the following
in your server initialization code:
```jsoniq
grpc_prometheus.EnableHandlingTimeHistogram()
```
After the call completes, its handling time will be recorded in a [Prometheus histogram](https://prometheus.io/docs/concepts/metric_types/#histogram)
variable `grpc_server_handling_seconds`. The histogram variable contains three sub-metrics:
* `grpc_server_handling_seconds_count` - the count of all completed RPCs by status and method
* `grpc_server_handling_seconds_sum` - cumulative time of RPCs by status and method, useful for
calculating average handling times
* `grpc_server_handling_seconds_bucket` - contains the counts of RPCs by status and method in respective
handling-time buckets. These buckets can be used by Prometheus to estimate SLAs (see [here](https://prometheus.io/docs/practices/histograms/))
The counter values will look as follows:
```jsoniq
grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.005"} 1
grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.01"} 1
grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.025"} 1
grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.05"} 1
grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.1"} 1
grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.25"} 1
grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="0.5"} 1
grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="1"} 1
grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="2.5"} 1
grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="5"} 1
grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="10"} 1
grpc_server_handling_seconds_bucket{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream",le="+Inf"} 1
grpc_server_handling_seconds_sum{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 0.0003866430000000001
grpc_server_handling_seconds_count{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1
```
## Useful query examples
Prometheus philosophy is to provide raw metrics to the monitoring system, and
let the aggregations be handled there. The verbosity of above metrics make it possible to have that
flexibility. Here's a couple of useful monitoring queries:
### request inbound rate
```jsoniq
sum(rate(grpc_server_started_total{job="foo"}[1m])) by (grpc_service)
```
For `job="foo"` (common label to differentiate between Prometheus monitoring targets), calculate the
rate of requests per second (1 minute window) for each gRPC `grpc_service` that the job has. Please note
how the `grpc_method` is being omitted here: all methods of a given gRPC service will be summed together.
### unary request error rate
```jsoniq
sum(rate(grpc_server_handled_total{job="foo",grpc_type="unary",grpc_code!="OK"}[1m])) by (grpc_service)
```
For `job="foo"`, calculate the per-`grpc_service` rate of `unary` (1:1) RPCs that failed, i.e. the
ones that didn't finish with `OK` code.
### unary request error percentage
```jsoniq
sum(rate(grpc_server_handled_total{job="foo",grpc_type="unary",grpc_code!="OK"}[1m])) by (grpc_service)
/
sum(rate(grpc_server_started_total{job="foo",grpc_type="unary"}[1m])) by (grpc_service)
* 100.0
```
For `job="foo"`, calculate the percentage of failed requests by service. It's easy to notice that
this is a combination of the two above examples. This is an example of a query you would like to
[alert on](https://prometheus.io/docs/alerting/rules/) in your system for SLA violations, e.g.
"no more than 1% requests should fail".
### average response stream size
```jsoniq
sum(rate(grpc_server_msg_sent_total{job="foo",grpc_type="server_stream"}[10m])) by (grpc_service)
/
sum(rate(grpc_server_started_total{job="foo",grpc_type="server_stream"}[10m])) by (grpc_service)
```
For `job="foo"` what is the `grpc_service`-wide `10m` average of messages returned for all `
server_stream` RPCs. This allows you to track the stream sizes returned by your system, e.g. allows
you to track when clients started to send "wide" queries that ret
Note the divisor is the number of started RPCs, in order to account for in-flight requests.
### 99%-tile latency of unary requests
```jsoniq
histogram_quantile(0.99,
sum(rate(grpc_server_handling_seconds_bucket{job="foo",grpc_type="unary"}[5m])) by (grpc_service,le)
)
```
For `job="foo"`, returns an 99%-tile [quantile estimation](https://prometheus.io/docs/practices/histograms/#quantiles)
of the handling time of RPCs per service. Please note the `5m` rate, this means that the quantile
estimation will take samples in a rolling `5m` window. When combined with other quantiles
(e.g. 50%, 90%), this query gives you tremendous insight into the responsiveness of your system
(e.g. impact of caching).
### percentage of slow unary queries (>250ms)
```jsoniq
100.0 - (
sum(rate(grpc_server_handling_seconds_bucket{job="foo",grpc_type="unary",le="0.25"}[5m])) by (grpc_service)
/
sum(rate(grpc_server_handling_seconds_count{job="foo",grpc_type="unary"}[5m])) by (grpc_service)
) * 100.0
```
For `job="foo"` calculate the by-`grpc_service` fraction of slow requests that took longer than `0.25`
seconds. This query is relatively complex, since the Prometheus aggregations use `le` (less or equal)
buckets, meaning that counting "fast" requests fractions is easier. However, simple maths helps.
This is an example of a query you would like to alert on in your system for SLA violations,
e.g. "less than 1% of requests are slower than 250ms".
## Status
This code has been used since August 2015 as the basis for monitoring of *production* gRPC micro services at [Improbable](https://improbable.io).
## License
`go-grpc-prometheus` is released under the Apache 2.0 license. See the [LICENSE](LICENSE) file for details.
-39
View File
@@ -1,39 +0,0 @@
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
// gRPC Prometheus monitoring interceptors for client-side gRPC.
package grpc_prometheus
import (
prom "github.com/prometheus/client_golang/prometheus"
)
var (
// DefaultClientMetrics is the default instance of ClientMetrics. It is
// intended to be used in conjunction the default Prometheus metrics
// registry.
DefaultClientMetrics = NewClientMetrics()
// UnaryClientInterceptor is a gRPC client-side interceptor that provides Prometheus monitoring for Unary RPCs.
UnaryClientInterceptor = DefaultClientMetrics.UnaryClientInterceptor()
// StreamClientInterceptor is a gRPC client-side interceptor that provides Prometheus monitoring for Streaming RPCs.
StreamClientInterceptor = DefaultClientMetrics.StreamClientInterceptor()
)
func init() {
prom.MustRegister(DefaultClientMetrics.clientStartedCounter)
prom.MustRegister(DefaultClientMetrics.clientHandledCounter)
prom.MustRegister(DefaultClientMetrics.clientStreamMsgReceived)
prom.MustRegister(DefaultClientMetrics.clientStreamMsgSent)
}
// EnableClientHandlingTimeHistogram turns on recording of handling time of
// RPCs. Histogram metrics can be very expensive for Prometheus to retain and
// query. This function acts on the DefaultClientMetrics variable and the
// default Prometheus metrics registry.
func EnableClientHandlingTimeHistogram(opts ...HistogramOption) {
DefaultClientMetrics.EnableClientHandlingTimeHistogram(opts...)
prom.Register(DefaultClientMetrics.clientHandledHistogram)
}
-170
View File
@@ -1,170 +0,0 @@
package grpc_prometheus
import (
"io"
prom "github.com/prometheus/client_golang/prometheus"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// ClientMetrics represents a collection of metrics to be registered on a
// Prometheus metrics registry for a gRPC client.
type ClientMetrics struct {
clientStartedCounter *prom.CounterVec
clientHandledCounter *prom.CounterVec
clientStreamMsgReceived *prom.CounterVec
clientStreamMsgSent *prom.CounterVec
clientHandledHistogramEnabled bool
clientHandledHistogramOpts prom.HistogramOpts
clientHandledHistogram *prom.HistogramVec
}
// NewClientMetrics returns a ClientMetrics object. Use a new instance of
// ClientMetrics when not using the default Prometheus metrics registry, for
// example when wanting to control which metrics are added to a registry as
// opposed to automatically adding metrics via init functions.
func NewClientMetrics(counterOpts ...CounterOption) *ClientMetrics {
opts := counterOptions(counterOpts)
return &ClientMetrics{
clientStartedCounter: prom.NewCounterVec(
opts.apply(prom.CounterOpts{
Name: "grpc_client_started_total",
Help: "Total number of RPCs started on the client.",
}), []string{"grpc_type", "grpc_service", "grpc_method"}),
clientHandledCounter: prom.NewCounterVec(
opts.apply(prom.CounterOpts{
Name: "grpc_client_handled_total",
Help: "Total number of RPCs completed by the client, regardless of success or failure.",
}), []string{"grpc_type", "grpc_service", "grpc_method", "grpc_code"}),
clientStreamMsgReceived: prom.NewCounterVec(
opts.apply(prom.CounterOpts{
Name: "grpc_client_msg_received_total",
Help: "Total number of RPC stream messages received by the client.",
}), []string{"grpc_type", "grpc_service", "grpc_method"}),
clientStreamMsgSent: prom.NewCounterVec(
opts.apply(prom.CounterOpts{
Name: "grpc_client_msg_sent_total",
Help: "Total number of gRPC stream messages sent by the client.",
}), []string{"grpc_type", "grpc_service", "grpc_method"}),
clientHandledHistogramEnabled: false,
clientHandledHistogramOpts: prom.HistogramOpts{
Name: "grpc_client_handling_seconds",
Help: "Histogram of response latency (seconds) of the gRPC until it is finished by the application.",
Buckets: prom.DefBuckets,
},
clientHandledHistogram: nil,
}
}
// Describe sends the super-set of all possible descriptors of metrics
// collected by this Collector to the provided channel and returns once
// the last descriptor has been sent.
func (m *ClientMetrics) Describe(ch chan<- *prom.Desc) {
m.clientStartedCounter.Describe(ch)
m.clientHandledCounter.Describe(ch)
m.clientStreamMsgReceived.Describe(ch)
m.clientStreamMsgSent.Describe(ch)
if m.clientHandledHistogramEnabled {
m.clientHandledHistogram.Describe(ch)
}
}
// Collect is called by the Prometheus registry when collecting
// metrics. The implementation sends each collected metric via the
// provided channel and returns once the last metric has been sent.
func (m *ClientMetrics) Collect(ch chan<- prom.Metric) {
m.clientStartedCounter.Collect(ch)
m.clientHandledCounter.Collect(ch)
m.clientStreamMsgReceived.Collect(ch)
m.clientStreamMsgSent.Collect(ch)
if m.clientHandledHistogramEnabled {
m.clientHandledHistogram.Collect(ch)
}
}
// EnableClientHandlingTimeHistogram turns on recording of handling time of RPCs.
// Histogram metrics can be very expensive for Prometheus to retain and query.
func (m *ClientMetrics) EnableClientHandlingTimeHistogram(opts ...HistogramOption) {
for _, o := range opts {
o(&m.clientHandledHistogramOpts)
}
if !m.clientHandledHistogramEnabled {
m.clientHandledHistogram = prom.NewHistogramVec(
m.clientHandledHistogramOpts,
[]string{"grpc_type", "grpc_service", "grpc_method"},
)
}
m.clientHandledHistogramEnabled = true
}
// UnaryClientInterceptor is a gRPC client-side interceptor that provides Prometheus monitoring for Unary RPCs.
func (m *ClientMetrics) UnaryClientInterceptor() func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
monitor := newClientReporter(m, Unary, method)
monitor.SentMessage()
err := invoker(ctx, method, req, reply, cc, opts...)
if err != nil {
monitor.ReceivedMessage()
}
st, _ := status.FromError(err)
monitor.Handled(st.Code())
return err
}
}
// StreamClientInterceptor is a gRPC client-side interceptor that provides Prometheus monitoring for Streaming RPCs.
func (m *ClientMetrics) StreamClientInterceptor() func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
monitor := newClientReporter(m, clientStreamType(desc), method)
clientStream, err := streamer(ctx, desc, cc, method, opts...)
if err != nil {
st, _ := status.FromError(err)
monitor.Handled(st.Code())
return nil, err
}
return &monitoredClientStream{clientStream, monitor}, nil
}
}
func clientStreamType(desc *grpc.StreamDesc) grpcType {
if desc.ClientStreams && !desc.ServerStreams {
return ClientStream
} else if !desc.ClientStreams && desc.ServerStreams {
return ServerStream
}
return BidiStream
}
// monitoredClientStream wraps grpc.ClientStream allowing each Sent/Recv of message to increment counters.
type monitoredClientStream struct {
grpc.ClientStream
monitor *clientReporter
}
func (s *monitoredClientStream) SendMsg(m interface{}) error {
err := s.ClientStream.SendMsg(m)
if err == nil {
s.monitor.SentMessage()
}
return err
}
func (s *monitoredClientStream) RecvMsg(m interface{}) error {
err := s.ClientStream.RecvMsg(m)
if err == nil {
s.monitor.ReceivedMessage()
} else if err == io.EOF {
s.monitor.Handled(codes.OK)
} else {
st, _ := status.FromError(err)
s.monitor.Handled(st.Code())
}
return err
}
-46
View File
@@ -1,46 +0,0 @@
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package grpc_prometheus
import (
"time"
"google.golang.org/grpc/codes"
)
type clientReporter struct {
metrics *ClientMetrics
rpcType grpcType
serviceName string
methodName string
startTime time.Time
}
func newClientReporter(m *ClientMetrics, rpcType grpcType, fullMethod string) *clientReporter {
r := &clientReporter{
metrics: m,
rpcType: rpcType,
}
if r.metrics.clientHandledHistogramEnabled {
r.startTime = time.Now()
}
r.serviceName, r.methodName = splitMethodName(fullMethod)
r.metrics.clientStartedCounter.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Inc()
return r
}
func (r *clientReporter) ReceivedMessage() {
r.metrics.clientStreamMsgReceived.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Inc()
}
func (r *clientReporter) SentMessage() {
r.metrics.clientStreamMsgSent.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Inc()
}
func (r *clientReporter) Handled(code codes.Code) {
r.metrics.clientHandledCounter.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName, code.String()).Inc()
if r.metrics.clientHandledHistogramEnabled {
r.metrics.clientHandledHistogram.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Observe(time.Since(r.startTime).Seconds())
}
}
-16
View File
@@ -1,16 +0,0 @@
SHELL="/bin/bash"
GOFILES_NOVENDOR = $(shell go list ./... | grep -v /vendor/)
all: vet fmt test
fmt:
go fmt $(GOFILES_NOVENDOR)
vet:
go vet $(GOFILES_NOVENDOR)
test: vet
./scripts/test_all.sh
.PHONY: all vet test
-41
View File
@@ -1,41 +0,0 @@
package grpc_prometheus
import (
prom "github.com/prometheus/client_golang/prometheus"
)
// A CounterOption lets you add options to Counter metrics using With* funcs.
type CounterOption func(*prom.CounterOpts)
type counterOptions []CounterOption
func (co counterOptions) apply(o prom.CounterOpts) prom.CounterOpts {
for _, f := range co {
f(&o)
}
return o
}
// WithConstLabels allows you to add ConstLabels to Counter metrics.
func WithConstLabels(labels prom.Labels) CounterOption {
return func(o *prom.CounterOpts) {
o.ConstLabels = labels
}
}
// A HistogramOption lets you add options to Histogram metrics using With*
// funcs.
type HistogramOption func(*prom.HistogramOpts)
// WithHistogramBuckets allows you to specify custom bucket ranges for histograms if EnableHandlingTimeHistogram is on.
func WithHistogramBuckets(buckets []float64) HistogramOption {
return func(o *prom.HistogramOpts) { o.Buckets = buckets }
}
// WithHistogramConstLabels allows you to add custom ConstLabels to
// histograms metrics.
func WithHistogramConstLabels(labels prom.Labels) HistogramOption {
return func(o *prom.HistogramOpts) {
o.ConstLabels = labels
}
}
-48
View File
@@ -1,48 +0,0 @@
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
// gRPC Prometheus monitoring interceptors for server-side gRPC.
package grpc_prometheus
import (
prom "github.com/prometheus/client_golang/prometheus"
"google.golang.org/grpc"
)
var (
// DefaultServerMetrics is the default instance of ServerMetrics. It is
// intended to be used in conjunction the default Prometheus metrics
// registry.
DefaultServerMetrics = NewServerMetrics()
// UnaryServerInterceptor is a gRPC server-side interceptor that provides Prometheus monitoring for Unary RPCs.
UnaryServerInterceptor = DefaultServerMetrics.UnaryServerInterceptor()
// StreamServerInterceptor is a gRPC server-side interceptor that provides Prometheus monitoring for Streaming RPCs.
StreamServerInterceptor = DefaultServerMetrics.StreamServerInterceptor()
)
func init() {
prom.MustRegister(DefaultServerMetrics.serverStartedCounter)
prom.MustRegister(DefaultServerMetrics.serverHandledCounter)
prom.MustRegister(DefaultServerMetrics.serverStreamMsgReceived)
prom.MustRegister(DefaultServerMetrics.serverStreamMsgSent)
}
// Register takes a gRPC server and pre-initializes all counters to 0. This
// allows for easier monitoring in Prometheus (no missing metrics), and should
// be called *after* all services have been registered with the server. This
// function acts on the DefaultServerMetrics variable.
func Register(server *grpc.Server) {
DefaultServerMetrics.InitializeMetrics(server)
}
// EnableHandlingTimeHistogram turns on recording of handling time
// of RPCs. Histogram metrics can be very expensive for Prometheus
// to retain and query. This function acts on the DefaultServerMetrics
// variable and the default Prometheus metrics registry.
func EnableHandlingTimeHistogram(opts ...HistogramOption) {
DefaultServerMetrics.EnableHandlingTimeHistogram(opts...)
prom.Register(DefaultServerMetrics.serverHandledHistogram)
}
-185
View File
@@ -1,185 +0,0 @@
package grpc_prometheus
import (
prom "github.com/prometheus/client_golang/prometheus"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/status"
)
// ServerMetrics represents a collection of metrics to be registered on a
// Prometheus metrics registry for a gRPC server.
type ServerMetrics struct {
serverStartedCounter *prom.CounterVec
serverHandledCounter *prom.CounterVec
serverStreamMsgReceived *prom.CounterVec
serverStreamMsgSent *prom.CounterVec
serverHandledHistogramEnabled bool
serverHandledHistogramOpts prom.HistogramOpts
serverHandledHistogram *prom.HistogramVec
}
// NewServerMetrics returns a ServerMetrics object. Use a new instance of
// ServerMetrics when not using the default Prometheus metrics registry, for
// example when wanting to control which metrics are added to a registry as
// opposed to automatically adding metrics via init functions.
func NewServerMetrics(counterOpts ...CounterOption) *ServerMetrics {
opts := counterOptions(counterOpts)
return &ServerMetrics{
serverStartedCounter: prom.NewCounterVec(
opts.apply(prom.CounterOpts{
Name: "grpc_server_started_total",
Help: "Total number of RPCs started on the server.",
}), []string{"grpc_type", "grpc_service", "grpc_method"}),
serverHandledCounter: prom.NewCounterVec(
opts.apply(prom.CounterOpts{
Name: "grpc_server_handled_total",
Help: "Total number of RPCs completed on the server, regardless of success or failure.",
}), []string{"grpc_type", "grpc_service", "grpc_method", "grpc_code"}),
serverStreamMsgReceived: prom.NewCounterVec(
opts.apply(prom.CounterOpts{
Name: "grpc_server_msg_received_total",
Help: "Total number of RPC stream messages received on the server.",
}), []string{"grpc_type", "grpc_service", "grpc_method"}),
serverStreamMsgSent: prom.NewCounterVec(
opts.apply(prom.CounterOpts{
Name: "grpc_server_msg_sent_total",
Help: "Total number of gRPC stream messages sent by the server.",
}), []string{"grpc_type", "grpc_service", "grpc_method"}),
serverHandledHistogramEnabled: false,
serverHandledHistogramOpts: prom.HistogramOpts{
Name: "grpc_server_handling_seconds",
Help: "Histogram of response latency (seconds) of gRPC that had been application-level handled by the server.",
Buckets: prom.DefBuckets,
},
serverHandledHistogram: nil,
}
}
// EnableHandlingTimeHistogram enables histograms being registered when
// registering the ServerMetrics on a Prometheus registry. Histograms can be
// expensive on Prometheus servers. It takes options to configure histogram
// options such as the defined buckets.
func (m *ServerMetrics) EnableHandlingTimeHistogram(opts ...HistogramOption) {
for _, o := range opts {
o(&m.serverHandledHistogramOpts)
}
if !m.serverHandledHistogramEnabled {
m.serverHandledHistogram = prom.NewHistogramVec(
m.serverHandledHistogramOpts,
[]string{"grpc_type", "grpc_service", "grpc_method"},
)
}
m.serverHandledHistogramEnabled = true
}
// Describe sends the super-set of all possible descriptors of metrics
// collected by this Collector to the provided channel and returns once
// the last descriptor has been sent.
func (m *ServerMetrics) Describe(ch chan<- *prom.Desc) {
m.serverStartedCounter.Describe(ch)
m.serverHandledCounter.Describe(ch)
m.serverStreamMsgReceived.Describe(ch)
m.serverStreamMsgSent.Describe(ch)
if m.serverHandledHistogramEnabled {
m.serverHandledHistogram.Describe(ch)
}
}
// Collect is called by the Prometheus registry when collecting
// metrics. The implementation sends each collected metric via the
// provided channel and returns once the last metric has been sent.
func (m *ServerMetrics) Collect(ch chan<- prom.Metric) {
m.serverStartedCounter.Collect(ch)
m.serverHandledCounter.Collect(ch)
m.serverStreamMsgReceived.Collect(ch)
m.serverStreamMsgSent.Collect(ch)
if m.serverHandledHistogramEnabled {
m.serverHandledHistogram.Collect(ch)
}
}
// UnaryServerInterceptor is a gRPC server-side interceptor that provides Prometheus monitoring for Unary RPCs.
func (m *ServerMetrics) UnaryServerInterceptor() func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
monitor := newServerReporter(m, Unary, info.FullMethod)
monitor.ReceivedMessage()
resp, err := handler(ctx, req)
st, _ := status.FromError(err)
monitor.Handled(st.Code())
if err == nil {
monitor.SentMessage()
}
return resp, err
}
}
// StreamServerInterceptor is a gRPC server-side interceptor that provides Prometheus monitoring for Streaming RPCs.
func (m *ServerMetrics) StreamServerInterceptor() func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
monitor := newServerReporter(m, streamRPCType(info), info.FullMethod)
err := handler(srv, &monitoredServerStream{ss, monitor})
st, _ := status.FromError(err)
monitor.Handled(st.Code())
return err
}
}
// InitializeMetrics initializes all metrics, with their appropriate null
// value, for all gRPC methods registered on a gRPC server. This is useful, to
// ensure that all metrics exist when collecting and querying.
func (m *ServerMetrics) InitializeMetrics(server *grpc.Server) {
serviceInfo := server.GetServiceInfo()
for serviceName, info := range serviceInfo {
for _, mInfo := range info.Methods {
preRegisterMethod(m, serviceName, &mInfo)
}
}
}
func streamRPCType(info *grpc.StreamServerInfo) grpcType {
if info.IsClientStream && !info.IsServerStream {
return ClientStream
} else if !info.IsClientStream && info.IsServerStream {
return ServerStream
}
return BidiStream
}
// monitoredStream wraps grpc.ServerStream allowing each Sent/Recv of message to increment counters.
type monitoredServerStream struct {
grpc.ServerStream
monitor *serverReporter
}
func (s *monitoredServerStream) SendMsg(m interface{}) error {
err := s.ServerStream.SendMsg(m)
if err == nil {
s.monitor.SentMessage()
}
return err
}
func (s *monitoredServerStream) RecvMsg(m interface{}) error {
err := s.ServerStream.RecvMsg(m)
if err == nil {
s.monitor.ReceivedMessage()
}
return err
}
// preRegisterMethod is invoked on Register of a Server, allowing all gRPC services labels to be pre-populated.
func preRegisterMethod(metrics *ServerMetrics, serviceName string, mInfo *grpc.MethodInfo) {
methodName := mInfo.Name
methodType := string(typeFromMethodInfo(mInfo))
// These are just references (no increments), as just referencing will create the labels but not set values.
metrics.serverStartedCounter.GetMetricWithLabelValues(methodType, serviceName, methodName)
metrics.serverStreamMsgReceived.GetMetricWithLabelValues(methodType, serviceName, methodName)
metrics.serverStreamMsgSent.GetMetricWithLabelValues(methodType, serviceName, methodName)
if metrics.serverHandledHistogramEnabled {
metrics.serverHandledHistogram.GetMetricWithLabelValues(methodType, serviceName, methodName)
}
for _, code := range allCodes {
metrics.serverHandledCounter.GetMetricWithLabelValues(methodType, serviceName, methodName, code.String())
}
}
-46
View File
@@ -1,46 +0,0 @@
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package grpc_prometheus
import (
"time"
"google.golang.org/grpc/codes"
)
type serverReporter struct {
metrics *ServerMetrics
rpcType grpcType
serviceName string
methodName string
startTime time.Time
}
func newServerReporter(m *ServerMetrics, rpcType grpcType, fullMethod string) *serverReporter {
r := &serverReporter{
metrics: m,
rpcType: rpcType,
}
if r.metrics.serverHandledHistogramEnabled {
r.startTime = time.Now()
}
r.serviceName, r.methodName = splitMethodName(fullMethod)
r.metrics.serverStartedCounter.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Inc()
return r
}
func (r *serverReporter) ReceivedMessage() {
r.metrics.serverStreamMsgReceived.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Inc()
}
func (r *serverReporter) SentMessage() {
r.metrics.serverStreamMsgSent.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Inc()
}
func (r *serverReporter) Handled(code codes.Code) {
r.metrics.serverHandledCounter.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName, code.String()).Inc()
if r.metrics.serverHandledHistogramEnabled {
r.metrics.serverHandledHistogram.WithLabelValues(string(r.rpcType), r.serviceName, r.methodName).Observe(time.Since(r.startTime).Seconds())
}
}
-50
View File
@@ -1,50 +0,0 @@
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package grpc_prometheus
import (
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
type grpcType string
const (
Unary grpcType = "unary"
ClientStream grpcType = "client_stream"
ServerStream grpcType = "server_stream"
BidiStream grpcType = "bidi_stream"
)
var (
allCodes = []codes.Code{
codes.OK, codes.Canceled, codes.Unknown, codes.InvalidArgument, codes.DeadlineExceeded, codes.NotFound,
codes.AlreadyExists, codes.PermissionDenied, codes.Unauthenticated, codes.ResourceExhausted,
codes.FailedPrecondition, codes.Aborted, codes.OutOfRange, codes.Unimplemented, codes.Internal,
codes.Unavailable, codes.DataLoss,
}
)
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"
}
func typeFromMethodInfo(mInfo *grpc.MethodInfo) grpcType {
if !mInfo.IsClientStream && !mInfo.IsServerStream {
return Unary
}
if mInfo.IsClientStream && !mInfo.IsServerStream {
return ClientStream
}
if !mInfo.IsClientStream && mInfo.IsServerStream {
return ServerStream
}
return BidiStream
}
+3 -2
View File
@@ -8,6 +8,7 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"github.com/container-storage-interface/spec/lib/go/csi"
@@ -108,9 +109,9 @@ func newNodePlugin(name string, p plugin.AddrPlugin, secrets SecretGetter) *node
// client from a grpc client. it exists separately so that testing code can
// substitute in fake clients without a grpc connection
func (np *nodePlugin) connect(ctx context.Context) error {
// even though this is a unix socket, we must set WithInsecure or the
// even though this is a unix socket, we must set insecure.NewCredentials or the
// connection will not be allowed.
cc, err := grpc.DialContext(ctx, np.socket, grpc.WithInsecure())
cc, err := grpc.DialContext(ctx, np.socket, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return err
}
+3 -3
View File
@@ -8,8 +8,8 @@ import (
"sync"
"time"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/moby/swarmkit/v2/api"
"github.com/moby/swarmkit/v2/internal/grpcmetrics"
"github.com/moby/swarmkit/v2/remotes"
"google.golang.org/grpc"
)
@@ -66,8 +66,8 @@ func (b *Broker) SelectRemote(dialOpts ...grpc.DialOption) (*Conn, error) {
// gRPC dialer connects to proxy first. Provide a custom dialer here avoid that.
// TODO(anshul) Add an option to configure this.
dialOpts = append(dialOpts,
grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor),
grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor),
grpc.WithUnaryInterceptor(grpcmetrics.Client.UnaryClientInterceptor()),
grpc.WithStreamInterceptor(grpcmetrics.Client.StreamClientInterceptor()),
grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout("tcp", addr, timeout)
}))
+15
View File
@@ -0,0 +1,15 @@
package grpcmetrics
import (
grpcprom "github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
"github.com/prometheus/client_golang/prometheus"
)
var (
Client = grpcprom.NewClientMetrics()
Server = grpcprom.NewServerMetrics()
)
func init() {
prometheus.MustRegister(Client, Server)
}
+3 -2
View File
@@ -6,11 +6,12 @@ import (
"fmt"
"net"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/moby/swarmkit/v2/api"
"github.com/moby/swarmkit/v2/internal/csi/capability"
"github.com/moby/swarmkit/v2/log"
@@ -93,7 +94,7 @@ func NewPlugin(p mobyplugin.AddrPlugin, provider SecretProvider) Plugin {
// connect is a private method that initializes a gRPC ClientConn and creates
// the IdentityClient and ControllerClient.
func (p *plugin) connect(ctx context.Context) error {
cc, err := grpc.DialContext(ctx, p.socket, grpc.WithInsecure())
cc, err := grpc.DialContext(ctx, p.socket, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return err
}
+27 -27
View File
@@ -4,6 +4,7 @@ import (
"context"
"crypto/tls"
"fmt"
"io"
"math"
"net"
"os"
@@ -16,11 +17,11 @@ import (
"github.com/docker/go-events"
gmetrics "github.com/docker/go-metrics"
gogotypes "github.com/gogo/protobuf/types"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/moby/swarmkit/v2/api"
"github.com/moby/swarmkit/v2/ca"
"github.com/moby/swarmkit/v2/connectionbroker"
"github.com/moby/swarmkit/v2/identity"
"github.com/moby/swarmkit/v2/internal/grpcmetrics"
"github.com/moby/swarmkit/v2/log"
"github.com/moby/swarmkit/v2/manager/allocator"
"github.com/moby/swarmkit/v2/manager/allocator/networkallocator"
@@ -249,6 +250,9 @@ func New(config *Config) (*Manager, error) {
}
raftNode := raft.NewNode(newNodeOpts)
streamMetricsInterceptor := grpcmetrics.Server.StreamServerInterceptor()
unaryMetricsInterceptor := grpcmetrics.Server.UnaryServerInterceptor()
// the interceptorWrappers are functions that wrap the prometheus grpc
// interceptor, and add some of code to log errors locally. one for stream
// and one for unary. this is needed because the grpc unary interceptor
@@ -263,30 +267,26 @@ func New(config *Config) (*Manager, error) {
// they are not automatically tested. If you modify them later, make _sure_
// that they are correct. If you add substantial side effects, abstract
// these out and test them!
unaryInterceptorWrapper := func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
// pass the call down into the grpc_prometheus interceptor
resp, err := grpc_prometheus.UnaryServerInterceptor(ctx, req, info, handler)
if err != nil {
log.G(ctx).WithField("rpc", info.FullMethod).WithError(err).Debug("error handling rpc")
}
return resp, err
}
streamInterceptorWrapper := func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
// we can't re-write a stream context, so don't bother creating a
// sub-context like in unary methods
// pass the call down into the grpc_prometheus interceptor
err := grpc_prometheus.StreamServerInterceptor(srv, ss, info, handler)
if err != nil {
log.G(ss.Context()).WithField("rpc", info.FullMethod).WithError(err).Debug("error handling streaming rpc")
}
return err
}
opts := []grpc.ServerOption{
grpc.Creds(config.SecurityConfig.ServerTLSCreds),
grpc.StreamInterceptor(streamInterceptorWrapper),
grpc.UnaryInterceptor(unaryInterceptorWrapper),
grpc.StreamInterceptor(func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
// pass the call down into the grpc_prometheus interceptor
err := streamMetricsInterceptor(srv, ss, info, handler)
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, context.Canceled) {
log.G(ss.Context()).WithField("rpc", info.FullMethod).WithError(err).Debug("error handling streaming rpc")
}
return err
}),
grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
// we can't re-write a stream context, so don't bother creating a
// sub-context like in unary methods
// pass the call down into the grpc_prometheus interceptor
resp, err := unaryMetricsInterceptor(ctx, req, info, handler)
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, context.Canceled) {
log.G(ctx).WithField("rpc", info.FullMethod).WithError(err).Debug("error handling rpc")
}
return resp, err
}),
grpc.MaxRecvMsgSize(transport.GRPCMaxMsgSize),
}
@@ -549,7 +549,7 @@ func (m *Manager) Run(parent context.Context) error {
api.RegisterLogBrokerServer(m.server, proxyLogBrokerAPI)
api.RegisterResourceAllocatorServer(m.server, proxyResourceAPI)
api.RegisterDispatcherServer(m.server, proxyDispatcherAPI)
grpc_prometheus.Register(m.server)
grpcmetrics.Server.InitializeMetrics(m.server)
api.RegisterControlServer(m.localserver, localProxyControlAPI)
api.RegisterWatchServer(m.localserver, m.watchServer)
@@ -560,7 +560,7 @@ func (m *Manager) Run(parent context.Context) error {
api.RegisterNodeCAServer(m.localserver, localProxyNodeCAAPI)
api.RegisterResourceAllocatorServer(m.localserver, localProxyResourceAPI)
api.RegisterLogBrokerServer(m.localserver, localProxyLogBrokerAPI)
grpc_prometheus.Register(m.localserver)
grpcmetrics.Server.InitializeMetrics(m.localserver)
healthServer.SetServingStatus("Raft", api.HealthCheckResponse_NOT_SERVING)
localHealthServer.SetServingStatus("ControlAPI", api.HealthCheckResponse_NOT_SERVING)
@@ -772,8 +772,8 @@ func (m *Manager) updateKEK(ctx context.Context, cluster *api.Cluster) error {
conn, err := grpc.Dial(
m.config.ControlAPI,
grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor),
grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor),
grpc.WithUnaryInterceptor(grpcmetrics.Client.UnaryClientInterceptor()),
grpc.WithStreamInterceptor(grpcmetrics.Client.StreamClientInterceptor()),
grpc.WithTransportCredentials(insecureCreds),
grpc.WithDialer(
func(addr string, timeout time.Duration) (net.Conn, error) {
@@ -9,14 +9,15 @@ import (
"sync"
"time"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"github.com/moby/swarmkit/v2/log"
"github.com/pkg/errors"
"go.etcd.io/raft/v3"
"go.etcd.io/raft/v3/raftpb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"github.com/moby/swarmkit/v2/internal/grpcmetrics"
"github.com/moby/swarmkit/v2/log"
)
// ErrIsNotFound indicates that peer was never added to transport.
@@ -334,14 +335,14 @@ func (t *Transport) longestActive() (*peer, error) {
func (t *Transport) dial(addr string) (*grpc.ClientConn, error) {
grpcOptions := []grpc.DialOption{
grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor),
grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor),
grpc.WithUnaryInterceptor(grpcmetrics.Client.UnaryClientInterceptor()),
grpc.WithStreamInterceptor(grpcmetrics.Client.StreamClientInterceptor()),
grpc.WithBackoffMaxDelay(8 * time.Second),
}
if t.config.Credentials != nil {
grpcOptions = append(grpcOptions, grpc.WithTransportCredentials(t.config.Credentials))
} else {
grpcOptions = append(grpcOptions, grpc.WithInsecure())
grpcOptions = append(grpcOptions, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
if t.config.SendTimeout > 0 {
+3 -3
View File
@@ -5,8 +5,8 @@ import (
"net"
"time"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/moby/swarmkit/v2/api"
"github.com/moby/swarmkit/v2/internal/grpcmetrics"
"github.com/moby/swarmkit/v2/manager/state"
"github.com/moby/swarmkit/v2/manager/state/store"
"google.golang.org/grpc"
@@ -19,8 +19,8 @@ func dial(addr string, _ string, creds credentials.TransportCredentials, timeout
grpcOptions := []grpc.DialOption{
grpc.WithBackoffMaxDelay(2 * time.Second),
grpc.WithTransportCredentials(creds),
grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor),
grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor),
grpc.WithUnaryInterceptor(grpcmetrics.Client.UnaryClientInterceptor()),
grpc.WithStreamInterceptor(grpcmetrics.Client.StreamClientInterceptor()),
grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout("tcp", addr, timeout)
}),
+3 -3
View File
@@ -16,7 +16,6 @@ import (
"time"
"github.com/docker/go-metrics"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/moby/swarmkit/v2/agent"
"github.com/moby/swarmkit/v2/agent/exec"
"github.com/moby/swarmkit/v2/api"
@@ -24,6 +23,7 @@ import (
"github.com/moby/swarmkit/v2/ca/keyutils"
"github.com/moby/swarmkit/v2/connectionbroker"
"github.com/moby/swarmkit/v2/identity"
"github.com/moby/swarmkit/v2/internal/grpcmetrics"
"github.com/moby/swarmkit/v2/ioutils"
"github.com/moby/swarmkit/v2/log"
"github.com/moby/swarmkit/v2/manager"
@@ -907,8 +907,8 @@ func (n *Node) loadSecurityConfig(ctx context.Context, paths *ca.SecurityConfigP
func (n *Node) initManagerConnection(ctx context.Context, ready chan<- struct{}) error {
opts := []grpc.DialOption{
grpc.WithUnaryInterceptor(grpc_prometheus.UnaryClientInterceptor),
grpc.WithStreamInterceptor(grpc_prometheus.StreamClientInterceptor),
grpc.WithUnaryInterceptor(grpcmetrics.Client.UnaryClientInterceptor()),
grpc.WithStreamInterceptor(grpcmetrics.Client.StreamClientInterceptor()),
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(math.MaxInt32)),
}
insecureCreds := credentials.NewTLS(&tls.Config{InsecureSkipVerify: true})
-118
View File
@@ -1,118 +0,0 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package context has been superseded by the standard library [context] package.
//
// Deprecated: Use the standard library context package instead.
package context
import (
"context" // standard library's context, as of Go 1.7
"time"
)
// A Context carries a deadline, a cancellation signal, and other values across
// API boundaries.
//
// Context's methods may be called by multiple goroutines simultaneously.
//
//go:fix inline
type Context = context.Context
// Canceled is the error returned by [Context.Err] when the context is canceled
// for some reason other than its deadline passing.
//
//go:fix inline
var Canceled = context.Canceled
// DeadlineExceeded is the error returned by [Context.Err] when the context is canceled
// due to its deadline passing.
//
//go:fix inline
var DeadlineExceeded = context.DeadlineExceeded
// Background returns a non-nil, empty Context. It is never canceled, has no
// values, and has no deadline. It is typically used by the main function,
// initialization, and tests, and as the top-level Context for incoming
// requests.
//
//go:fix inline
func Background() Context { return context.Background() }
// TODO returns a non-nil, empty Context. Code should use context.TODO when
// it's unclear which Context to use or it is not yet available (because the
// surrounding function has not yet been extended to accept a Context
// parameter).
//
//go:fix inline
func TODO() Context { return context.TODO() }
// A CancelFunc tells an operation to abandon its work.
// A CancelFunc does not wait for the work to stop.
// A CancelFunc may be called by multiple goroutines simultaneously.
// After the first call, subsequent calls to a CancelFunc do nothing.
type CancelFunc = context.CancelFunc
// WithCancel returns a derived context that points to the parent context
// but has a new Done channel. The returned context's Done channel is closed
// when the returned cancel function is called or when the parent context's
// Done channel is closed, whichever happens first.
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this [Context] complete.
//
//go:fix inline
func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
return context.WithCancel(parent)
}
// WithDeadline returns a derived context that points to the parent context
// but has the deadline adjusted to be no later than d. If the parent's
// deadline is already earlier than d, WithDeadline(parent, d) is semantically
// equivalent to parent. The returned [Context.Done] channel is closed when
// the deadline expires, when the returned cancel function is called,
// or when the parent context's Done channel is closed, whichever happens first.
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this [Context] complete.
//
//go:fix inline
func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
return context.WithDeadline(parent, d)
}
// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this [Context] complete:
//
// func slowOperationWithTimeout(ctx context.Context) (Result, error) {
// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
// defer cancel() // releases resources if slowOperation completes before timeout elapses
// return slowOperation(ctx)
// }
//
//go:fix inline
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
return context.WithTimeout(parent, timeout)
}
// WithValue returns a derived context that points to the parent Context.
// In the derived context, the value associated with key is val.
//
// Use context Values only for request-scoped data that transits processes and
// APIs, not for passing optional parameters to functions.
//
// The provided key must be comparable and should not be of type
// string or any other built-in type to avoid collisions between
// packages using context. Users of WithValue should define their own
// types for keys. To avoid allocating when assigning to an
// interface{}, context keys often have concrete type
// struct{}. Alternatively, exported context key variables' static
// type should be a pointer or interface.
//
//go:fix inline
func WithValue(parent Context, key, val interface{}) Context {
return context.WithValue(parent, key, val)
}
+18
View File
@@ -0,0 +1,18 @@
# Reflection
Package reflection implements server reflection service.
The service implemented is defined in: https://github.com/grpc/grpc/blob/master/src/proto/grpc/reflection/v1/reflection.proto.
To register server reflection on a gRPC server:
```go
import "google.golang.org/grpc/reflection"
s := grpc.NewServer()
pb.RegisterYourOwnServer(s, &server{})
// Register reflection service on gRPC server.
reflection.Register(s)
s.Serve(lis)
```
+57
View File
@@ -0,0 +1,57 @@
/*
*
* Copyright 2023 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package reflection
import (
"google.golang.org/grpc/reflection/internal"
v1reflectiongrpc "google.golang.org/grpc/reflection/grpc_reflection_v1"
v1reflectionpb "google.golang.org/grpc/reflection/grpc_reflection_v1"
v1alphareflectiongrpc "google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
)
// asV1Alpha returns an implementation of the v1alpha version of the reflection
// interface that delegates all calls to the given v1 version.
func asV1Alpha(svr v1reflectiongrpc.ServerReflectionServer) v1alphareflectiongrpc.ServerReflectionServer {
return v1AlphaServerImpl{svr: svr}
}
type v1AlphaServerImpl struct {
svr v1reflectiongrpc.ServerReflectionServer
}
func (s v1AlphaServerImpl) ServerReflectionInfo(stream v1alphareflectiongrpc.ServerReflection_ServerReflectionInfoServer) error {
return s.svr.ServerReflectionInfo(v1AlphaServerStreamAdapter{stream})
}
type v1AlphaServerStreamAdapter struct {
v1alphareflectiongrpc.ServerReflection_ServerReflectionInfoServer
}
func (s v1AlphaServerStreamAdapter) Send(response *v1reflectionpb.ServerReflectionResponse) error {
return s.ServerReflection_ServerReflectionInfoServer.Send(internal.V1ToV1AlphaResponse(response))
}
func (s v1AlphaServerStreamAdapter) Recv() (*v1reflectionpb.ServerReflectionRequest, error) {
resp, err := s.ServerReflection_ServerReflectionInfoServer.Recv()
if err != nil {
return nil, err
}
return internal.V1AlphaToV1Request(resp), nil
}
@@ -0,0 +1,777 @@
// Copyright 2016 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Service exported by server reflection. A more complete description of how
// server reflection works can be found at
// https://github.com/grpc/grpc/blob/master/doc/server-reflection.md
//
// The canonical version of this proto can be found at
// https://github.com/grpc/grpc-proto/blob/master/grpc/reflection/v1/reflection.proto
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.12
// protoc v5.27.1
// source: grpc/reflection/v1/reflection.proto
package grpc_reflection_v1
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// The message sent by the client when calling ServerReflectionInfo method.
type ServerReflectionRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Host string `protobuf:"bytes,1,opt,name=host,proto3" json:"host,omitempty"`
// To use reflection service, the client should set one of the following
// fields in message_request. The server distinguishes requests by their
// defined field and then handles them using corresponding methods.
//
// Types that are valid to be assigned to MessageRequest:
//
// *ServerReflectionRequest_FileByFilename
// *ServerReflectionRequest_FileContainingSymbol
// *ServerReflectionRequest_FileContainingExtension
// *ServerReflectionRequest_AllExtensionNumbersOfType
// *ServerReflectionRequest_ListServices
MessageRequest isServerReflectionRequest_MessageRequest `protobuf_oneof:"message_request"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ServerReflectionRequest) Reset() {
*x = ServerReflectionRequest{}
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ServerReflectionRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServerReflectionRequest) ProtoMessage() {}
func (x *ServerReflectionRequest) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ServerReflectionRequest.ProtoReflect.Descriptor instead.
func (*ServerReflectionRequest) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1_reflection_proto_rawDescGZIP(), []int{0}
}
func (x *ServerReflectionRequest) GetHost() string {
if x != nil {
return x.Host
}
return ""
}
func (x *ServerReflectionRequest) GetMessageRequest() isServerReflectionRequest_MessageRequest {
if x != nil {
return x.MessageRequest
}
return nil
}
func (x *ServerReflectionRequest) GetFileByFilename() string {
if x != nil {
if x, ok := x.MessageRequest.(*ServerReflectionRequest_FileByFilename); ok {
return x.FileByFilename
}
}
return ""
}
func (x *ServerReflectionRequest) GetFileContainingSymbol() string {
if x != nil {
if x, ok := x.MessageRequest.(*ServerReflectionRequest_FileContainingSymbol); ok {
return x.FileContainingSymbol
}
}
return ""
}
func (x *ServerReflectionRequest) GetFileContainingExtension() *ExtensionRequest {
if x != nil {
if x, ok := x.MessageRequest.(*ServerReflectionRequest_FileContainingExtension); ok {
return x.FileContainingExtension
}
}
return nil
}
func (x *ServerReflectionRequest) GetAllExtensionNumbersOfType() string {
if x != nil {
if x, ok := x.MessageRequest.(*ServerReflectionRequest_AllExtensionNumbersOfType); ok {
return x.AllExtensionNumbersOfType
}
}
return ""
}
func (x *ServerReflectionRequest) GetListServices() string {
if x != nil {
if x, ok := x.MessageRequest.(*ServerReflectionRequest_ListServices); ok {
return x.ListServices
}
}
return ""
}
type isServerReflectionRequest_MessageRequest interface {
isServerReflectionRequest_MessageRequest()
}
type ServerReflectionRequest_FileByFilename struct {
// Find a proto file by the file name.
FileByFilename string `protobuf:"bytes,3,opt,name=file_by_filename,json=fileByFilename,proto3,oneof"`
}
type ServerReflectionRequest_FileContainingSymbol struct {
// Find the proto file that declares the given fully-qualified symbol name.
// This field should be a fully-qualified symbol name
// (e.g. <package>.<service>[.<method>] or <package>.<type>).
FileContainingSymbol string `protobuf:"bytes,4,opt,name=file_containing_symbol,json=fileContainingSymbol,proto3,oneof"`
}
type ServerReflectionRequest_FileContainingExtension struct {
// Find the proto file which defines an extension extending the given
// message type with the given field number.
FileContainingExtension *ExtensionRequest `protobuf:"bytes,5,opt,name=file_containing_extension,json=fileContainingExtension,proto3,oneof"`
}
type ServerReflectionRequest_AllExtensionNumbersOfType struct {
// Finds the tag numbers used by all known extensions of the given message
// type, and appends them to ExtensionNumberResponse in an undefined order.
// Its corresponding method is best-effort: it's not guaranteed that the
// reflection service will implement this method, and it's not guaranteed
// that this method will provide all extensions. Returns
// StatusCode::UNIMPLEMENTED if it's not implemented.
// This field should be a fully-qualified type name. The format is
// <package>.<type>
AllExtensionNumbersOfType string `protobuf:"bytes,6,opt,name=all_extension_numbers_of_type,json=allExtensionNumbersOfType,proto3,oneof"`
}
type ServerReflectionRequest_ListServices struct {
// List the full names of registered services. The content will not be
// checked.
ListServices string `protobuf:"bytes,7,opt,name=list_services,json=listServices,proto3,oneof"`
}
func (*ServerReflectionRequest_FileByFilename) isServerReflectionRequest_MessageRequest() {}
func (*ServerReflectionRequest_FileContainingSymbol) isServerReflectionRequest_MessageRequest() {}
func (*ServerReflectionRequest_FileContainingExtension) isServerReflectionRequest_MessageRequest() {}
func (*ServerReflectionRequest_AllExtensionNumbersOfType) isServerReflectionRequest_MessageRequest() {
}
func (*ServerReflectionRequest_ListServices) isServerReflectionRequest_MessageRequest() {}
// The type name and extension number sent by the client when requesting
// file_containing_extension.
type ExtensionRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Fully-qualified type name. The format should be <package>.<type>
ContainingType string `protobuf:"bytes,1,opt,name=containing_type,json=containingType,proto3" json:"containing_type,omitempty"`
ExtensionNumber int32 `protobuf:"varint,2,opt,name=extension_number,json=extensionNumber,proto3" json:"extension_number,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ExtensionRequest) Reset() {
*x = ExtensionRequest{}
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ExtensionRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ExtensionRequest) ProtoMessage() {}
func (x *ExtensionRequest) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ExtensionRequest.ProtoReflect.Descriptor instead.
func (*ExtensionRequest) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1_reflection_proto_rawDescGZIP(), []int{1}
}
func (x *ExtensionRequest) GetContainingType() string {
if x != nil {
return x.ContainingType
}
return ""
}
func (x *ExtensionRequest) GetExtensionNumber() int32 {
if x != nil {
return x.ExtensionNumber
}
return 0
}
// The message sent by the server to answer ServerReflectionInfo method.
type ServerReflectionResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
ValidHost string `protobuf:"bytes,1,opt,name=valid_host,json=validHost,proto3" json:"valid_host,omitempty"`
OriginalRequest *ServerReflectionRequest `protobuf:"bytes,2,opt,name=original_request,json=originalRequest,proto3" json:"original_request,omitempty"`
// The server sets one of the following fields according to the message_request
// in the request.
//
// Types that are valid to be assigned to MessageResponse:
//
// *ServerReflectionResponse_FileDescriptorResponse
// *ServerReflectionResponse_AllExtensionNumbersResponse
// *ServerReflectionResponse_ListServicesResponse
// *ServerReflectionResponse_ErrorResponse
MessageResponse isServerReflectionResponse_MessageResponse `protobuf_oneof:"message_response"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ServerReflectionResponse) Reset() {
*x = ServerReflectionResponse{}
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ServerReflectionResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServerReflectionResponse) ProtoMessage() {}
func (x *ServerReflectionResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ServerReflectionResponse.ProtoReflect.Descriptor instead.
func (*ServerReflectionResponse) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1_reflection_proto_rawDescGZIP(), []int{2}
}
func (x *ServerReflectionResponse) GetValidHost() string {
if x != nil {
return x.ValidHost
}
return ""
}
func (x *ServerReflectionResponse) GetOriginalRequest() *ServerReflectionRequest {
if x != nil {
return x.OriginalRequest
}
return nil
}
func (x *ServerReflectionResponse) GetMessageResponse() isServerReflectionResponse_MessageResponse {
if x != nil {
return x.MessageResponse
}
return nil
}
func (x *ServerReflectionResponse) GetFileDescriptorResponse() *FileDescriptorResponse {
if x != nil {
if x, ok := x.MessageResponse.(*ServerReflectionResponse_FileDescriptorResponse); ok {
return x.FileDescriptorResponse
}
}
return nil
}
func (x *ServerReflectionResponse) GetAllExtensionNumbersResponse() *ExtensionNumberResponse {
if x != nil {
if x, ok := x.MessageResponse.(*ServerReflectionResponse_AllExtensionNumbersResponse); ok {
return x.AllExtensionNumbersResponse
}
}
return nil
}
func (x *ServerReflectionResponse) GetListServicesResponse() *ListServiceResponse {
if x != nil {
if x, ok := x.MessageResponse.(*ServerReflectionResponse_ListServicesResponse); ok {
return x.ListServicesResponse
}
}
return nil
}
func (x *ServerReflectionResponse) GetErrorResponse() *ErrorResponse {
if x != nil {
if x, ok := x.MessageResponse.(*ServerReflectionResponse_ErrorResponse); ok {
return x.ErrorResponse
}
}
return nil
}
type isServerReflectionResponse_MessageResponse interface {
isServerReflectionResponse_MessageResponse()
}
type ServerReflectionResponse_FileDescriptorResponse struct {
// This message is used to answer file_by_filename, file_containing_symbol,
// file_containing_extension requests with transitive dependencies.
// As the repeated label is not allowed in oneof fields, we use a
// FileDescriptorResponse message to encapsulate the repeated fields.
// The reflection service is allowed to avoid sending FileDescriptorProtos
// that were previously sent in response to earlier requests in the stream.
FileDescriptorResponse *FileDescriptorResponse `protobuf:"bytes,4,opt,name=file_descriptor_response,json=fileDescriptorResponse,proto3,oneof"`
}
type ServerReflectionResponse_AllExtensionNumbersResponse struct {
// This message is used to answer all_extension_numbers_of_type requests.
AllExtensionNumbersResponse *ExtensionNumberResponse `protobuf:"bytes,5,opt,name=all_extension_numbers_response,json=allExtensionNumbersResponse,proto3,oneof"`
}
type ServerReflectionResponse_ListServicesResponse struct {
// This message is used to answer list_services requests.
ListServicesResponse *ListServiceResponse `protobuf:"bytes,6,opt,name=list_services_response,json=listServicesResponse,proto3,oneof"`
}
type ServerReflectionResponse_ErrorResponse struct {
// This message is used when an error occurs.
ErrorResponse *ErrorResponse `protobuf:"bytes,7,opt,name=error_response,json=errorResponse,proto3,oneof"`
}
func (*ServerReflectionResponse_FileDescriptorResponse) isServerReflectionResponse_MessageResponse() {
}
func (*ServerReflectionResponse_AllExtensionNumbersResponse) isServerReflectionResponse_MessageResponse() {
}
func (*ServerReflectionResponse_ListServicesResponse) isServerReflectionResponse_MessageResponse() {}
func (*ServerReflectionResponse_ErrorResponse) isServerReflectionResponse_MessageResponse() {}
// Serialized FileDescriptorProto messages sent by the server answering
// a file_by_filename, file_containing_symbol, or file_containing_extension
// request.
type FileDescriptorResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Serialized FileDescriptorProto messages. We avoid taking a dependency on
// descriptor.proto, which uses proto2 only features, by making them opaque
// bytes instead.
FileDescriptorProto [][]byte `protobuf:"bytes,1,rep,name=file_descriptor_proto,json=fileDescriptorProto,proto3" json:"file_descriptor_proto,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *FileDescriptorResponse) Reset() {
*x = FileDescriptorResponse{}
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FileDescriptorResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FileDescriptorResponse) ProtoMessage() {}
func (x *FileDescriptorResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use FileDescriptorResponse.ProtoReflect.Descriptor instead.
func (*FileDescriptorResponse) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1_reflection_proto_rawDescGZIP(), []int{3}
}
func (x *FileDescriptorResponse) GetFileDescriptorProto() [][]byte {
if x != nil {
return x.FileDescriptorProto
}
return nil
}
// A list of extension numbers sent by the server answering
// all_extension_numbers_of_type request.
type ExtensionNumberResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Full name of the base type, including the package name. The format
// is <package>.<type>
BaseTypeName string `protobuf:"bytes,1,opt,name=base_type_name,json=baseTypeName,proto3" json:"base_type_name,omitempty"`
ExtensionNumber []int32 `protobuf:"varint,2,rep,packed,name=extension_number,json=extensionNumber,proto3" json:"extension_number,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ExtensionNumberResponse) Reset() {
*x = ExtensionNumberResponse{}
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ExtensionNumberResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ExtensionNumberResponse) ProtoMessage() {}
func (x *ExtensionNumberResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ExtensionNumberResponse.ProtoReflect.Descriptor instead.
func (*ExtensionNumberResponse) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1_reflection_proto_rawDescGZIP(), []int{4}
}
func (x *ExtensionNumberResponse) GetBaseTypeName() string {
if x != nil {
return x.BaseTypeName
}
return ""
}
func (x *ExtensionNumberResponse) GetExtensionNumber() []int32 {
if x != nil {
return x.ExtensionNumber
}
return nil
}
// A list of ServiceResponse sent by the server answering list_services request.
type ListServiceResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The information of each service may be expanded in the future, so we use
// ServiceResponse message to encapsulate it.
Service []*ServiceResponse `protobuf:"bytes,1,rep,name=service,proto3" json:"service,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ListServiceResponse) Reset() {
*x = ListServiceResponse{}
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ListServiceResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListServiceResponse) ProtoMessage() {}
func (x *ListServiceResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ListServiceResponse.ProtoReflect.Descriptor instead.
func (*ListServiceResponse) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1_reflection_proto_rawDescGZIP(), []int{5}
}
func (x *ListServiceResponse) GetService() []*ServiceResponse {
if x != nil {
return x.Service
}
return nil
}
// The information of a single service used by ListServiceResponse to answer
// list_services request.
type ServiceResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Full name of a registered service, including its package name. The format
// is <package>.<service>
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ServiceResponse) Reset() {
*x = ServiceResponse{}
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ServiceResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServiceResponse) ProtoMessage() {}
func (x *ServiceResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ServiceResponse.ProtoReflect.Descriptor instead.
func (*ServiceResponse) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1_reflection_proto_rawDescGZIP(), []int{6}
}
func (x *ServiceResponse) GetName() string {
if x != nil {
return x.Name
}
return ""
}
// The error code and error message sent by the server when an error occurs.
type ErrorResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// This field uses the error codes defined in grpc::StatusCode.
ErrorCode int32 `protobuf:"varint,1,opt,name=error_code,json=errorCode,proto3" json:"error_code,omitempty"`
ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ErrorResponse) Reset() {
*x = ErrorResponse{}
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ErrorResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ErrorResponse) ProtoMessage() {}
func (x *ErrorResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1_reflection_proto_msgTypes[7]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ErrorResponse.ProtoReflect.Descriptor instead.
func (*ErrorResponse) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1_reflection_proto_rawDescGZIP(), []int{7}
}
func (x *ErrorResponse) GetErrorCode() int32 {
if x != nil {
return x.ErrorCode
}
return 0
}
func (x *ErrorResponse) GetErrorMessage() string {
if x != nil {
return x.ErrorMessage
}
return ""
}
var File_grpc_reflection_v1_reflection_proto protoreflect.FileDescriptor
const file_grpc_reflection_v1_reflection_proto_rawDesc = "" +
"\n" +
"#grpc/reflection/v1/reflection.proto\x12\x12grpc.reflection.v1\"\xf3\x02\n" +
"\x17ServerReflectionRequest\x12\x12\n" +
"\x04host\x18\x01 \x01(\tR\x04host\x12*\n" +
"\x10file_by_filename\x18\x03 \x01(\tH\x00R\x0efileByFilename\x126\n" +
"\x16file_containing_symbol\x18\x04 \x01(\tH\x00R\x14fileContainingSymbol\x12b\n" +
"\x19file_containing_extension\x18\x05 \x01(\v2$.grpc.reflection.v1.ExtensionRequestH\x00R\x17fileContainingExtension\x12B\n" +
"\x1dall_extension_numbers_of_type\x18\x06 \x01(\tH\x00R\x19allExtensionNumbersOfType\x12%\n" +
"\rlist_services\x18\a \x01(\tH\x00R\flistServicesB\x11\n" +
"\x0fmessage_request\"f\n" +
"\x10ExtensionRequest\x12'\n" +
"\x0fcontaining_type\x18\x01 \x01(\tR\x0econtainingType\x12)\n" +
"\x10extension_number\x18\x02 \x01(\x05R\x0fextensionNumber\"\xae\x04\n" +
"\x18ServerReflectionResponse\x12\x1d\n" +
"\n" +
"valid_host\x18\x01 \x01(\tR\tvalidHost\x12V\n" +
"\x10original_request\x18\x02 \x01(\v2+.grpc.reflection.v1.ServerReflectionRequestR\x0foriginalRequest\x12f\n" +
"\x18file_descriptor_response\x18\x04 \x01(\v2*.grpc.reflection.v1.FileDescriptorResponseH\x00R\x16fileDescriptorResponse\x12r\n" +
"\x1eall_extension_numbers_response\x18\x05 \x01(\v2+.grpc.reflection.v1.ExtensionNumberResponseH\x00R\x1ballExtensionNumbersResponse\x12_\n" +
"\x16list_services_response\x18\x06 \x01(\v2'.grpc.reflection.v1.ListServiceResponseH\x00R\x14listServicesResponse\x12J\n" +
"\x0eerror_response\x18\a \x01(\v2!.grpc.reflection.v1.ErrorResponseH\x00R\rerrorResponseB\x12\n" +
"\x10message_response\"L\n" +
"\x16FileDescriptorResponse\x122\n" +
"\x15file_descriptor_proto\x18\x01 \x03(\fR\x13fileDescriptorProto\"j\n" +
"\x17ExtensionNumberResponse\x12$\n" +
"\x0ebase_type_name\x18\x01 \x01(\tR\fbaseTypeName\x12)\n" +
"\x10extension_number\x18\x02 \x03(\x05R\x0fextensionNumber\"T\n" +
"\x13ListServiceResponse\x12=\n" +
"\aservice\x18\x01 \x03(\v2#.grpc.reflection.v1.ServiceResponseR\aservice\"%\n" +
"\x0fServiceResponse\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\"S\n" +
"\rErrorResponse\x12\x1d\n" +
"\n" +
"error_code\x18\x01 \x01(\x05R\terrorCode\x12#\n" +
"\rerror_message\x18\x02 \x01(\tR\ferrorMessage2\x89\x01\n" +
"\x10ServerReflection\x12u\n" +
"\x14ServerReflectionInfo\x12+.grpc.reflection.v1.ServerReflectionRequest\x1a,.grpc.reflection.v1.ServerReflectionResponse(\x010\x01Bf\n" +
"\x15io.grpc.reflection.v1B\x15ServerReflectionProtoP\x01Z4google.golang.org/grpc/reflection/grpc_reflection_v1b\x06proto3"
var (
file_grpc_reflection_v1_reflection_proto_rawDescOnce sync.Once
file_grpc_reflection_v1_reflection_proto_rawDescData []byte
)
func file_grpc_reflection_v1_reflection_proto_rawDescGZIP() []byte {
file_grpc_reflection_v1_reflection_proto_rawDescOnce.Do(func() {
file_grpc_reflection_v1_reflection_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_grpc_reflection_v1_reflection_proto_rawDesc), len(file_grpc_reflection_v1_reflection_proto_rawDesc)))
})
return file_grpc_reflection_v1_reflection_proto_rawDescData
}
var file_grpc_reflection_v1_reflection_proto_msgTypes = make([]protoimpl.MessageInfo, 8)
var file_grpc_reflection_v1_reflection_proto_goTypes = []any{
(*ServerReflectionRequest)(nil), // 0: grpc.reflection.v1.ServerReflectionRequest
(*ExtensionRequest)(nil), // 1: grpc.reflection.v1.ExtensionRequest
(*ServerReflectionResponse)(nil), // 2: grpc.reflection.v1.ServerReflectionResponse
(*FileDescriptorResponse)(nil), // 3: grpc.reflection.v1.FileDescriptorResponse
(*ExtensionNumberResponse)(nil), // 4: grpc.reflection.v1.ExtensionNumberResponse
(*ListServiceResponse)(nil), // 5: grpc.reflection.v1.ListServiceResponse
(*ServiceResponse)(nil), // 6: grpc.reflection.v1.ServiceResponse
(*ErrorResponse)(nil), // 7: grpc.reflection.v1.ErrorResponse
}
var file_grpc_reflection_v1_reflection_proto_depIdxs = []int32{
1, // 0: grpc.reflection.v1.ServerReflectionRequest.file_containing_extension:type_name -> grpc.reflection.v1.ExtensionRequest
0, // 1: grpc.reflection.v1.ServerReflectionResponse.original_request:type_name -> grpc.reflection.v1.ServerReflectionRequest
3, // 2: grpc.reflection.v1.ServerReflectionResponse.file_descriptor_response:type_name -> grpc.reflection.v1.FileDescriptorResponse
4, // 3: grpc.reflection.v1.ServerReflectionResponse.all_extension_numbers_response:type_name -> grpc.reflection.v1.ExtensionNumberResponse
5, // 4: grpc.reflection.v1.ServerReflectionResponse.list_services_response:type_name -> grpc.reflection.v1.ListServiceResponse
7, // 5: grpc.reflection.v1.ServerReflectionResponse.error_response:type_name -> grpc.reflection.v1.ErrorResponse
6, // 6: grpc.reflection.v1.ListServiceResponse.service:type_name -> grpc.reflection.v1.ServiceResponse
0, // 7: grpc.reflection.v1.ServerReflection.ServerReflectionInfo:input_type -> grpc.reflection.v1.ServerReflectionRequest
2, // 8: grpc.reflection.v1.ServerReflection.ServerReflectionInfo:output_type -> grpc.reflection.v1.ServerReflectionResponse
8, // [8:9] is the sub-list for method output_type
7, // [7:8] is the sub-list for method input_type
7, // [7:7] is the sub-list for extension type_name
7, // [7:7] is the sub-list for extension extendee
0, // [0:7] is the sub-list for field type_name
}
func init() { file_grpc_reflection_v1_reflection_proto_init() }
func file_grpc_reflection_v1_reflection_proto_init() {
if File_grpc_reflection_v1_reflection_proto != nil {
return
}
file_grpc_reflection_v1_reflection_proto_msgTypes[0].OneofWrappers = []any{
(*ServerReflectionRequest_FileByFilename)(nil),
(*ServerReflectionRequest_FileContainingSymbol)(nil),
(*ServerReflectionRequest_FileContainingExtension)(nil),
(*ServerReflectionRequest_AllExtensionNumbersOfType)(nil),
(*ServerReflectionRequest_ListServices)(nil),
}
file_grpc_reflection_v1_reflection_proto_msgTypes[2].OneofWrappers = []any{
(*ServerReflectionResponse_FileDescriptorResponse)(nil),
(*ServerReflectionResponse_AllExtensionNumbersResponse)(nil),
(*ServerReflectionResponse_ListServicesResponse)(nil),
(*ServerReflectionResponse_ErrorResponse)(nil),
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_grpc_reflection_v1_reflection_proto_rawDesc), len(file_grpc_reflection_v1_reflection_proto_rawDesc)),
NumEnums: 0,
NumMessages: 8,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_grpc_reflection_v1_reflection_proto_goTypes,
DependencyIndexes: file_grpc_reflection_v1_reflection_proto_depIdxs,
MessageInfos: file_grpc_reflection_v1_reflection_proto_msgTypes,
}.Build()
File_grpc_reflection_v1_reflection_proto = out.File
file_grpc_reflection_v1_reflection_proto_goTypes = nil
file_grpc_reflection_v1_reflection_proto_depIdxs = nil
}
@@ -0,0 +1,138 @@
// Copyright 2016 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Service exported by server reflection. A more complete description of how
// server reflection works can be found at
// https://github.com/grpc/grpc/blob/master/doc/server-reflection.md
//
// The canonical version of this proto can be found at
// https://github.com/grpc/grpc-proto/blob/master/grpc/reflection/v1/reflection.proto
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
// - protoc v5.27.1
// source: grpc/reflection/v1/reflection.proto
package grpc_reflection_v1
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
ServerReflection_ServerReflectionInfo_FullMethodName = "/grpc.reflection.v1.ServerReflection/ServerReflectionInfo"
)
// ServerReflectionClient is the client API for ServerReflection service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type ServerReflectionClient interface {
// The reflection service is structured as a bidirectional stream, ensuring
// all related requests go to a single server.
ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[ServerReflectionRequest, ServerReflectionResponse], error)
}
type serverReflectionClient struct {
cc grpc.ClientConnInterface
}
func NewServerReflectionClient(cc grpc.ClientConnInterface) ServerReflectionClient {
return &serverReflectionClient{cc}
}
func (c *serverReflectionClient) ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[ServerReflectionRequest, ServerReflectionResponse], error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
stream, err := c.cc.NewStream(ctx, &ServerReflection_ServiceDesc.Streams[0], ServerReflection_ServerReflectionInfo_FullMethodName, cOpts...)
if err != nil {
return nil, err
}
x := &grpc.GenericClientStream[ServerReflectionRequest, ServerReflectionResponse]{ClientStream: stream}
return x, nil
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type ServerReflection_ServerReflectionInfoClient = grpc.BidiStreamingClient[ServerReflectionRequest, ServerReflectionResponse]
// ServerReflectionServer is the server API for ServerReflection service.
// All implementations should embed UnimplementedServerReflectionServer
// for forward compatibility.
type ServerReflectionServer interface {
// The reflection service is structured as a bidirectional stream, ensuring
// all related requests go to a single server.
ServerReflectionInfo(grpc.BidiStreamingServer[ServerReflectionRequest, ServerReflectionResponse]) error
}
// UnimplementedServerReflectionServer should be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedServerReflectionServer struct{}
func (UnimplementedServerReflectionServer) ServerReflectionInfo(grpc.BidiStreamingServer[ServerReflectionRequest, ServerReflectionResponse]) error {
return status.Error(codes.Unimplemented, "method ServerReflectionInfo not implemented")
}
func (UnimplementedServerReflectionServer) testEmbeddedByValue() {}
// UnsafeServerReflectionServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to ServerReflectionServer will
// result in compilation errors.
type UnsafeServerReflectionServer interface {
mustEmbedUnimplementedServerReflectionServer()
}
func RegisterServerReflectionServer(s grpc.ServiceRegistrar, srv ServerReflectionServer) {
// If the following call panics, it indicates UnimplementedServerReflectionServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&ServerReflection_ServiceDesc, srv)
}
func _ServerReflection_ServerReflectionInfo_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(ServerReflectionServer).ServerReflectionInfo(&grpc.GenericServerStream[ServerReflectionRequest, ServerReflectionResponse]{ServerStream: stream})
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type ServerReflection_ServerReflectionInfoServer = grpc.BidiStreamingServer[ServerReflectionRequest, ServerReflectionResponse]
// ServerReflection_ServiceDesc is the grpc.ServiceDesc for ServerReflection service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var ServerReflection_ServiceDesc = grpc.ServiceDesc{
ServiceName: "grpc.reflection.v1.ServerReflection",
HandlerType: (*ServerReflectionServer)(nil),
Methods: []grpc.MethodDesc{},
Streams: []grpc.StreamDesc{
{
StreamName: "ServerReflectionInfo",
Handler: _ServerReflection_ServerReflectionInfo_Handler,
ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "grpc/reflection/v1/reflection.proto",
}
@@ -0,0 +1,847 @@
// Copyright 2016 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Service exported by server reflection
// Warning: this entire file is deprecated. Use this instead:
// https://github.com/grpc/grpc-proto/blob/master/grpc/reflection/v1/reflection.proto
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.12
// protoc v5.27.1
// grpc/reflection/v1alpha/reflection.proto is a deprecated file.
package grpc_reflection_v1alpha
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// The message sent by the client when calling ServerReflectionInfo method.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
type ServerReflectionRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
Host string `protobuf:"bytes,1,opt,name=host,proto3" json:"host,omitempty"`
// To use reflection service, the client should set one of the following
// fields in message_request. The server distinguishes requests by their
// defined field and then handles them using corresponding methods.
//
// Types that are valid to be assigned to MessageRequest:
//
// *ServerReflectionRequest_FileByFilename
// *ServerReflectionRequest_FileContainingSymbol
// *ServerReflectionRequest_FileContainingExtension
// *ServerReflectionRequest_AllExtensionNumbersOfType
// *ServerReflectionRequest_ListServices
MessageRequest isServerReflectionRequest_MessageRequest `protobuf_oneof:"message_request"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ServerReflectionRequest) Reset() {
*x = ServerReflectionRequest{}
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ServerReflectionRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServerReflectionRequest) ProtoMessage() {}
func (x *ServerReflectionRequest) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ServerReflectionRequest.ProtoReflect.Descriptor instead.
func (*ServerReflectionRequest) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{0}
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServerReflectionRequest) GetHost() string {
if x != nil {
return x.Host
}
return ""
}
func (x *ServerReflectionRequest) GetMessageRequest() isServerReflectionRequest_MessageRequest {
if x != nil {
return x.MessageRequest
}
return nil
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServerReflectionRequest) GetFileByFilename() string {
if x != nil {
if x, ok := x.MessageRequest.(*ServerReflectionRequest_FileByFilename); ok {
return x.FileByFilename
}
}
return ""
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServerReflectionRequest) GetFileContainingSymbol() string {
if x != nil {
if x, ok := x.MessageRequest.(*ServerReflectionRequest_FileContainingSymbol); ok {
return x.FileContainingSymbol
}
}
return ""
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServerReflectionRequest) GetFileContainingExtension() *ExtensionRequest {
if x != nil {
if x, ok := x.MessageRequest.(*ServerReflectionRequest_FileContainingExtension); ok {
return x.FileContainingExtension
}
}
return nil
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServerReflectionRequest) GetAllExtensionNumbersOfType() string {
if x != nil {
if x, ok := x.MessageRequest.(*ServerReflectionRequest_AllExtensionNumbersOfType); ok {
return x.AllExtensionNumbersOfType
}
}
return ""
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServerReflectionRequest) GetListServices() string {
if x != nil {
if x, ok := x.MessageRequest.(*ServerReflectionRequest_ListServices); ok {
return x.ListServices
}
}
return ""
}
type isServerReflectionRequest_MessageRequest interface {
isServerReflectionRequest_MessageRequest()
}
type ServerReflectionRequest_FileByFilename struct {
// Find a proto file by the file name.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
FileByFilename string `protobuf:"bytes,3,opt,name=file_by_filename,json=fileByFilename,proto3,oneof"`
}
type ServerReflectionRequest_FileContainingSymbol struct {
// Find the proto file that declares the given fully-qualified symbol name.
// This field should be a fully-qualified symbol name
// (e.g. <package>.<service>[.<method>] or <package>.<type>).
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
FileContainingSymbol string `protobuf:"bytes,4,opt,name=file_containing_symbol,json=fileContainingSymbol,proto3,oneof"`
}
type ServerReflectionRequest_FileContainingExtension struct {
// Find the proto file which defines an extension extending the given
// message type with the given field number.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
FileContainingExtension *ExtensionRequest `protobuf:"bytes,5,opt,name=file_containing_extension,json=fileContainingExtension,proto3,oneof"`
}
type ServerReflectionRequest_AllExtensionNumbersOfType struct {
// Finds the tag numbers used by all known extensions of extendee_type, and
// appends them to ExtensionNumberResponse in an undefined order.
// Its corresponding method is best-effort: it's not guaranteed that the
// reflection service will implement this method, and it's not guaranteed
// that this method will provide all extensions. Returns
// StatusCode::UNIMPLEMENTED if it's not implemented.
// This field should be a fully-qualified type name. The format is
// <package>.<type>
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
AllExtensionNumbersOfType string `protobuf:"bytes,6,opt,name=all_extension_numbers_of_type,json=allExtensionNumbersOfType,proto3,oneof"`
}
type ServerReflectionRequest_ListServices struct {
// List the full names of registered services. The content will not be
// checked.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
ListServices string `protobuf:"bytes,7,opt,name=list_services,json=listServices,proto3,oneof"`
}
func (*ServerReflectionRequest_FileByFilename) isServerReflectionRequest_MessageRequest() {}
func (*ServerReflectionRequest_FileContainingSymbol) isServerReflectionRequest_MessageRequest() {}
func (*ServerReflectionRequest_FileContainingExtension) isServerReflectionRequest_MessageRequest() {}
func (*ServerReflectionRequest_AllExtensionNumbersOfType) isServerReflectionRequest_MessageRequest() {
}
func (*ServerReflectionRequest_ListServices) isServerReflectionRequest_MessageRequest() {}
// The type name and extension number sent by the client when requesting
// file_containing_extension.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
type ExtensionRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Fully-qualified type name. The format should be <package>.<type>
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
ContainingType string `protobuf:"bytes,1,opt,name=containing_type,json=containingType,proto3" json:"containing_type,omitempty"`
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
ExtensionNumber int32 `protobuf:"varint,2,opt,name=extension_number,json=extensionNumber,proto3" json:"extension_number,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ExtensionRequest) Reset() {
*x = ExtensionRequest{}
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ExtensionRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ExtensionRequest) ProtoMessage() {}
func (x *ExtensionRequest) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ExtensionRequest.ProtoReflect.Descriptor instead.
func (*ExtensionRequest) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{1}
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ExtensionRequest) GetContainingType() string {
if x != nil {
return x.ContainingType
}
return ""
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ExtensionRequest) GetExtensionNumber() int32 {
if x != nil {
return x.ExtensionNumber
}
return 0
}
// The message sent by the server to answer ServerReflectionInfo method.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
type ServerReflectionResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
ValidHost string `protobuf:"bytes,1,opt,name=valid_host,json=validHost,proto3" json:"valid_host,omitempty"`
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
OriginalRequest *ServerReflectionRequest `protobuf:"bytes,2,opt,name=original_request,json=originalRequest,proto3" json:"original_request,omitempty"`
// The server set one of the following fields according to the message_request
// in the request.
//
// Types that are valid to be assigned to MessageResponse:
//
// *ServerReflectionResponse_FileDescriptorResponse
// *ServerReflectionResponse_AllExtensionNumbersResponse
// *ServerReflectionResponse_ListServicesResponse
// *ServerReflectionResponse_ErrorResponse
MessageResponse isServerReflectionResponse_MessageResponse `protobuf_oneof:"message_response"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ServerReflectionResponse) Reset() {
*x = ServerReflectionResponse{}
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ServerReflectionResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServerReflectionResponse) ProtoMessage() {}
func (x *ServerReflectionResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ServerReflectionResponse.ProtoReflect.Descriptor instead.
func (*ServerReflectionResponse) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{2}
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServerReflectionResponse) GetValidHost() string {
if x != nil {
return x.ValidHost
}
return ""
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServerReflectionResponse) GetOriginalRequest() *ServerReflectionRequest {
if x != nil {
return x.OriginalRequest
}
return nil
}
func (x *ServerReflectionResponse) GetMessageResponse() isServerReflectionResponse_MessageResponse {
if x != nil {
return x.MessageResponse
}
return nil
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServerReflectionResponse) GetFileDescriptorResponse() *FileDescriptorResponse {
if x != nil {
if x, ok := x.MessageResponse.(*ServerReflectionResponse_FileDescriptorResponse); ok {
return x.FileDescriptorResponse
}
}
return nil
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServerReflectionResponse) GetAllExtensionNumbersResponse() *ExtensionNumberResponse {
if x != nil {
if x, ok := x.MessageResponse.(*ServerReflectionResponse_AllExtensionNumbersResponse); ok {
return x.AllExtensionNumbersResponse
}
}
return nil
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServerReflectionResponse) GetListServicesResponse() *ListServiceResponse {
if x != nil {
if x, ok := x.MessageResponse.(*ServerReflectionResponse_ListServicesResponse); ok {
return x.ListServicesResponse
}
}
return nil
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServerReflectionResponse) GetErrorResponse() *ErrorResponse {
if x != nil {
if x, ok := x.MessageResponse.(*ServerReflectionResponse_ErrorResponse); ok {
return x.ErrorResponse
}
}
return nil
}
type isServerReflectionResponse_MessageResponse interface {
isServerReflectionResponse_MessageResponse()
}
type ServerReflectionResponse_FileDescriptorResponse struct {
// This message is used to answer file_by_filename, file_containing_symbol,
// file_containing_extension requests with transitive dependencies. As
// the repeated label is not allowed in oneof fields, we use a
// FileDescriptorResponse message to encapsulate the repeated fields.
// The reflection service is allowed to avoid sending FileDescriptorProtos
// that were previously sent in response to earlier requests in the stream.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
FileDescriptorResponse *FileDescriptorResponse `protobuf:"bytes,4,opt,name=file_descriptor_response,json=fileDescriptorResponse,proto3,oneof"`
}
type ServerReflectionResponse_AllExtensionNumbersResponse struct {
// This message is used to answer all_extension_numbers_of_type request.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
AllExtensionNumbersResponse *ExtensionNumberResponse `protobuf:"bytes,5,opt,name=all_extension_numbers_response,json=allExtensionNumbersResponse,proto3,oneof"`
}
type ServerReflectionResponse_ListServicesResponse struct {
// This message is used to answer list_services request.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
ListServicesResponse *ListServiceResponse `protobuf:"bytes,6,opt,name=list_services_response,json=listServicesResponse,proto3,oneof"`
}
type ServerReflectionResponse_ErrorResponse struct {
// This message is used when an error occurs.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
ErrorResponse *ErrorResponse `protobuf:"bytes,7,opt,name=error_response,json=errorResponse,proto3,oneof"`
}
func (*ServerReflectionResponse_FileDescriptorResponse) isServerReflectionResponse_MessageResponse() {
}
func (*ServerReflectionResponse_AllExtensionNumbersResponse) isServerReflectionResponse_MessageResponse() {
}
func (*ServerReflectionResponse_ListServicesResponse) isServerReflectionResponse_MessageResponse() {}
func (*ServerReflectionResponse_ErrorResponse) isServerReflectionResponse_MessageResponse() {}
// Serialized FileDescriptorProto messages sent by the server answering
// a file_by_filename, file_containing_symbol, or file_containing_extension
// request.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
type FileDescriptorResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Serialized FileDescriptorProto messages. We avoid taking a dependency on
// descriptor.proto, which uses proto2 only features, by making them opaque
// bytes instead.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
FileDescriptorProto [][]byte `protobuf:"bytes,1,rep,name=file_descriptor_proto,json=fileDescriptorProto,proto3" json:"file_descriptor_proto,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *FileDescriptorResponse) Reset() {
*x = FileDescriptorResponse{}
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *FileDescriptorResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FileDescriptorResponse) ProtoMessage() {}
func (x *FileDescriptorResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use FileDescriptorResponse.ProtoReflect.Descriptor instead.
func (*FileDescriptorResponse) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{3}
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *FileDescriptorResponse) GetFileDescriptorProto() [][]byte {
if x != nil {
return x.FileDescriptorProto
}
return nil
}
// A list of extension numbers sent by the server answering
// all_extension_numbers_of_type request.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
type ExtensionNumberResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Full name of the base type, including the package name. The format
// is <package>.<type>
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
BaseTypeName string `protobuf:"bytes,1,opt,name=base_type_name,json=baseTypeName,proto3" json:"base_type_name,omitempty"`
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
ExtensionNumber []int32 `protobuf:"varint,2,rep,packed,name=extension_number,json=extensionNumber,proto3" json:"extension_number,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ExtensionNumberResponse) Reset() {
*x = ExtensionNumberResponse{}
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ExtensionNumberResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ExtensionNumberResponse) ProtoMessage() {}
func (x *ExtensionNumberResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ExtensionNumberResponse.ProtoReflect.Descriptor instead.
func (*ExtensionNumberResponse) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{4}
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ExtensionNumberResponse) GetBaseTypeName() string {
if x != nil {
return x.BaseTypeName
}
return ""
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ExtensionNumberResponse) GetExtensionNumber() []int32 {
if x != nil {
return x.ExtensionNumber
}
return nil
}
// A list of ServiceResponse sent by the server answering list_services request.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
type ListServiceResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// The information of each service may be expanded in the future, so we use
// ServiceResponse message to encapsulate it.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
Service []*ServiceResponse `protobuf:"bytes,1,rep,name=service,proto3" json:"service,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ListServiceResponse) Reset() {
*x = ListServiceResponse{}
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ListServiceResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListServiceResponse) ProtoMessage() {}
func (x *ListServiceResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ListServiceResponse.ProtoReflect.Descriptor instead.
func (*ListServiceResponse) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{5}
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ListServiceResponse) GetService() []*ServiceResponse {
if x != nil {
return x.Service
}
return nil
}
// The information of a single service used by ListServiceResponse to answer
// list_services request.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
type ServiceResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Full name of a registered service, including its package name. The format
// is <package>.<service>
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ServiceResponse) Reset() {
*x = ServiceResponse{}
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ServiceResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ServiceResponse) ProtoMessage() {}
func (x *ServiceResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ServiceResponse.ProtoReflect.Descriptor instead.
func (*ServiceResponse) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{6}
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ServiceResponse) GetName() string {
if x != nil {
return x.Name
}
return ""
}
// The error code and error message sent by the server when an error occurs.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
type ErrorResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
// This field uses the error codes defined in grpc::StatusCode.
//
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
ErrorCode int32 `protobuf:"varint,1,opt,name=error_code,json=errorCode,proto3" json:"error_code,omitempty"`
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ErrorResponse) Reset() {
*x = ErrorResponse{}
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ErrorResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ErrorResponse) ProtoMessage() {}
func (x *ErrorResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_reflection_v1alpha_reflection_proto_msgTypes[7]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ErrorResponse.ProtoReflect.Descriptor instead.
func (*ErrorResponse) Descriptor() ([]byte, []int) {
return file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP(), []int{7}
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ErrorResponse) GetErrorCode() int32 {
if x != nil {
return x.ErrorCode
}
return 0
}
// Deprecated: The entire proto file grpc/reflection/v1alpha/reflection.proto is marked as deprecated.
func (x *ErrorResponse) GetErrorMessage() string {
if x != nil {
return x.ErrorMessage
}
return ""
}
var File_grpc_reflection_v1alpha_reflection_proto protoreflect.FileDescriptor
const file_grpc_reflection_v1alpha_reflection_proto_rawDesc = "" +
"\n" +
"(grpc/reflection/v1alpha/reflection.proto\x12\x17grpc.reflection.v1alpha\"\xf8\x02\n" +
"\x17ServerReflectionRequest\x12\x12\n" +
"\x04host\x18\x01 \x01(\tR\x04host\x12*\n" +
"\x10file_by_filename\x18\x03 \x01(\tH\x00R\x0efileByFilename\x126\n" +
"\x16file_containing_symbol\x18\x04 \x01(\tH\x00R\x14fileContainingSymbol\x12g\n" +
"\x19file_containing_extension\x18\x05 \x01(\v2).grpc.reflection.v1alpha.ExtensionRequestH\x00R\x17fileContainingExtension\x12B\n" +
"\x1dall_extension_numbers_of_type\x18\x06 \x01(\tH\x00R\x19allExtensionNumbersOfType\x12%\n" +
"\rlist_services\x18\a \x01(\tH\x00R\flistServicesB\x11\n" +
"\x0fmessage_request\"f\n" +
"\x10ExtensionRequest\x12'\n" +
"\x0fcontaining_type\x18\x01 \x01(\tR\x0econtainingType\x12)\n" +
"\x10extension_number\x18\x02 \x01(\x05R\x0fextensionNumber\"\xc7\x04\n" +
"\x18ServerReflectionResponse\x12\x1d\n" +
"\n" +
"valid_host\x18\x01 \x01(\tR\tvalidHost\x12[\n" +
"\x10original_request\x18\x02 \x01(\v20.grpc.reflection.v1alpha.ServerReflectionRequestR\x0foriginalRequest\x12k\n" +
"\x18file_descriptor_response\x18\x04 \x01(\v2/.grpc.reflection.v1alpha.FileDescriptorResponseH\x00R\x16fileDescriptorResponse\x12w\n" +
"\x1eall_extension_numbers_response\x18\x05 \x01(\v20.grpc.reflection.v1alpha.ExtensionNumberResponseH\x00R\x1ballExtensionNumbersResponse\x12d\n" +
"\x16list_services_response\x18\x06 \x01(\v2,.grpc.reflection.v1alpha.ListServiceResponseH\x00R\x14listServicesResponse\x12O\n" +
"\x0eerror_response\x18\a \x01(\v2&.grpc.reflection.v1alpha.ErrorResponseH\x00R\rerrorResponseB\x12\n" +
"\x10message_response\"L\n" +
"\x16FileDescriptorResponse\x122\n" +
"\x15file_descriptor_proto\x18\x01 \x03(\fR\x13fileDescriptorProto\"j\n" +
"\x17ExtensionNumberResponse\x12$\n" +
"\x0ebase_type_name\x18\x01 \x01(\tR\fbaseTypeName\x12)\n" +
"\x10extension_number\x18\x02 \x03(\x05R\x0fextensionNumber\"Y\n" +
"\x13ListServiceResponse\x12B\n" +
"\aservice\x18\x01 \x03(\v2(.grpc.reflection.v1alpha.ServiceResponseR\aservice\"%\n" +
"\x0fServiceResponse\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\"S\n" +
"\rErrorResponse\x12\x1d\n" +
"\n" +
"error_code\x18\x01 \x01(\x05R\terrorCode\x12#\n" +
"\rerror_message\x18\x02 \x01(\tR\ferrorMessage2\x93\x01\n" +
"\x10ServerReflection\x12\x7f\n" +
"\x14ServerReflectionInfo\x120.grpc.reflection.v1alpha.ServerReflectionRequest\x1a1.grpc.reflection.v1alpha.ServerReflectionResponse(\x010\x01Bs\n" +
"\x1aio.grpc.reflection.v1alphaB\x15ServerReflectionProtoP\x01Z9google.golang.org/grpc/reflection/grpc_reflection_v1alpha\xb8\x01\x01b\x06proto3"
var (
file_grpc_reflection_v1alpha_reflection_proto_rawDescOnce sync.Once
file_grpc_reflection_v1alpha_reflection_proto_rawDescData []byte
)
func file_grpc_reflection_v1alpha_reflection_proto_rawDescGZIP() []byte {
file_grpc_reflection_v1alpha_reflection_proto_rawDescOnce.Do(func() {
file_grpc_reflection_v1alpha_reflection_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_grpc_reflection_v1alpha_reflection_proto_rawDesc), len(file_grpc_reflection_v1alpha_reflection_proto_rawDesc)))
})
return file_grpc_reflection_v1alpha_reflection_proto_rawDescData
}
var file_grpc_reflection_v1alpha_reflection_proto_msgTypes = make([]protoimpl.MessageInfo, 8)
var file_grpc_reflection_v1alpha_reflection_proto_goTypes = []any{
(*ServerReflectionRequest)(nil), // 0: grpc.reflection.v1alpha.ServerReflectionRequest
(*ExtensionRequest)(nil), // 1: grpc.reflection.v1alpha.ExtensionRequest
(*ServerReflectionResponse)(nil), // 2: grpc.reflection.v1alpha.ServerReflectionResponse
(*FileDescriptorResponse)(nil), // 3: grpc.reflection.v1alpha.FileDescriptorResponse
(*ExtensionNumberResponse)(nil), // 4: grpc.reflection.v1alpha.ExtensionNumberResponse
(*ListServiceResponse)(nil), // 5: grpc.reflection.v1alpha.ListServiceResponse
(*ServiceResponse)(nil), // 6: grpc.reflection.v1alpha.ServiceResponse
(*ErrorResponse)(nil), // 7: grpc.reflection.v1alpha.ErrorResponse
}
var file_grpc_reflection_v1alpha_reflection_proto_depIdxs = []int32{
1, // 0: grpc.reflection.v1alpha.ServerReflectionRequest.file_containing_extension:type_name -> grpc.reflection.v1alpha.ExtensionRequest
0, // 1: grpc.reflection.v1alpha.ServerReflectionResponse.original_request:type_name -> grpc.reflection.v1alpha.ServerReflectionRequest
3, // 2: grpc.reflection.v1alpha.ServerReflectionResponse.file_descriptor_response:type_name -> grpc.reflection.v1alpha.FileDescriptorResponse
4, // 3: grpc.reflection.v1alpha.ServerReflectionResponse.all_extension_numbers_response:type_name -> grpc.reflection.v1alpha.ExtensionNumberResponse
5, // 4: grpc.reflection.v1alpha.ServerReflectionResponse.list_services_response:type_name -> grpc.reflection.v1alpha.ListServiceResponse
7, // 5: grpc.reflection.v1alpha.ServerReflectionResponse.error_response:type_name -> grpc.reflection.v1alpha.ErrorResponse
6, // 6: grpc.reflection.v1alpha.ListServiceResponse.service:type_name -> grpc.reflection.v1alpha.ServiceResponse
0, // 7: grpc.reflection.v1alpha.ServerReflection.ServerReflectionInfo:input_type -> grpc.reflection.v1alpha.ServerReflectionRequest
2, // 8: grpc.reflection.v1alpha.ServerReflection.ServerReflectionInfo:output_type -> grpc.reflection.v1alpha.ServerReflectionResponse
8, // [8:9] is the sub-list for method output_type
7, // [7:8] is the sub-list for method input_type
7, // [7:7] is the sub-list for extension type_name
7, // [7:7] is the sub-list for extension extendee
0, // [0:7] is the sub-list for field type_name
}
func init() { file_grpc_reflection_v1alpha_reflection_proto_init() }
func file_grpc_reflection_v1alpha_reflection_proto_init() {
if File_grpc_reflection_v1alpha_reflection_proto != nil {
return
}
file_grpc_reflection_v1alpha_reflection_proto_msgTypes[0].OneofWrappers = []any{
(*ServerReflectionRequest_FileByFilename)(nil),
(*ServerReflectionRequest_FileContainingSymbol)(nil),
(*ServerReflectionRequest_FileContainingExtension)(nil),
(*ServerReflectionRequest_AllExtensionNumbersOfType)(nil),
(*ServerReflectionRequest_ListServices)(nil),
}
file_grpc_reflection_v1alpha_reflection_proto_msgTypes[2].OneofWrappers = []any{
(*ServerReflectionResponse_FileDescriptorResponse)(nil),
(*ServerReflectionResponse_AllExtensionNumbersResponse)(nil),
(*ServerReflectionResponse_ListServicesResponse)(nil),
(*ServerReflectionResponse_ErrorResponse)(nil),
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_grpc_reflection_v1alpha_reflection_proto_rawDesc), len(file_grpc_reflection_v1alpha_reflection_proto_rawDesc)),
NumEnums: 0,
NumMessages: 8,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_grpc_reflection_v1alpha_reflection_proto_goTypes,
DependencyIndexes: file_grpc_reflection_v1alpha_reflection_proto_depIdxs,
MessageInfos: file_grpc_reflection_v1alpha_reflection_proto_msgTypes,
}.Build()
File_grpc_reflection_v1alpha_reflection_proto = out.File
file_grpc_reflection_v1alpha_reflection_proto_goTypes = nil
file_grpc_reflection_v1alpha_reflection_proto_depIdxs = nil
}
@@ -0,0 +1,135 @@
// Copyright 2016 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Service exported by server reflection
// Warning: this entire file is deprecated. Use this instead:
// https://github.com/grpc/grpc-proto/blob/master/grpc/reflection/v1/reflection.proto
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
// - protoc v5.27.1
// grpc/reflection/v1alpha/reflection.proto is a deprecated file.
package grpc_reflection_v1alpha
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
ServerReflection_ServerReflectionInfo_FullMethodName = "/grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo"
)
// ServerReflectionClient is the client API for ServerReflection service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type ServerReflectionClient interface {
// The reflection service is structured as a bidirectional stream, ensuring
// all related requests go to a single server.
ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[ServerReflectionRequest, ServerReflectionResponse], error)
}
type serverReflectionClient struct {
cc grpc.ClientConnInterface
}
func NewServerReflectionClient(cc grpc.ClientConnInterface) ServerReflectionClient {
return &serverReflectionClient{cc}
}
func (c *serverReflectionClient) ServerReflectionInfo(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[ServerReflectionRequest, ServerReflectionResponse], error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
stream, err := c.cc.NewStream(ctx, &ServerReflection_ServiceDesc.Streams[0], ServerReflection_ServerReflectionInfo_FullMethodName, cOpts...)
if err != nil {
return nil, err
}
x := &grpc.GenericClientStream[ServerReflectionRequest, ServerReflectionResponse]{ClientStream: stream}
return x, nil
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type ServerReflection_ServerReflectionInfoClient = grpc.BidiStreamingClient[ServerReflectionRequest, ServerReflectionResponse]
// ServerReflectionServer is the server API for ServerReflection service.
// All implementations should embed UnimplementedServerReflectionServer
// for forward compatibility.
type ServerReflectionServer interface {
// The reflection service is structured as a bidirectional stream, ensuring
// all related requests go to a single server.
ServerReflectionInfo(grpc.BidiStreamingServer[ServerReflectionRequest, ServerReflectionResponse]) error
}
// UnimplementedServerReflectionServer should be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedServerReflectionServer struct{}
func (UnimplementedServerReflectionServer) ServerReflectionInfo(grpc.BidiStreamingServer[ServerReflectionRequest, ServerReflectionResponse]) error {
return status.Error(codes.Unimplemented, "method ServerReflectionInfo not implemented")
}
func (UnimplementedServerReflectionServer) testEmbeddedByValue() {}
// UnsafeServerReflectionServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to ServerReflectionServer will
// result in compilation errors.
type UnsafeServerReflectionServer interface {
mustEmbedUnimplementedServerReflectionServer()
}
func RegisterServerReflectionServer(s grpc.ServiceRegistrar, srv ServerReflectionServer) {
// If the following call panics, it indicates UnimplementedServerReflectionServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&ServerReflection_ServiceDesc, srv)
}
func _ServerReflection_ServerReflectionInfo_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(ServerReflectionServer).ServerReflectionInfo(&grpc.GenericServerStream[ServerReflectionRequest, ServerReflectionResponse]{ServerStream: stream})
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type ServerReflection_ServerReflectionInfoServer = grpc.BidiStreamingServer[ServerReflectionRequest, ServerReflectionResponse]
// ServerReflection_ServiceDesc is the grpc.ServiceDesc for ServerReflection service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var ServerReflection_ServiceDesc = grpc.ServiceDesc{
ServiceName: "grpc.reflection.v1alpha.ServerReflection",
HandlerType: (*ServerReflectionServer)(nil),
Methods: []grpc.MethodDesc{},
Streams: []grpc.StreamDesc{
{
StreamName: "ServerReflectionInfo",
Handler: _ServerReflection_ServerReflectionInfo_Handler,
ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "grpc/reflection/v1alpha/reflection.proto",
}
+436
View File
@@ -0,0 +1,436 @@
/*
*
* Copyright 2024 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// Package internal contains code that is shared by both reflection package and
// the test package. The packages are split in this way inorder to avoid
// dependency to deprecated package github.com/golang/protobuf.
package internal
import (
"io"
"sort"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protodesc"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
v1reflectiongrpc "google.golang.org/grpc/reflection/grpc_reflection_v1"
v1reflectionpb "google.golang.org/grpc/reflection/grpc_reflection_v1"
v1alphareflectiongrpc "google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
v1alphareflectionpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
)
// ServiceInfoProvider is an interface used to retrieve metadata about the
// services to expose.
type ServiceInfoProvider interface {
GetServiceInfo() map[string]grpc.ServiceInfo
}
// ExtensionResolver is the interface used to query details about extensions.
// This interface is satisfied by protoregistry.GlobalTypes.
type ExtensionResolver interface {
protoregistry.ExtensionTypeResolver
RangeExtensionsByMessage(message protoreflect.FullName, f func(protoreflect.ExtensionType) bool)
}
// ServerReflectionServer is the server API for ServerReflection service.
type ServerReflectionServer struct {
v1alphareflectiongrpc.UnimplementedServerReflectionServer
S ServiceInfoProvider
DescResolver protodesc.Resolver
ExtResolver ExtensionResolver
}
// FileDescWithDependencies returns a slice of serialized fileDescriptors in
// wire format ([]byte). The fileDescriptors will include fd and all the
// transitive dependencies of fd with names not in sentFileDescriptors.
func (s *ServerReflectionServer) FileDescWithDependencies(fd protoreflect.FileDescriptor, sentFileDescriptors map[string]bool) ([][]byte, error) {
if fd.IsPlaceholder() {
// If the given root file is a placeholder, treat it
// as missing instead of serializing it.
return nil, protoregistry.NotFound
}
var r [][]byte
queue := []protoreflect.FileDescriptor{fd}
for len(queue) > 0 {
currentfd := queue[0]
queue = queue[1:]
if currentfd.IsPlaceholder() {
// Skip any missing files in the dependency graph.
continue
}
if sent := sentFileDescriptors[currentfd.Path()]; len(r) == 0 || !sent {
sentFileDescriptors[currentfd.Path()] = true
fdProto := protodesc.ToFileDescriptorProto(currentfd)
currentfdEncoded, err := proto.Marshal(fdProto)
if err != nil {
return nil, err
}
r = append(r, currentfdEncoded)
}
for i := 0; i < currentfd.Imports().Len(); i++ {
queue = append(queue, currentfd.Imports().Get(i))
}
}
return r, nil
}
// FileDescEncodingContainingSymbol finds the file descriptor containing the
// given symbol, finds all of its previously unsent transitive dependencies,
// does marshalling on them, and returns the marshalled result. The given symbol
// can be a type, a service or a method.
func (s *ServerReflectionServer) FileDescEncodingContainingSymbol(name string, sentFileDescriptors map[string]bool) ([][]byte, error) {
d, err := s.DescResolver.FindDescriptorByName(protoreflect.FullName(name))
if err != nil {
return nil, err
}
return s.FileDescWithDependencies(d.ParentFile(), sentFileDescriptors)
}
// FileDescEncodingContainingExtension finds the file descriptor containing
// given extension, finds all of its previously unsent transitive dependencies,
// does marshalling on them, and returns the marshalled result.
func (s *ServerReflectionServer) FileDescEncodingContainingExtension(typeName string, extNum int32, sentFileDescriptors map[string]bool) ([][]byte, error) {
xt, err := s.ExtResolver.FindExtensionByNumber(protoreflect.FullName(typeName), protoreflect.FieldNumber(extNum))
if err != nil {
return nil, err
}
return s.FileDescWithDependencies(xt.TypeDescriptor().ParentFile(), sentFileDescriptors)
}
// AllExtensionNumbersForTypeName returns all extension numbers for the given type.
func (s *ServerReflectionServer) AllExtensionNumbersForTypeName(name string) ([]int32, error) {
var numbers []int32
s.ExtResolver.RangeExtensionsByMessage(protoreflect.FullName(name), func(xt protoreflect.ExtensionType) bool {
numbers = append(numbers, int32(xt.TypeDescriptor().Number()))
return true
})
sort.Slice(numbers, func(i, j int) bool {
return numbers[i] < numbers[j]
})
if len(numbers) == 0 {
// maybe return an error if given type name is not known
if _, err := s.DescResolver.FindDescriptorByName(protoreflect.FullName(name)); err != nil {
return nil, err
}
}
return numbers, nil
}
// ListServices returns the names of services this server exposes.
func (s *ServerReflectionServer) ListServices() []*v1reflectionpb.ServiceResponse {
serviceInfo := s.S.GetServiceInfo()
resp := make([]*v1reflectionpb.ServiceResponse, 0, len(serviceInfo))
for svc := range serviceInfo {
resp = append(resp, &v1reflectionpb.ServiceResponse{Name: svc})
}
sort.Slice(resp, func(i, j int) bool {
return resp[i].Name < resp[j].Name
})
return resp
}
// ServerReflectionInfo is the reflection service handler.
func (s *ServerReflectionServer) ServerReflectionInfo(stream v1reflectiongrpc.ServerReflection_ServerReflectionInfoServer) error {
sentFileDescriptors := make(map[string]bool)
for {
in, err := stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
out := &v1reflectionpb.ServerReflectionResponse{
ValidHost: in.Host,
OriginalRequest: in,
}
switch req := in.MessageRequest.(type) {
case *v1reflectionpb.ServerReflectionRequest_FileByFilename:
var b [][]byte
fd, err := s.DescResolver.FindFileByPath(req.FileByFilename)
if err == nil {
b, err = s.FileDescWithDependencies(fd, sentFileDescriptors)
}
if err != nil {
out.MessageResponse = &v1reflectionpb.ServerReflectionResponse_ErrorResponse{
ErrorResponse: &v1reflectionpb.ErrorResponse{
ErrorCode: int32(codes.NotFound),
ErrorMessage: err.Error(),
},
}
} else {
out.MessageResponse = &v1reflectionpb.ServerReflectionResponse_FileDescriptorResponse{
FileDescriptorResponse: &v1reflectionpb.FileDescriptorResponse{FileDescriptorProto: b},
}
}
case *v1reflectionpb.ServerReflectionRequest_FileContainingSymbol:
b, err := s.FileDescEncodingContainingSymbol(req.FileContainingSymbol, sentFileDescriptors)
if err != nil {
out.MessageResponse = &v1reflectionpb.ServerReflectionResponse_ErrorResponse{
ErrorResponse: &v1reflectionpb.ErrorResponse{
ErrorCode: int32(codes.NotFound),
ErrorMessage: err.Error(),
},
}
} else {
out.MessageResponse = &v1reflectionpb.ServerReflectionResponse_FileDescriptorResponse{
FileDescriptorResponse: &v1reflectionpb.FileDescriptorResponse{FileDescriptorProto: b},
}
}
case *v1reflectionpb.ServerReflectionRequest_FileContainingExtension:
typeName := req.FileContainingExtension.ContainingType
extNum := req.FileContainingExtension.ExtensionNumber
b, err := s.FileDescEncodingContainingExtension(typeName, extNum, sentFileDescriptors)
if err != nil {
out.MessageResponse = &v1reflectionpb.ServerReflectionResponse_ErrorResponse{
ErrorResponse: &v1reflectionpb.ErrorResponse{
ErrorCode: int32(codes.NotFound),
ErrorMessage: err.Error(),
},
}
} else {
out.MessageResponse = &v1reflectionpb.ServerReflectionResponse_FileDescriptorResponse{
FileDescriptorResponse: &v1reflectionpb.FileDescriptorResponse{FileDescriptorProto: b},
}
}
case *v1reflectionpb.ServerReflectionRequest_AllExtensionNumbersOfType:
extNums, err := s.AllExtensionNumbersForTypeName(req.AllExtensionNumbersOfType)
if err != nil {
out.MessageResponse = &v1reflectionpb.ServerReflectionResponse_ErrorResponse{
ErrorResponse: &v1reflectionpb.ErrorResponse{
ErrorCode: int32(codes.NotFound),
ErrorMessage: err.Error(),
},
}
} else {
out.MessageResponse = &v1reflectionpb.ServerReflectionResponse_AllExtensionNumbersResponse{
AllExtensionNumbersResponse: &v1reflectionpb.ExtensionNumberResponse{
BaseTypeName: req.AllExtensionNumbersOfType,
ExtensionNumber: extNums,
},
}
}
case *v1reflectionpb.ServerReflectionRequest_ListServices:
out.MessageResponse = &v1reflectionpb.ServerReflectionResponse_ListServicesResponse{
ListServicesResponse: &v1reflectionpb.ListServiceResponse{
Service: s.ListServices(),
},
}
default:
return status.Errorf(codes.InvalidArgument, "invalid MessageRequest: %v", in.MessageRequest)
}
if err := stream.Send(out); err != nil {
return err
}
}
}
// V1ToV1AlphaResponse converts a v1 ServerReflectionResponse to a v1alpha.
func V1ToV1AlphaResponse(v1 *v1reflectionpb.ServerReflectionResponse) *v1alphareflectionpb.ServerReflectionResponse {
var v1alpha v1alphareflectionpb.ServerReflectionResponse
v1alpha.ValidHost = v1.ValidHost
if v1.OriginalRequest != nil {
v1alpha.OriginalRequest = V1ToV1AlphaRequest(v1.OriginalRequest)
}
switch mr := v1.MessageResponse.(type) {
case *v1reflectionpb.ServerReflectionResponse_FileDescriptorResponse:
if mr != nil {
v1alpha.MessageResponse = &v1alphareflectionpb.ServerReflectionResponse_FileDescriptorResponse{
FileDescriptorResponse: &v1alphareflectionpb.FileDescriptorResponse{
FileDescriptorProto: mr.FileDescriptorResponse.GetFileDescriptorProto(),
},
}
}
case *v1reflectionpb.ServerReflectionResponse_AllExtensionNumbersResponse:
if mr != nil {
v1alpha.MessageResponse = &v1alphareflectionpb.ServerReflectionResponse_AllExtensionNumbersResponse{
AllExtensionNumbersResponse: &v1alphareflectionpb.ExtensionNumberResponse{
BaseTypeName: mr.AllExtensionNumbersResponse.GetBaseTypeName(),
ExtensionNumber: mr.AllExtensionNumbersResponse.GetExtensionNumber(),
},
}
}
case *v1reflectionpb.ServerReflectionResponse_ListServicesResponse:
if mr != nil {
svcs := make([]*v1alphareflectionpb.ServiceResponse, len(mr.ListServicesResponse.GetService()))
for i, svc := range mr.ListServicesResponse.GetService() {
svcs[i] = &v1alphareflectionpb.ServiceResponse{
Name: svc.GetName(),
}
}
v1alpha.MessageResponse = &v1alphareflectionpb.ServerReflectionResponse_ListServicesResponse{
ListServicesResponse: &v1alphareflectionpb.ListServiceResponse{
Service: svcs,
},
}
}
case *v1reflectionpb.ServerReflectionResponse_ErrorResponse:
if mr != nil {
v1alpha.MessageResponse = &v1alphareflectionpb.ServerReflectionResponse_ErrorResponse{
ErrorResponse: &v1alphareflectionpb.ErrorResponse{
ErrorCode: mr.ErrorResponse.GetErrorCode(),
ErrorMessage: mr.ErrorResponse.GetErrorMessage(),
},
}
}
default:
// no value set
}
return &v1alpha
}
// V1AlphaToV1Request converts a v1alpha ServerReflectionRequest to a v1.
func V1AlphaToV1Request(v1alpha *v1alphareflectionpb.ServerReflectionRequest) *v1reflectionpb.ServerReflectionRequest {
var v1 v1reflectionpb.ServerReflectionRequest
v1.Host = v1alpha.Host
switch mr := v1alpha.MessageRequest.(type) {
case *v1alphareflectionpb.ServerReflectionRequest_FileByFilename:
v1.MessageRequest = &v1reflectionpb.ServerReflectionRequest_FileByFilename{
FileByFilename: mr.FileByFilename,
}
case *v1alphareflectionpb.ServerReflectionRequest_FileContainingSymbol:
v1.MessageRequest = &v1reflectionpb.ServerReflectionRequest_FileContainingSymbol{
FileContainingSymbol: mr.FileContainingSymbol,
}
case *v1alphareflectionpb.ServerReflectionRequest_FileContainingExtension:
if mr.FileContainingExtension != nil {
v1.MessageRequest = &v1reflectionpb.ServerReflectionRequest_FileContainingExtension{
FileContainingExtension: &v1reflectionpb.ExtensionRequest{
ContainingType: mr.FileContainingExtension.GetContainingType(),
ExtensionNumber: mr.FileContainingExtension.GetExtensionNumber(),
},
}
}
case *v1alphareflectionpb.ServerReflectionRequest_AllExtensionNumbersOfType:
v1.MessageRequest = &v1reflectionpb.ServerReflectionRequest_AllExtensionNumbersOfType{
AllExtensionNumbersOfType: mr.AllExtensionNumbersOfType,
}
case *v1alphareflectionpb.ServerReflectionRequest_ListServices:
v1.MessageRequest = &v1reflectionpb.ServerReflectionRequest_ListServices{
ListServices: mr.ListServices,
}
default:
// no value set
}
return &v1
}
// V1ToV1AlphaRequest converts a v1 ServerReflectionRequest to a v1alpha.
func V1ToV1AlphaRequest(v1 *v1reflectionpb.ServerReflectionRequest) *v1alphareflectionpb.ServerReflectionRequest {
var v1alpha v1alphareflectionpb.ServerReflectionRequest
v1alpha.Host = v1.Host
switch mr := v1.MessageRequest.(type) {
case *v1reflectionpb.ServerReflectionRequest_FileByFilename:
if mr != nil {
v1alpha.MessageRequest = &v1alphareflectionpb.ServerReflectionRequest_FileByFilename{
FileByFilename: mr.FileByFilename,
}
}
case *v1reflectionpb.ServerReflectionRequest_FileContainingSymbol:
if mr != nil {
v1alpha.MessageRequest = &v1alphareflectionpb.ServerReflectionRequest_FileContainingSymbol{
FileContainingSymbol: mr.FileContainingSymbol,
}
}
case *v1reflectionpb.ServerReflectionRequest_FileContainingExtension:
if mr != nil {
v1alpha.MessageRequest = &v1alphareflectionpb.ServerReflectionRequest_FileContainingExtension{
FileContainingExtension: &v1alphareflectionpb.ExtensionRequest{
ContainingType: mr.FileContainingExtension.GetContainingType(),
ExtensionNumber: mr.FileContainingExtension.GetExtensionNumber(),
},
}
}
case *v1reflectionpb.ServerReflectionRequest_AllExtensionNumbersOfType:
if mr != nil {
v1alpha.MessageRequest = &v1alphareflectionpb.ServerReflectionRequest_AllExtensionNumbersOfType{
AllExtensionNumbersOfType: mr.AllExtensionNumbersOfType,
}
}
case *v1reflectionpb.ServerReflectionRequest_ListServices:
if mr != nil {
v1alpha.MessageRequest = &v1alphareflectionpb.ServerReflectionRequest_ListServices{
ListServices: mr.ListServices,
}
}
default:
// no value set
}
return &v1alpha
}
// V1AlphaToV1Response converts a v1alpha ServerReflectionResponse to a v1.
func V1AlphaToV1Response(v1alpha *v1alphareflectionpb.ServerReflectionResponse) *v1reflectionpb.ServerReflectionResponse {
var v1 v1reflectionpb.ServerReflectionResponse
v1.ValidHost = v1alpha.ValidHost
if v1alpha.OriginalRequest != nil {
v1.OriginalRequest = V1AlphaToV1Request(v1alpha.OriginalRequest)
}
switch mr := v1alpha.MessageResponse.(type) {
case *v1alphareflectionpb.ServerReflectionResponse_FileDescriptorResponse:
if mr != nil {
v1.MessageResponse = &v1reflectionpb.ServerReflectionResponse_FileDescriptorResponse{
FileDescriptorResponse: &v1reflectionpb.FileDescriptorResponse{
FileDescriptorProto: mr.FileDescriptorResponse.GetFileDescriptorProto(),
},
}
}
case *v1alphareflectionpb.ServerReflectionResponse_AllExtensionNumbersResponse:
if mr != nil {
v1.MessageResponse = &v1reflectionpb.ServerReflectionResponse_AllExtensionNumbersResponse{
AllExtensionNumbersResponse: &v1reflectionpb.ExtensionNumberResponse{
BaseTypeName: mr.AllExtensionNumbersResponse.GetBaseTypeName(),
ExtensionNumber: mr.AllExtensionNumbersResponse.GetExtensionNumber(),
},
}
}
case *v1alphareflectionpb.ServerReflectionResponse_ListServicesResponse:
if mr != nil {
svcs := make([]*v1reflectionpb.ServiceResponse, len(mr.ListServicesResponse.GetService()))
for i, svc := range mr.ListServicesResponse.GetService() {
svcs[i] = &v1reflectionpb.ServiceResponse{
Name: svc.GetName(),
}
}
v1.MessageResponse = &v1reflectionpb.ServerReflectionResponse_ListServicesResponse{
ListServicesResponse: &v1reflectionpb.ListServiceResponse{
Service: svcs,
},
}
}
case *v1alphareflectionpb.ServerReflectionResponse_ErrorResponse:
if mr != nil {
v1.MessageResponse = &v1reflectionpb.ServerReflectionResponse_ErrorResponse{
ErrorResponse: &v1reflectionpb.ErrorResponse{
ErrorCode: mr.ErrorResponse.GetErrorCode(),
ErrorMessage: mr.ErrorResponse.GetErrorMessage(),
},
}
}
default:
// no value set
}
return &v1
}
+160
View File
@@ -0,0 +1,160 @@
/*
*
* Copyright 2016 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
Package reflection implements server reflection service.
The service implemented is defined in:
https://github.com/grpc/grpc/blob/master/src/proto/grpc/reflection/v1alpha/reflection.proto.
To register server reflection on a gRPC server:
import "google.golang.org/grpc/reflection"
s := grpc.NewServer()
pb.RegisterYourOwnServer(s, &server{})
// Register reflection service on gRPC server.
reflection.Register(s)
s.Serve(lis)
*/
package reflection // import "google.golang.org/grpc/reflection"
import (
"google.golang.org/grpc"
"google.golang.org/grpc/reflection/internal"
"google.golang.org/protobuf/reflect/protodesc"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
v1reflectiongrpc "google.golang.org/grpc/reflection/grpc_reflection_v1"
v1alphareflectiongrpc "google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
)
// GRPCServer is the interface provided by a gRPC server. It is implemented by
// *grpc.Server, but could also be implemented by other concrete types. It acts
// as a registry, for accumulating the services exposed by the server.
type GRPCServer interface {
grpc.ServiceRegistrar
ServiceInfoProvider
}
var _ GRPCServer = (*grpc.Server)(nil)
// Register registers the server reflection service on the given gRPC server.
// Both the v1 and v1alpha versions are registered.
func Register(s GRPCServer) {
svr := NewServerV1(ServerOptions{Services: s})
v1alphareflectiongrpc.RegisterServerReflectionServer(s, asV1Alpha(svr))
v1reflectiongrpc.RegisterServerReflectionServer(s, svr)
}
// RegisterV1 registers only the v1 version of the server reflection service
// on the given gRPC server. Many clients may only support v1alpha so most
// users should use Register instead, at least until clients have upgraded.
func RegisterV1(s GRPCServer) {
svr := NewServerV1(ServerOptions{Services: s})
v1reflectiongrpc.RegisterServerReflectionServer(s, svr)
}
// ServiceInfoProvider is an interface used to retrieve metadata about the
// services to expose.
//
// The reflection service is only interested in the service names, but the
// signature is this way so that *grpc.Server implements it. So it is okay
// for a custom implementation to return zero values for the
// grpc.ServiceInfo values in the map.
//
// # Experimental
//
// Notice: This type is EXPERIMENTAL and may be changed or removed in a
// later release.
type ServiceInfoProvider interface {
GetServiceInfo() map[string]grpc.ServiceInfo
}
// ExtensionResolver is the interface used to query details about extensions.
// This interface is satisfied by protoregistry.GlobalTypes.
//
// # Experimental
//
// Notice: This type is EXPERIMENTAL and may be changed or removed in a
// later release.
type ExtensionResolver interface {
protoregistry.ExtensionTypeResolver
RangeExtensionsByMessage(message protoreflect.FullName, f func(protoreflect.ExtensionType) bool)
}
// ServerOptions represents the options used to construct a reflection server.
//
// # Experimental
//
// Notice: This type is EXPERIMENTAL and may be changed or removed in a
// later release.
type ServerOptions struct {
// The source of advertised RPC services. If not specified, the reflection
// server will report an empty list when asked to list services.
//
// This value will typically be a *grpc.Server. But the set of advertised
// services can be customized by wrapping a *grpc.Server or using an
// alternate implementation that returns a custom set of service names.
Services ServiceInfoProvider
// Optional resolver used to load descriptors. If not specified,
// protoregistry.GlobalFiles will be used.
DescriptorResolver protodesc.Resolver
// Optional resolver used to query for known extensions. If not specified,
// protoregistry.GlobalTypes will be used.
ExtensionResolver ExtensionResolver
}
// NewServer returns a reflection server implementation using the given options.
// This can be used to customize behavior of the reflection service. Most usages
// should prefer to use Register instead. For backwards compatibility reasons,
// this returns the v1alpha version of the reflection server. For a v1 version
// of the reflection server, see NewServerV1.
//
// # Experimental
//
// Notice: This function is EXPERIMENTAL and may be changed or removed in a
// later release.
func NewServer(opts ServerOptions) v1alphareflectiongrpc.ServerReflectionServer {
return asV1Alpha(NewServerV1(opts))
}
// NewServerV1 returns a reflection server implementation using the given options.
// This can be used to customize behavior of the reflection service. Most usages
// should prefer to use Register instead.
//
// # Experimental
//
// Notice: This function is EXPERIMENTAL and may be changed or removed in a
// later release.
func NewServerV1(opts ServerOptions) v1reflectiongrpc.ServerReflectionServer {
if opts.DescriptorResolver == nil {
opts.DescriptorResolver = protoregistry.GlobalFiles
}
if opts.ExtensionResolver == nil {
opts.ExtensionResolver = protoregistry.GlobalTypes
}
return &internal.ServerReflectionServer{
S: opts.Services,
DescResolver: opts.DescriptorResolver,
ExtResolver: opts.ExtensionResolver,
}
}
+12 -5
View File
@@ -969,9 +969,12 @@ github.com/googleapis/gax-go/v2/iterator
# github.com/gorilla/mux v1.8.1
## explicit; go 1.20
github.com/gorilla/mux
# github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0
## explicit
github.com/grpc-ecosystem/go-grpc-prometheus
# github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.1
## explicit; go 1.23.0
github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus
# github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3
## explicit; go 1.23.0
github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors
# github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0
## explicit; go 1.26.0
github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule
@@ -1360,7 +1363,7 @@ github.com/moby/profiles/seccomp
# github.com/moby/pubsub v1.0.0
## explicit; go 1.19
github.com/moby/pubsub
# github.com/moby/swarmkit/v2 v2.1.3-0.20261016144904-5d8dbdc21997
# github.com/moby/swarmkit/v2 v2.1.3-0.20261102175146-49925db4331f
## explicit; go 1.25.0
github.com/moby/swarmkit/v2/agent
github.com/moby/swarmkit/v2/agent/configs
@@ -1381,6 +1384,7 @@ github.com/moby/swarmkit/v2/ca/pkcs8
github.com/moby/swarmkit/v2/connectionbroker
github.com/moby/swarmkit/v2/identity
github.com/moby/swarmkit/v2/internal/csi/capability
github.com/moby/swarmkit/v2/internal/grpcmetrics
github.com/moby/swarmkit/v2/internal/idm
github.com/moby/swarmkit/v2/ioutils
github.com/moby/swarmkit/v2/log
@@ -2006,7 +2010,6 @@ golang.org/x/mod/sumdb/note
# golang.org/x/net v0.62.0
## explicit; go 1.26.0
golang.org/x/net/bpf
golang.org/x/net/context
golang.org/x/net/http/httpguts
golang.org/x/net/http2
golang.org/x/net/http2/hpack
@@ -2185,6 +2188,10 @@ google.golang.org/grpc/keepalive
google.golang.org/grpc/mem
google.golang.org/grpc/metadata
google.golang.org/grpc/peer
google.golang.org/grpc/reflection
google.golang.org/grpc/reflection/grpc_reflection_v1
google.golang.org/grpc/reflection/grpc_reflection_v1alpha
google.golang.org/grpc/reflection/internal
google.golang.org/grpc/resolver
google.golang.org/grpc/resolver/dns
google.golang.org/grpc/resolver/manual