From 829779f4a92bb78a2be8ed02a4ffba0219f28983 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Tue, 14 Mar 2023 12:36:22 +0100 Subject: [PATCH] vendor: pin OTEL to version that is compatible with BuildKit Building static bundles/binary-daemon/dockerd (linux/arm64)... # github.com/docker/docker/vendor/github.com/moby/buildkit/worker/containerd vendor/github.com/moby/buildkit/worker/containerd/containerd.go:56:74: cannot use &gogoptypes.Empty{} (value of type *"github.com/docker/docker/vendor/github.com/gogo/protobuf/types".Empty) as *emptypb.Empty value in argument to client.IntrospectionService().Server Signed-off-by: Sebastiaan van Stijn --- vendor.mod | 53 +- vendor.sum | 97 +-- .../golang/protobuf/descriptor/descriptor.go | 180 ++++++ .../grpc-gateway/{v2 => }/LICENSE.txt | 0 .../grpc-gateway/internal/BUILD.bazel | 23 + .../grpc-gateway/internal/errors.pb.go | 189 ++++++ .../grpc-gateway/internal/errors.proto | 26 + .../grpc-gateway/runtime/BUILD.bazel | 85 +++ .../grpc-gateway/{v2 => }/runtime/context.go | 64 +- .../grpc-gateway/{v2 => }/runtime/convert.go | 60 +- .../grpc-gateway/{v2 => }/runtime/doc.go | 0 .../grpc-gateway/runtime/errors.go | 186 ++++++ .../grpc-gateway/runtime/fieldmask.go | 89 +++ .../grpc-gateway/{v2 => }/runtime/handler.go | 73 +-- .../{v2 => }/runtime/marshal_httpbodyproto.go | 21 +- .../{v2 => }/runtime/marshal_json.go | 2 +- .../{v2 => }/runtime/marshal_jsonpb.go | 158 ++--- .../{v2 => }/runtime/marshal_proto.go | 5 +- .../{v2 => }/runtime/marshaler.go | 11 +- .../{v2 => }/runtime/marshaler_registry.go | 12 +- .../grpc-gateway/{v2 => }/runtime/mux.go | 228 +++---- .../grpc-gateway/{v2 => }/runtime/pattern.go | 203 ++----- .../{v2 => }/runtime/proto2_convert.go | 2 +- .../grpc-gateway/runtime/proto_errors.go | 106 ++++ .../grpc-gateway/runtime/query.go | 406 +++++++++++++ .../{v2 => }/utilities/BUILD.bazel | 14 +- .../grpc-gateway/{v2 => }/utilities/doc.go | 0 .../{v2 => }/utilities/pattern.go | 0 .../{v2 => }/utilities/readerfactory.go | 0 .../grpc-gateway/{v2 => }/utilities/trie.go | 5 +- .../v2/internal/httprule/BUILD.bazel | 35 -- .../v2/internal/httprule/compile.go | 121 ---- .../grpc-gateway/v2/internal/httprule/fuzz.go | 11 - .../v2/internal/httprule/parse.go | 368 ----------- .../v2/internal/httprule/types.go | 60 -- .../grpc-gateway/v2/runtime/BUILD.bazel | 91 --- .../grpc-gateway/v2/runtime/errors.go | 180 ------ .../grpc-gateway/v2/runtime/fieldmask.go | 165 ----- .../grpc-gateway/v2/runtime/query.go | 329 ---------- .../grpc/otelgrpc/{config.go => grpctrace.go} | 95 ++- .../grpc/otelgrpc/interceptor.go | 162 ++--- .../grpc/otelgrpc/interceptorinfo.go | 50 -- .../grpc/otelgrpc/internal/parse.go | 8 +- .../grpc/otelgrpc/metadata_supplier.go | 98 --- .../grpc/otelgrpc/semconv.go | 6 +- .../grpc/otelgrpc/version.go | 4 +- .../otlp/internal/envconfig/envconfig.go | 199 ------ .../exporters/otlp/internal/partialsuccess.go | 64 -- .../exporters/otlp/internal/wrappederror.go | 61 -- .../otel/exporters/otlp/otlptrace/README.md | 20 +- .../otel/exporters/otlp/otlptrace/exporter.go | 18 +- .../internal/otlpconfig/envconfig.go | 233 ++++--- .../otlptrace/internal/otlpconfig/options.go | 28 +- .../internal/otlpconfig/optiontypes.go | 9 +- .../internal/tracetransform/attribute.go | 4 +- .../tracetransform/instrumentation.go | 6 +- .../otlptrace/internal/tracetransform/span.go | 74 ++- .../otlp/otlptrace/otlptracegrpc/client.go | 27 +- .../otlp/otlptrace/otlptracegrpc/options.go | 3 +- .../otlp/otlptrace/otlptracehttp/client.go | 98 ++- .../otlp/otlptrace/otlptracehttp/options.go | 10 +- .../otel/internal/metric/LICENSE | 201 ++++++ .../otel/internal/metric/global/meter.go | 287 +++++++++ .../metric/global/metric.go} | 52 +- .../metric/registry/doc.go} | 28 +- .../otel/internal/metric/registry/registry.go | 139 +++++ .../go.opentelemetry.io/otel/metric/config.go | 88 ++- vendor/go.opentelemetry.io/otel/metric/doc.go | 44 ++ .../otel/metric/global/global.go | 42 -- .../otel/metric/global/metric.go | 49 ++ .../otel/metric/instrument/asyncfloat64.go | 130 ---- .../otel/metric/instrument/asyncint64.go | 130 ---- .../otel/metric/instrument/instrument.go | 88 --- .../otel/metric/instrument/syncfloat64.go | 85 --- .../otel/metric/instrument/syncint64.go | 85 --- .../metric/internal/global/instruments.go | 355 ----------- .../otel/metric/internal/global/meter.go | 354 ----------- .../go.opentelemetry.io/otel/metric/meter.go | 138 ----- .../go.opentelemetry.io/otel/metric/metric.go | 538 ++++++++++++++++ .../otel/metric/metric_instrument.go | 464 ++++++++++++++ .../go.opentelemetry.io/otel/metric/noop.go | 127 +--- .../otel/metric/number/doc.go | 23 + .../otel/metric/number/kind_string.go | 24 + .../otel/metric/number/number.go | 538 ++++++++++++++++ .../otel/metric/sdkapi/descriptor.go | 70 +++ .../otel/metric/sdkapi/instrumentkind.go | 80 +++ .../metric/sdkapi/instrumentkind_string.go | 28 + .../otel/metric/sdkapi/noop.go | 66 ++ .../otel/metric/sdkapi/sdkapi.go | 159 +++++ .../otel/metric/unit/doc.go | 20 + .../header.go => metric/unit/unit.go} | 16 +- .../collector/trace/v1/trace_config.pb.go | 573 ++++++++++++++++++ .../collector/trace/v1/trace_service.pb.go | 191 ++---- .../collector/trace/v1/trace_service.pb.gw.go | 14 +- .../trace/v1/trace_service_grpc.pb.go | 12 +- .../proto/otlp/common/v1/common.pb.go | 182 ++++-- .../proto/otlp/resource/v1/resource.pb.go | 31 +- .../proto/otlp/trace/v1/trace.pb.go | 342 ++++++----- .../grpc/attributes/attributes.go | 2 +- vendor/google.golang.org/grpc/backoff.go | 2 +- .../grpc/balancer/balancer.go | 31 - .../grpc/balancer/base/balancer.go | 4 +- .../grpc/balancer/conn_state_evaluator.go | 12 +- .../grpclb/grpc_lb_v1/load_balancer.pb.go | 9 +- .../grpc/balancer/grpclb/grpclb.go | 28 +- .../balancer/grpclb/grpclb_remote_balancer.go | 2 +- .../grpc/balancer_conn_wrappers.go | 71 +-- .../grpc_binarylog_v1/binarylog.pb.go | 20 +- .../grpc/channelz/channelz.go | 2 +- vendor/google.golang.org/grpc/clientconn.go | 173 ++++-- .../internal/proto/grpc_gcp/altscontext.pb.go | 7 +- .../internal/proto/grpc_gcp/handshaker.pb.go | 9 +- .../grpc_gcp/transport_security_common.pb.go | 7 +- .../grpc/credentials/credentials.go | 20 +- .../grpc/credentials/google/xds.go | 1 - .../grpc/credentials/oauth/oauth.go | 8 +- .../google.golang.org/grpc/credentials/tls.go | 6 +- vendor/google.golang.org/grpc/dialoptions.go | 25 +- .../grpc/encoding/encoding.go | 7 +- .../grpc/encoding/gzip/gzip.go | 7 +- .../grpc/grpclog/loggerv2.go | 9 +- .../grpc/health/grpc_health_v1/health.pb.go | 7 +- .../grpc/internal/binarylog/env_config.go | 18 +- .../grpc/internal/binarylog/method_logger.go | 128 ++-- .../grpc/internal/binarylog/sink.go | 12 +- .../grpc/internal/channelz/types.go | 16 +- .../grpc/internal/envconfig/envconfig.go | 39 +- .../grpc/internal/envconfig/xds.go | 31 +- .../googlecloud/manufacturer_linux.go | 4 +- .../grpc/internal/grpclog/grpclog.go | 2 +- .../grpc/internal/grpcsync/oncefunc.go | 32 - .../grpc/internal/grpcutil/compressor.go | 47 -- .../grpc/internal/grpcutil/method.go | 1 + .../grpc/internal/internal.go | 3 - .../internal/resolver/dns/dns_resolver.go | 6 +- .../resolver/passthrough/passthrough.go | 11 +- .../grpc/internal/resolver/unix/unix.go | 4 +- .../internal/serviceconfig/serviceconfig.go | 8 +- .../grpc/internal/status/status.go | 10 - .../grpc/internal/transport/controlbuf.go | 62 +- .../grpc/internal/transport/defaults.go | 6 - .../grpc/internal/transport/handler_server.go | 53 +- .../grpc/internal/transport/http2_client.go | 261 +++----- .../grpc/internal/transport/http2_server.go | 142 ++--- .../grpc/internal/transport/transport.go | 16 +- .../grpc/metadata/metadata.go | 20 +- .../google.golang.org/grpc/picker_wrapper.go | 35 +- vendor/google.golang.org/grpc/pickfirst.go | 6 +- vendor/google.golang.org/grpc/preloader.go | 2 +- vendor/google.golang.org/grpc/regenerate.sh | 7 +- .../grpc/resolver/resolver.go | 36 +- vendor/google.golang.org/grpc/rpc_util.go | 56 +- vendor/google.golang.org/grpc/server.go | 79 +-- .../google.golang.org/grpc/service_config.go | 10 +- .../grpc/serviceconfig/serviceconfig.go | 2 +- .../google.golang.org/grpc/status/status.go | 12 +- vendor/google.golang.org/grpc/stream.go | 62 +- vendor/google.golang.org/grpc/tap/tap.go | 2 +- vendor/google.golang.org/grpc/version.go | 2 +- vendor/google.golang.org/grpc/vet.sh | 29 +- vendor/modules.txt | 52 +- 161 files changed, 6493 insertions(+), 6028 deletions(-) create mode 100644 vendor/github.com/golang/protobuf/descriptor/descriptor.go rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/LICENSE.txt (100%) create mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/internal/BUILD.bazel create mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/internal/errors.pb.go create mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/internal/errors.proto create mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/BUILD.bazel rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/context.go (79%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/convert.go (80%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/doc.go (100%) create mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/errors.go create mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/fieldmask.go rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/handler.go (77%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/marshal_httpbodyproto.go (54%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/marshal_json.go (95%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/marshal_jsonpb.go (58%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/marshal_proto.go (93%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/marshaler.go (80%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/marshaler_registry.go (91%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/mux.go (59%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/pattern.go (57%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/runtime/proto2_convert.go (98%) create mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/proto_errors.go create mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/query.go rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/utilities/BUILD.bazel (59%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/utilities/doc.go (100%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/utilities/pattern.go (100%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/utilities/readerfactory.go (100%) rename vendor/github.com/grpc-ecosystem/grpc-gateway/{v2 => }/utilities/trie.go (98%) delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/BUILD.bazel delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/compile.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/fuzz.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/types.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go delete mode 100644 vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go rename vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/{config.go => grpctrace.go} (58%) delete mode 100644 vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/interceptorinfo.go delete mode 100644 vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/metadata_supplier.go delete mode 100644 vendor/go.opentelemetry.io/otel/exporters/otlp/internal/envconfig/envconfig.go delete mode 100644 vendor/go.opentelemetry.io/otel/exporters/otlp/internal/partialsuccess.go delete mode 100644 vendor/go.opentelemetry.io/otel/exporters/otlp/internal/wrappederror.go create mode 100644 vendor/go.opentelemetry.io/otel/internal/metric/LICENSE create mode 100644 vendor/go.opentelemetry.io/otel/internal/metric/global/meter.go rename vendor/go.opentelemetry.io/otel/{metric/internal/global/state.go => internal/metric/global/metric.go} (54%) rename vendor/go.opentelemetry.io/otel/{exporters/otlp/internal/config.go => internal/metric/registry/doc.go} (50%) create mode 100644 vendor/go.opentelemetry.io/otel/internal/metric/registry/registry.go delete mode 100644 vendor/go.opentelemetry.io/otel/metric/global/global.go create mode 100644 vendor/go.opentelemetry.io/otel/metric/global/metric.go delete mode 100644 vendor/go.opentelemetry.io/otel/metric/instrument/asyncfloat64.go delete mode 100644 vendor/go.opentelemetry.io/otel/metric/instrument/asyncint64.go delete mode 100644 vendor/go.opentelemetry.io/otel/metric/instrument/instrument.go delete mode 100644 vendor/go.opentelemetry.io/otel/metric/instrument/syncfloat64.go delete mode 100644 vendor/go.opentelemetry.io/otel/metric/instrument/syncint64.go delete mode 100644 vendor/go.opentelemetry.io/otel/metric/internal/global/instruments.go delete mode 100644 vendor/go.opentelemetry.io/otel/metric/internal/global/meter.go delete mode 100644 vendor/go.opentelemetry.io/otel/metric/meter.go create mode 100644 vendor/go.opentelemetry.io/otel/metric/metric.go create mode 100644 vendor/go.opentelemetry.io/otel/metric/metric_instrument.go create mode 100644 vendor/go.opentelemetry.io/otel/metric/number/doc.go create mode 100644 vendor/go.opentelemetry.io/otel/metric/number/kind_string.go create mode 100644 vendor/go.opentelemetry.io/otel/metric/number/number.go create mode 100644 vendor/go.opentelemetry.io/otel/metric/sdkapi/descriptor.go create mode 100644 vendor/go.opentelemetry.io/otel/metric/sdkapi/instrumentkind.go create mode 100644 vendor/go.opentelemetry.io/otel/metric/sdkapi/instrumentkind_string.go create mode 100644 vendor/go.opentelemetry.io/otel/metric/sdkapi/noop.go create mode 100644 vendor/go.opentelemetry.io/otel/metric/sdkapi/sdkapi.go create mode 100644 vendor/go.opentelemetry.io/otel/metric/unit/doc.go rename vendor/go.opentelemetry.io/otel/{exporters/otlp/internal/header.go => metric/unit/unit.go} (55%) create mode 100644 vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_config.pb.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcsync/oncefunc.go delete mode 100644 vendor/google.golang.org/grpc/internal/grpcutil/compressor.go diff --git a/vendor.mod b/vendor.mod index 3f7faca1c71fe..bd686ed5f2d30 100644 --- a/vendor.mod +++ b/vendor.mod @@ -99,6 +99,11 @@ require ( resenje.org/singleflight v0.3.0 ) +require ( + github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect + go.opentelemetry.io/otel/internal/metric v0.27.0 // indirect +) + require ( cloud.google.com/go v0.110.0 // indirect cloud.google.com/go/compute v1.18.0 // indirect @@ -147,7 +152,6 @@ require ( github.com/googleapis/gax-go/v2 v2.7.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-msgpack v0.5.5 // indirect github.com/hashicorp/go-sockaddr v1.0.2 // indirect @@ -175,18 +179,18 @@ require ( go.etcd.io/etcd/raft/v3 v3.5.6 // indirect go.etcd.io/etcd/server/v3 v3.5.6 // indirect go.opencensus.io v0.24.0 // indirect - go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.40.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.29.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.29.0 // indirect - go.opentelemetry.io/otel v1.14.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.14.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.14.0 // indirect - go.opentelemetry.io/otel/metric v0.37.0 // indirect - go.opentelemetry.io/otel/sdk v1.14.0 // indirect - go.opentelemetry.io/otel/trace v1.14.0 // indirect - go.opentelemetry.io/proto/otlp v0.19.0 // indirect + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.40.0 // indirect; indirect // replaced: see replace section for version used + go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.29.0 // indirect; indirect // replaced: see replace section for version used + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.29.0 // indirect; indirect // replaced: see replace section for version used + go.opentelemetry.io/otel v1.14.0 // indirect; indirect // replaced: see replace section for version used + go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.14.0 // indirect; indirect // replaced: see replace section for version used + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0 // indirect; indirect // replaced: see replace section for version used + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0 // indirect; indirect // replaced: see replace section for version used + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.14.0 // indirect; indirect // replaced: see replace section for version used + go.opentelemetry.io/otel/metric v0.37.0 // indirect; indirect // replaced: see replace section for version used + go.opentelemetry.io/otel/sdk v1.14.0 // indirect; indirect // replaced: see replace section for version used + go.opentelemetry.io/otel/trace v1.14.0 // indirect; indirect // replaced: see replace section for version used + go.opentelemetry.io/proto/otlp v0.19.0 // indirect; indirect // replaced: see replace section for version used go.uber.org/atomic v1.9.0 // indirect go.uber.org/multierr v1.8.0 // indirect go.uber.org/zap v1.21.0 // indirect @@ -198,3 +202,26 @@ require ( google.golang.org/appengine v1.6.7 // indirect k8s.io/klog/v2 v2.90.1 // indirect ) + +replace ( + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc => go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.29.0 + //go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace => go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.29.0 + //go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp => go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.29.0 + //go.opentelemetry.io/otel => go.opentelemetry.io/otel v1.4.1 + //go.opentelemetry.io/otel/exporters/jaeger => go.opentelemetry.io/otel/exporters/jaeger v1.4.1 + go.opentelemetry.io/otel/exporters/otlp/otlptrace => go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.4.1 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc => go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.4.1 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp => go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.4.1 + //go.opentelemetry.io/otel/exporters/otlp/internal/retry => go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.4.1 + go.opentelemetry.io/otel/internal/metric => go.opentelemetry.io/otel/internal/metric v0.27.0 + go.opentelemetry.io/otel/metric => go.opentelemetry.io/otel/metric v0.27.0 + //go.opentelemetry.io/otel/sdk => go.opentelemetry.io/otel/sdk v1.4.1 + //go.opentelemetry.io/otel/trace => go.opentelemetry.io/otel/trace v1.4.1 + go.opentelemetry.io/proto/otlp => go.opentelemetry.io/proto/otlp v0.12.0 + // pinning to older version to fix compatibility with BuildKit v0.11; + // - https://github.com/moby/buildkit/blob/v0.11.4/go.mod#L71-L81 + // - https://github.com/moby/buildkit/blob/v0.11.4/go.mod#L148-L151 + // see https://github.com/moby/moby/pull/44530#issuecomment-1460561806 + // FIXME(thaJeztah): remove once we update to BuildKit v0.12.x + google.golang.org/grpc => google.golang.org/grpc v1.50.1 +) diff --git a/vendor.sum b/vendor.sum index 9650f67f5e1de..2b6fa6cd99692 100644 --- a/vendor.sum +++ b/vendor.sum @@ -1,7 +1,6 @@ bazil.org/fuse v0.0.0-20160811212531-371fbbdaa898/go.mod h1:Xbm+BRKSBEpa4q4hTSxohYNQpsxXPbPry4JJWOB3LB8= bazil.org/fuse v0.0.0-20180421153158-65cc252bf669/go.mod h1:Xbm+BRKSBEpa4q4hTSxohYNQpsxXPbPry4JJWOB3LB8= cloud.google.com/go v0.25.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.31.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.37.2/go.mod h1:H8IAquKe2L30IxoupDgqTaQvKSwF/c8prYHynGIWQbA= @@ -236,7 +235,7 @@ github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0/go.mod h1:D/8v3k github.com/caarlos0/ctrlc v1.0.0/go.mod h1:CdXpj4rmq0q/1Eb44M9zi2nKB0QraNKuRGYGrrHhcQw= github.com/campoy/unique v0.0.0-20180121183637-88950e537e7e/go.mod h1:9IOqJGCPMSc6E5ydlp5NIonxObaeu/Iub/X03EKPVYo= github.com/cavaliercoder/go-cpio v0.0.0-20180626203310-925f9528c45e/go.mod h1:oDpT4efm8tSYHXV5tHSdRvBet/b/QzxZ+XyyPehvm3A= -github.com/cenkalti/backoff/v4 v4.1.1/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= +github.com/cenkalti/backoff/v4 v4.1.2/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= github.com/cenkalti/backoff/v4 v4.2.0 h1:HN5dHm3WBOgndBH6E8V0q2jIYIR3s9yglV8k/+MN3u4= github.com/cenkalti/backoff/v4 v4.2.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/census-instrumentation/opencensus-proto v0.2.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= @@ -264,12 +263,9 @@ github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cloudflare/cfssl v0.0.0-20180323000720-5d63dbd981b5 h1:PqZ3bA4yzwywivzk7PBQWngJp2/PAS0bWRZerKteicY= github.com/cloudflare/cfssl v0.0.0-20180323000720-5d63dbd981b5/go.mod h1:yMWuSON2oQp+43nFtAV/uvKQIFpSPerB57DCt9t8sSA= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= -github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/cockroachdb/datadriven v0.0.0-20200714090401-bf6692d28da5 h1:xD/lrqdvwsc+O2bjSSi3YqY73Ke3LAiSCx49aCesA0E= @@ -425,13 +421,7 @@ github.com/elazarl/goproxy v0.0.0-20170405201442-c4fc26588b6e/go.mod h1:/Zj4wYkg github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= github.com/emicklei/go-restful v2.9.5+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= -github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= @@ -540,8 +530,6 @@ github.com/golang-jwt/jwt/v4 v4.4.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w github.com/golang/gddo v0.0.0-20190904175337-72a348e765d2 h1:xisWqjiKEff2B0KfFYGpCqc3M3zdTz+OHQHRc09FeYk= github.com/golang/gddo v0.0.0-20190904175337-72a348e765d2/go.mod h1:xEhNfoBDX1hzLm2Nf80qUvZ2sVwoMZ8d6IE2SrsQfh4= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= -github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -549,8 +537,6 @@ github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4er github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:tluoj9z5200jBnyusfRPU2LqT6J+DAorxEvtC7LHB+E= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= @@ -698,9 +684,8 @@ github.com/grpc-ecosystem/grpc-gateway v1.8.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.2/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0 h1:BZHcxBETFHIdVyhyEfOvn/RdU/QGdLI4y34qQGjGWO0= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0/go.mod h1:hgWBS7lorOAVIJEQMi4ZsPv9hVvWI6+ch50m39Pf2Ks= github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645/go.mod h1:6iZfnjpejD4L/4DwD7NryNaJyCQdzwWwH2MWhCA90Kw= github.com/hanwen/go-fuse v1.0.0/go.mod h1:unqXarDXqzAk0rt98O2tVndEPIpUgLD9+rwFisZH3Ok= github.com/hanwen/go-fuse/v2 v2.0.3/go.mod h1:0EQM6aH2ctVpvZ6a+onrQ/vaykxh2GH7hy3e13vzTUY= @@ -1297,49 +1282,49 @@ go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.25.0/go.mod h1:E5NNboN0UqSAki0Atn9kVwaN7I+l25gGxDqBueo/74E= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.40.0 h1:5jD3teb4Qh7mx/nfzq4jO2WFFpvXD0vYWFDrdvNWmXk= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.40.0/go.mod h1:UMklln0+MRhZC4e3PwmN3pCtq4DyIadWw4yikh6bNrw= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.29.0 h1:n9b7AAdbQtQ0k9dm0Dm2/KUcUqtG8i2O15KzNaDze8c= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.29.0/go.mod h1:LsankqVDx4W+RhZNA5uWarULII/MBhF5qwCYxTuyXjs= go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.29.0 h1:Wjp9vsVSIEyvdiaECfqxY9xBqQ7JaSCGtvHgR4doXZk= go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.29.0/go.mod h1:vHItvsnJtp7ES++nFLLFBzUWny7fJQSvTlxFcqQGUr4= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.29.0 h1:SLme4Porm+UwX0DdHMxlwRt7FzPSE0sys81bet2o0pU= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.29.0/go.mod h1:tLYsuf2v8fZreBVwp9gVMhefZlLFZaUiNVSq8QxXRII= go.opentelemetry.io/otel v1.0.1/go.mod h1:OPEOD4jIT2SlZPMmwT6FqZz2C0ZNdQqiWcoK6M0SNFU= go.opentelemetry.io/otel v1.4.0/go.mod h1:jeAqMFKy2uLIxCtKxoFj0FAL5zAPKQagc3+GtBWakzk= +go.opentelemetry.io/otel v1.4.1/go.mod h1:StM6F/0fSwpd8dKWDCdRr7uRvEPYdW0hBSlbdTiUde4= go.opentelemetry.io/otel v1.14.0 h1:/79Huy8wbf5DnIPhemGB+zEPVwnN6fuQybr/SRXa6hM= go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU= +go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.4.1/go.mod h1:VpP4/RMn8bv8gNo9uK7/IMY4mtWLELsS+JIP0inH0h4= go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.14.0 h1:/fXHZHGvro6MVqV34fJzDhi7sHGpX3Ej/Qjmfn003ho= go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.14.0/go.mod h1:UFG7EBMRdXyFstOwH028U0sVf+AvukSGhF0g8+dmNG8= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.0.1/go.mod h1:Kv8liBeVNFkkkbilbgWRpV+wWuu+H5xdOT6HAgd30iw= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0 h1:TKf2uAs2ueguzLaxOCBXNpHxfO/aC7PAdDsSH0IbeRQ= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0/go.mod h1:HrbCVv40OOLTABmOn1ZWty6CHXkU8DK/Urc43tHug70= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.0.1/go.mod h1:xOvWoTOrQjxjW61xtOmD/WKGRYb/P4NzRo3bs65U6Rk= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0 h1:ap+y8RXX3Mu9apKVtOkM6WSFESLM8K3wNQyOU8sWHcc= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0/go.mod h1:5w41DY6S9gZrbjuq6Y+753e96WfPha5IcsOSZTtullM= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.14.0 h1:3jAYbRHQAqzLjd9I4tzxwJ8Pk/N6AqBcF6m1ZHrxG94= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.14.0/go.mod h1:+N7zNjIJv4K+DeX67XXET0P+eIciESgaFDBqh+ZJFS4= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.4.1 h1:WPpPsAAs8I2rA47v5u0558meKmmwm1Dj99ZbqCV8sZ8= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.4.1/go.mod h1:o5RW5o2pKpJLD5dNTCmjF1DorYwMeFJmb/rKr5sLaa8= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.4.1 h1:AxqDiGk8CorEXStMDZF5Hz9vo9Z7ZZ+I5m8JRl/ko40= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.4.1/go.mod h1:c6E4V3/U+miqjs/8l950wggHGL1qzlp0Ypj9xoGrPqo= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.4.1 h1:8qOago/OqoFclMUUj/184tZyRdDZFpcejSjbk5Jrl6Y= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.4.1/go.mod h1:VwYo0Hak6Efuy0TXsZs8o1hnV3dHDPNtDbycG0hI8+M= +go.opentelemetry.io/otel/internal/metric v0.27.0 h1:9dAVGAfFiiEq5NVB9FUJ5et+btbDQAUIJehJ+ikyryk= go.opentelemetry.io/otel/internal/metric v0.27.0/go.mod h1:n1CVxRqKqYZtqyTh9U/onvKapPGv7y/rpyOTI+LFNzw= +go.opentelemetry.io/otel/metric v0.27.0 h1:HhJPsGhJoKRSegPQILFbODU56NS/L1UE4fS1sC5kIwQ= go.opentelemetry.io/otel/metric v0.27.0/go.mod h1:raXDJ7uP2/Jc0nVZWQjJtzoyssOYWu/+pjZqRzfvZ7g= -go.opentelemetry.io/otel/metric v0.37.0 h1:pHDQuLQOZwYD+Km0eb657A25NaRzy0a+eLyKfDXedEs= -go.opentelemetry.io/otel/metric v0.37.0/go.mod h1:DmdaHfGt54iV6UKxsV9slj2bBRJcKC1B1uvDLIioc1s= go.opentelemetry.io/otel/sdk v1.0.1/go.mod h1:HrdXne+BiwsOHYYkBE5ysIcv2bvdZstxzmCQhxTcZkI= +go.opentelemetry.io/otel/sdk v1.4.1/go.mod h1:NBwHDgDIBYjwK2WNu1OPgsIc2IJzmBXNnvIJxJc8BpE= go.opentelemetry.io/otel/sdk v1.14.0 h1:PDCppFRDq8A1jL9v6KMI6dYesaq+DFcDZvjsoGvxGzY= go.opentelemetry.io/otel/sdk v1.14.0/go.mod h1:bwIC5TjrNG6QDCHNWvW4HLHtUQ4I+VQDsnjhvyZCALM= go.opentelemetry.io/otel/trace v1.0.1/go.mod h1:5g4i4fKLaX2BQpSBsxw8YYcgKpMMSW3x7ZTuYBr3sUk= go.opentelemetry.io/otel/trace v1.4.0/go.mod h1:uc3eRsqDfWs9R7b92xbQbU42/eTNz4N+gLP8qJCi4aE= +go.opentelemetry.io/otel/trace v1.4.1/go.mod h1:iYEVbroFCNut9QkwEczV9vMRPHNKSSwYZjulEtsmhFc= go.opentelemetry.io/otel/trace v1.14.0 h1:wp2Mmvj41tDsyAJXiWDWpfNsOiIyd38fy85pyKcFq/M= go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8= -go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= -go.opentelemetry.io/proto/otlp v0.9.0/go.mod h1:1vKfU9rv61e9EVGthD1zNvUbiwPcimSsOPU9brfSHJg= -go.opentelemetry.io/proto/otlp v0.19.0 h1:IVN6GR+mhC4s5yfcTbmzHYODqvWAp3ZedA2SJPI1Nnw= -go.opentelemetry.io/proto/otlp v0.19.0/go.mod h1:H7XAot3MsfNsj7EXtrA2q5xSNQ10UqI405h3+duxN4U= +go.opentelemetry.io/proto/otlp v0.12.0 h1:CMJ/3Wp7iOWES+CYLfnBv+DVmPbB+kmy9PJ92XvlR6c= +go.opentelemetry.io/proto/otlp v0.12.0/go.mod h1:TsIjwGWIx5VFYv9KGVlOpxoBl5Dy+63SUguV7GGvlSQ= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= -go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= +go.uber.org/goleak v1.1.12 h1:gZAh5/EyT/HQwlpkCy6wTpqfH9H8Lz8zbm3dZh+OyzA= +go.uber.org/goleak v1.1.12/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/multierr v1.8.0 h1:dg6GjLku4EH+249NNmoIciG9N/jURbDG+pFlTkhzIC8= @@ -1386,8 +1371,6 @@ golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EH golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20181217174547-8f45f776aaf1/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -1412,7 +1395,6 @@ golang.org/x/mod v0.7.0 h1:LapD9S96VoQRhi/GrNTqeBJFrUjs5UHCAtTlgwA5oZA= golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180911220305-26e67e76b6c3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1480,7 +1462,6 @@ golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4Iltr golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= golang.org/x/oauth2 v0.5.0 h1:HuArIo48skDwlrvM3sEdHXElYslAMsf3KwRkkW4MC4s= golang.org/x/oauth2 v0.5.0/go.mod h1:9/XBHVqLaWO3/BRHs5jbpYCnOZVjj5V0ndyaAM7KB4I= @@ -1622,14 +1603,12 @@ golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181117154741-2ddaf7f79a09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181219222714-6e267b5cc78e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190110163146-51295c7ec13a/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190221204921-83362c3779f5/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= @@ -1788,37 +1767,10 @@ google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= -google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4 h1:DdoeryqhaXp1LtT/emMP1BRJPHHKFi5akj/nbx/zNTA= google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4/go.mod h1:NWraEVixdDnqcqQ30jipen1STv2r/n24Wb7twVTGR4s= -google.golang.org/grpc v0.0.0-20160317175043-d3ddb4469d5a/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= -google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= -google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio= -google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= -google.golang.org/grpc v1.41.0/go.mod h1:U3l9uK9J0sini8mHphKoXyaqDA/8VyGnDee1zzIUK6k= -google.golang.org/grpc v1.42.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= -google.golang.org/grpc v1.53.0 h1:LAv2ds7cmFV/XTS3XG1NneeENYrXGmorPxsBbptIjNc= -google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= +google.golang.org/grpc v1.50.1 h1:DS/BukOZWp8s6p4Dt/tOaJaTQyPyOoCcrjroHuCeLzY= +google.golang.org/grpc v1.50.1/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -1877,7 +1829,6 @@ gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= gotest.tools/v3 v3.4.0 h1:ZazjZUfuVeZGLAmlKKuyv3IKP5orXcwtOwDQH6YVr6o= gotest.tools/v3 v3.4.0/go.mod h1:CtbdzLSsqVhDgMtKsx03ird5YTGB3ar27v0u/yKBW5g= grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o= -honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20180920025451-e3ad64cb4ed3/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/vendor/github.com/golang/protobuf/descriptor/descriptor.go b/vendor/github.com/golang/protobuf/descriptor/descriptor.go new file mode 100644 index 0000000000000..ffde8a65081e4 --- /dev/null +++ b/vendor/github.com/golang/protobuf/descriptor/descriptor.go @@ -0,0 +1,180 @@ +// Copyright 2016 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 descriptor provides functions for obtaining the protocol buffer +// descriptors of generated Go types. +// +// Deprecated: See the "google.golang.org/protobuf/reflect/protoreflect" package +// for how to obtain an EnumDescriptor or MessageDescriptor in order to +// programatically interact with the protobuf type system. +package descriptor + +import ( + "bytes" + "compress/gzip" + "io/ioutil" + "sync" + + "github.com/golang/protobuf/proto" + "google.golang.org/protobuf/reflect/protodesc" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/runtime/protoimpl" + + descriptorpb "github.com/golang/protobuf/protoc-gen-go/descriptor" +) + +// Message is proto.Message with a method to return its descriptor. +// +// Deprecated: The Descriptor method may not be generated by future +// versions of protoc-gen-go, meaning that this interface may not +// be implemented by many concrete message types. +type Message interface { + proto.Message + Descriptor() ([]byte, []int) +} + +// ForMessage returns the file descriptor proto containing +// the message and the message descriptor proto for the message itself. +// The returned proto messages must not be mutated. +// +// Deprecated: Not all concrete message types satisfy the Message interface. +// Use MessageDescriptorProto instead. If possible, the calling code should +// be rewritten to use protobuf reflection instead. +// See package "google.golang.org/protobuf/reflect/protoreflect" for details. +func ForMessage(m Message) (*descriptorpb.FileDescriptorProto, *descriptorpb.DescriptorProto) { + return MessageDescriptorProto(m) +} + +type rawDesc struct { + fileDesc []byte + indexes []int +} + +var rawDescCache sync.Map // map[protoreflect.Descriptor]*rawDesc + +func deriveRawDescriptor(d protoreflect.Descriptor) ([]byte, []int) { + // Fast-path: check whether raw descriptors are already cached. + origDesc := d + if v, ok := rawDescCache.Load(origDesc); ok { + return v.(*rawDesc).fileDesc, v.(*rawDesc).indexes + } + + // Slow-path: derive the raw descriptor from the v2 descriptor. + + // Start with the leaf (a given enum or message declaration) and + // ascend upwards until we hit the parent file descriptor. + var idxs []int + for { + idxs = append(idxs, d.Index()) + d = d.Parent() + if d == nil { + // TODO: We could construct a FileDescriptor stub for standalone + // descriptors to satisfy the API. + return nil, nil + } + if _, ok := d.(protoreflect.FileDescriptor); ok { + break + } + } + + // Obtain the raw file descriptor. + fd := d.(protoreflect.FileDescriptor) + b, _ := proto.Marshal(protodesc.ToFileDescriptorProto(fd)) + file := protoimpl.X.CompressGZIP(b) + + // Reverse the indexes, since we populated it in reverse. + for i, j := 0, len(idxs)-1; i < j; i, j = i+1, j-1 { + idxs[i], idxs[j] = idxs[j], idxs[i] + } + + if v, ok := rawDescCache.LoadOrStore(origDesc, &rawDesc{file, idxs}); ok { + return v.(*rawDesc).fileDesc, v.(*rawDesc).indexes + } + return file, idxs +} + +// EnumRawDescriptor returns the GZIP'd raw file descriptor representing +// the enum and the index path to reach the enum declaration. +// The returned slices must not be mutated. +func EnumRawDescriptor(e proto.GeneratedEnum) ([]byte, []int) { + if ev, ok := e.(interface{ EnumDescriptor() ([]byte, []int) }); ok { + return ev.EnumDescriptor() + } + ed := protoimpl.X.EnumTypeOf(e) + return deriveRawDescriptor(ed.Descriptor()) +} + +// MessageRawDescriptor returns the GZIP'd raw file descriptor representing +// the message and the index path to reach the message declaration. +// The returned slices must not be mutated. +func MessageRawDescriptor(m proto.GeneratedMessage) ([]byte, []int) { + if mv, ok := m.(interface{ Descriptor() ([]byte, []int) }); ok { + return mv.Descriptor() + } + md := protoimpl.X.MessageTypeOf(m) + return deriveRawDescriptor(md.Descriptor()) +} + +var fileDescCache sync.Map // map[*byte]*descriptorpb.FileDescriptorProto + +func deriveFileDescriptor(rawDesc []byte) *descriptorpb.FileDescriptorProto { + // Fast-path: check whether descriptor protos are already cached. + if v, ok := fileDescCache.Load(&rawDesc[0]); ok { + return v.(*descriptorpb.FileDescriptorProto) + } + + // Slow-path: derive the descriptor proto from the GZIP'd message. + zr, err := gzip.NewReader(bytes.NewReader(rawDesc)) + if err != nil { + panic(err) + } + b, err := ioutil.ReadAll(zr) + if err != nil { + panic(err) + } + fd := new(descriptorpb.FileDescriptorProto) + if err := proto.Unmarshal(b, fd); err != nil { + panic(err) + } + if v, ok := fileDescCache.LoadOrStore(&rawDesc[0], fd); ok { + return v.(*descriptorpb.FileDescriptorProto) + } + return fd +} + +// EnumDescriptorProto returns the file descriptor proto representing +// the enum and the enum descriptor proto for the enum itself. +// The returned proto messages must not be mutated. +func EnumDescriptorProto(e proto.GeneratedEnum) (*descriptorpb.FileDescriptorProto, *descriptorpb.EnumDescriptorProto) { + rawDesc, idxs := EnumRawDescriptor(e) + if rawDesc == nil || idxs == nil { + return nil, nil + } + fd := deriveFileDescriptor(rawDesc) + if len(idxs) == 1 { + return fd, fd.EnumType[idxs[0]] + } + md := fd.MessageType[idxs[0]] + for _, i := range idxs[1 : len(idxs)-1] { + md = md.NestedType[i] + } + ed := md.EnumType[idxs[len(idxs)-1]] + return fd, ed +} + +// MessageDescriptorProto returns the file descriptor proto representing +// the message and the message descriptor proto for the message itself. +// The returned proto messages must not be mutated. +func MessageDescriptorProto(m proto.GeneratedMessage) (*descriptorpb.FileDescriptorProto, *descriptorpb.DescriptorProto) { + rawDesc, idxs := MessageRawDescriptor(m) + if rawDesc == nil || idxs == nil { + return nil, nil + } + fd := deriveFileDescriptor(rawDesc) + md := fd.MessageType[idxs[0]] + for _, i := range idxs[1:] { + md = md.NestedType[i] + } + return fd, md +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/LICENSE.txt b/vendor/github.com/grpc-ecosystem/grpc-gateway/LICENSE.txt similarity index 100% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/LICENSE.txt rename to vendor/github.com/grpc-ecosystem/grpc-gateway/LICENSE.txt diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/internal/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/internal/BUILD.bazel new file mode 100644 index 0000000000000..5242751fb2d5a --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/internal/BUILD.bazel @@ -0,0 +1,23 @@ +load("@rules_proto//proto:defs.bzl", "proto_library") +load("@io_bazel_rules_go//go:def.bzl", "go_library") +load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library") + +package(default_visibility = ["//visibility:public"]) + +proto_library( + name = "internal_proto", + srcs = ["errors.proto"], + deps = ["@com_google_protobuf//:any_proto"], +) + +go_proto_library( + name = "internal_go_proto", + importpath = "github.com/grpc-ecosystem/grpc-gateway/internal", + proto = ":internal_proto", +) + +go_library( + name = "go_default_library", + embed = [":internal_go_proto"], + importpath = "github.com/grpc-ecosystem/grpc-gateway/internal", +) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/internal/errors.pb.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/internal/errors.pb.go new file mode 100644 index 0000000000000..61101d7177f05 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/internal/errors.pb.go @@ -0,0 +1,189 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: internal/errors.proto + +package internal + +import ( + fmt "fmt" + proto "github.com/golang/protobuf/proto" + any "github.com/golang/protobuf/ptypes/any" + math "math" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package + +// Error is the generic error returned from unary RPCs. +type Error struct { + Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` + // This is to make the error more compatible with users that expect errors to be Status objects: + // https://github.com/grpc/grpc/blob/master/src/proto/grpc/status/status.proto + // It should be the exact same message as the Error field. + Code int32 `protobuf:"varint,2,opt,name=code,proto3" json:"code,omitempty"` + Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"` + Details []*any.Any `protobuf:"bytes,4,rep,name=details,proto3" json:"details,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Error) Reset() { *m = Error{} } +func (m *Error) String() string { return proto.CompactTextString(m) } +func (*Error) ProtoMessage() {} +func (*Error) Descriptor() ([]byte, []int) { + return fileDescriptor_9b093362ca6d1e03, []int{0} +} + +func (m *Error) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Error.Unmarshal(m, b) +} +func (m *Error) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Error.Marshal(b, m, deterministic) +} +func (m *Error) XXX_Merge(src proto.Message) { + xxx_messageInfo_Error.Merge(m, src) +} +func (m *Error) XXX_Size() int { + return xxx_messageInfo_Error.Size(m) +} +func (m *Error) XXX_DiscardUnknown() { + xxx_messageInfo_Error.DiscardUnknown(m) +} + +var xxx_messageInfo_Error proto.InternalMessageInfo + +func (m *Error) GetError() string { + if m != nil { + return m.Error + } + return "" +} + +func (m *Error) GetCode() int32 { + if m != nil { + return m.Code + } + return 0 +} + +func (m *Error) GetMessage() string { + if m != nil { + return m.Message + } + return "" +} + +func (m *Error) GetDetails() []*any.Any { + if m != nil { + return m.Details + } + return nil +} + +// StreamError is a response type which is returned when +// streaming rpc returns an error. +type StreamError struct { + GrpcCode int32 `protobuf:"varint,1,opt,name=grpc_code,json=grpcCode,proto3" json:"grpc_code,omitempty"` + HttpCode int32 `protobuf:"varint,2,opt,name=http_code,json=httpCode,proto3" json:"http_code,omitempty"` + Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"` + HttpStatus string `protobuf:"bytes,4,opt,name=http_status,json=httpStatus,proto3" json:"http_status,omitempty"` + Details []*any.Any `protobuf:"bytes,5,rep,name=details,proto3" json:"details,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *StreamError) Reset() { *m = StreamError{} } +func (m *StreamError) String() string { return proto.CompactTextString(m) } +func (*StreamError) ProtoMessage() {} +func (*StreamError) Descriptor() ([]byte, []int) { + return fileDescriptor_9b093362ca6d1e03, []int{1} +} + +func (m *StreamError) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_StreamError.Unmarshal(m, b) +} +func (m *StreamError) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_StreamError.Marshal(b, m, deterministic) +} +func (m *StreamError) XXX_Merge(src proto.Message) { + xxx_messageInfo_StreamError.Merge(m, src) +} +func (m *StreamError) XXX_Size() int { + return xxx_messageInfo_StreamError.Size(m) +} +func (m *StreamError) XXX_DiscardUnknown() { + xxx_messageInfo_StreamError.DiscardUnknown(m) +} + +var xxx_messageInfo_StreamError proto.InternalMessageInfo + +func (m *StreamError) GetGrpcCode() int32 { + if m != nil { + return m.GrpcCode + } + return 0 +} + +func (m *StreamError) GetHttpCode() int32 { + if m != nil { + return m.HttpCode + } + return 0 +} + +func (m *StreamError) GetMessage() string { + if m != nil { + return m.Message + } + return "" +} + +func (m *StreamError) GetHttpStatus() string { + if m != nil { + return m.HttpStatus + } + return "" +} + +func (m *StreamError) GetDetails() []*any.Any { + if m != nil { + return m.Details + } + return nil +} + +func init() { + proto.RegisterType((*Error)(nil), "grpc.gateway.runtime.Error") + proto.RegisterType((*StreamError)(nil), "grpc.gateway.runtime.StreamError") +} + +func init() { proto.RegisterFile("internal/errors.proto", fileDescriptor_9b093362ca6d1e03) } + +var fileDescriptor_9b093362ca6d1e03 = []byte{ + // 252 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x90, 0xc1, 0x4a, 0xc4, 0x30, + 0x10, 0x86, 0x89, 0xbb, 0x75, 0xdb, 0xe9, 0x2d, 0x54, 0x88, 0xee, 0xc1, 0xb2, 0xa7, 0x9e, 0x52, + 0xd0, 0x27, 0xd0, 0xc5, 0x17, 0xe8, 0xde, 0xbc, 0x2c, 0xd9, 0xdd, 0x31, 0x16, 0xda, 0xa4, 0x24, + 0x53, 0xa4, 0xf8, 0x56, 0x3e, 0xa1, 0x24, 0xa5, 0xb0, 0x27, 0xf1, 0xd6, 0xf9, 0xfb, 0xcf, 0x7c, + 0x1f, 0x81, 0xbb, 0xd6, 0x10, 0x3a, 0xa3, 0xba, 0x1a, 0x9d, 0xb3, 0xce, 0xcb, 0xc1, 0x59, 0xb2, + 0xbc, 0xd0, 0x6e, 0x38, 0x4b, 0xad, 0x08, 0xbf, 0xd4, 0x24, 0xdd, 0x68, 0xa8, 0xed, 0xf1, 0xe1, + 0x5e, 0x5b, 0xab, 0x3b, 0xac, 0x63, 0xe7, 0x34, 0x7e, 0xd4, 0xca, 0x4c, 0xf3, 0xc2, 0xee, 0x1b, + 0x92, 0xb7, 0x70, 0x80, 0x17, 0x90, 0xc4, 0x4b, 0x82, 0x95, 0xac, 0xca, 0x9a, 0x79, 0xe0, 0x1c, + 0xd6, 0x67, 0x7b, 0x41, 0x71, 0x53, 0xb2, 0x2a, 0x69, 0xe2, 0x37, 0x17, 0xb0, 0xe9, 0xd1, 0x7b, + 0xa5, 0x51, 0xac, 0x62, 0x77, 0x19, 0xb9, 0x84, 0xcd, 0x05, 0x49, 0xb5, 0x9d, 0x17, 0xeb, 0x72, + 0x55, 0xe5, 0x4f, 0x85, 0x9c, 0xc9, 0x72, 0x21, 0xcb, 0x17, 0x33, 0x35, 0x4b, 0x69, 0xf7, 0xc3, + 0x20, 0x3f, 0x90, 0x43, 0xd5, 0xcf, 0x0e, 0x5b, 0xc8, 0x82, 0xff, 0x31, 0x22, 0x59, 0x44, 0xa6, + 0x21, 0xd8, 0x07, 0xec, 0x16, 0xb2, 0x4f, 0xa2, 0xe1, 0x78, 0xe5, 0x93, 0x86, 0x60, 0xff, 0xb7, + 0xd3, 0x23, 0xe4, 0x71, 0xcd, 0x93, 0xa2, 0x31, 0x78, 0x85, 0xbf, 0x10, 0xa2, 0x43, 0x4c, 0xae, + 0xa5, 0x93, 0x7f, 0x48, 0xbf, 0xc2, 0x7b, 0xba, 0xbc, 0xfd, 0xe9, 0x36, 0x56, 0x9e, 0x7f, 0x03, + 0x00, 0x00, 0xff, 0xff, 0xde, 0x72, 0x6b, 0x83, 0x8e, 0x01, 0x00, 0x00, +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/internal/errors.proto b/vendor/github.com/grpc-ecosystem/grpc-gateway/internal/errors.proto new file mode 100644 index 0000000000000..4fb212c6b690d --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/internal/errors.proto @@ -0,0 +1,26 @@ +syntax = "proto3"; +package grpc.gateway.runtime; +option go_package = "internal"; + +import "google/protobuf/any.proto"; + +// Error is the generic error returned from unary RPCs. +message Error { + string error = 1; + // This is to make the error more compatible with users that expect errors to be Status objects: + // https://github.com/grpc/grpc/blob/master/src/proto/grpc/status/status.proto + // It should be the exact same message as the Error field. + int32 code = 2; + string message = 3; + repeated google.protobuf.Any details = 4; +} + +// StreamError is a response type which is returned when +// streaming rpc returns an error. +message StreamError { + int32 grpc_code = 1; + int32 http_code = 2; + string message = 3; + string http_status = 4; + repeated google.protobuf.Any details = 5; +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/BUILD.bazel new file mode 100644 index 0000000000000..58b72b9cf7513 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/BUILD.bazel @@ -0,0 +1,85 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +package(default_visibility = ["//visibility:public"]) + +go_library( + name = "go_default_library", + srcs = [ + "context.go", + "convert.go", + "doc.go", + "errors.go", + "fieldmask.go", + "handler.go", + "marshal_httpbodyproto.go", + "marshal_json.go", + "marshal_jsonpb.go", + "marshal_proto.go", + "marshaler.go", + "marshaler_registry.go", + "mux.go", + "pattern.go", + "proto2_convert.go", + "proto_errors.go", + "query.go", + ], + importpath = "github.com/grpc-ecosystem/grpc-gateway/runtime", + deps = [ + "//internal:go_default_library", + "//utilities:go_default_library", + "@com_github_golang_protobuf//descriptor:go_default_library_gen", + "@com_github_golang_protobuf//jsonpb:go_default_library_gen", + "@com_github_golang_protobuf//proto:go_default_library", + "@go_googleapis//google/api:httpbody_go_proto", + "@io_bazel_rules_go//proto/wkt:any_go_proto", + "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", + "@io_bazel_rules_go//proto/wkt:duration_go_proto", + "@io_bazel_rules_go//proto/wkt:field_mask_go_proto", + "@io_bazel_rules_go//proto/wkt:timestamp_go_proto", + "@io_bazel_rules_go//proto/wkt:wrappers_go_proto", + "@org_golang_google_grpc//codes:go_default_library", + "@org_golang_google_grpc//grpclog:go_default_library", + "@org_golang_google_grpc//metadata:go_default_library", + "@org_golang_google_grpc//status:go_default_library", + ], +) + +go_test( + name = "go_default_test", + size = "small", + srcs = [ + "context_test.go", + "convert_test.go", + "errors_test.go", + "fieldmask_test.go", + "handler_test.go", + "marshal_httpbodyproto_test.go", + "marshal_json_test.go", + "marshal_jsonpb_test.go", + "marshal_proto_test.go", + "marshaler_registry_test.go", + "mux_test.go", + "pattern_test.go", + "query_test.go", + ], + embed = [":go_default_library"], + deps = [ + "//internal:go_default_library", + "//runtime/internal/examplepb:go_default_library", + "//utilities:go_default_library", + "@com_github_golang_protobuf//jsonpb:go_default_library_gen", + "@com_github_golang_protobuf//proto:go_default_library", + "@com_github_golang_protobuf//ptypes:go_default_library_gen", + "@go_googleapis//google/api:httpbody_go_proto", + "@go_googleapis//google/rpc:errdetails_go_proto", + "@io_bazel_rules_go//proto/wkt:duration_go_proto", + "@io_bazel_rules_go//proto/wkt:empty_go_proto", + "@io_bazel_rules_go//proto/wkt:field_mask_go_proto", + "@io_bazel_rules_go//proto/wkt:struct_go_proto", + "@io_bazel_rules_go//proto/wkt:timestamp_go_proto", + "@io_bazel_rules_go//proto/wkt:wrappers_go_proto", + "@org_golang_google_grpc//codes:go_default_library", + "@org_golang_google_grpc//metadata:go_default_library", + "@org_golang_google_grpc//status:go_default_library", + ], +) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/context.go similarity index 79% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/context.go index fb57b9366eab1..d8cbd4cc96b03 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/context.go @@ -41,19 +41,6 @@ var ( DefaultContextTimeout = 0 * time.Second ) -type ( - rpcMethodKey struct{} - httpPathPatternKey struct{} - - AnnotateContextOption func(ctx context.Context) context.Context -) - -func WithHTTPPathPattern(pattern string) AnnotateContextOption { - return func(ctx context.Context) context.Context { - return withHTTPPathPattern(ctx, pattern) - } -} - func decodeBinHeader(v string) ([]byte, error) { if len(v)%4 == 0 { // Input was padded, or padding was not necessary. @@ -69,8 +56,8 @@ At a minimum, the RemoteAddr is included in the fashion of "X-Forwarded-For", except that the forwarded destination is not another HTTP service but rather a gRPC service. */ -func AnnotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcMethodName string, options ...AnnotateContextOption) (context.Context, error) { - ctx, md, err := annotateContext(ctx, mux, req, rpcMethodName, options...) +func AnnotateContext(ctx context.Context, mux *ServeMux, req *http.Request) (context.Context, error) { + ctx, md, err := annotateContext(ctx, mux, req) if err != nil { return nil, err } @@ -83,8 +70,8 @@ func AnnotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM // AnnotateIncomingContext adds context information such as metadata from the request. // Attach metadata as incoming context. -func AnnotateIncomingContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcMethodName string, options ...AnnotateContextOption) (context.Context, error) { - ctx, md, err := annotateContext(ctx, mux, req, rpcMethodName, options...) +func AnnotateIncomingContext(ctx context.Context, mux *ServeMux, req *http.Request) (context.Context, error) { + ctx, md, err := annotateContext(ctx, mux, req) if err != nil { return nil, err } @@ -95,11 +82,7 @@ func AnnotateIncomingContext(ctx context.Context, mux *ServeMux, req *http.Reque return metadata.NewIncomingContext(ctx, md), nil } -func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcMethodName string, options ...AnnotateContextOption) (context.Context, metadata.MD, error) { - ctx = withRPCMethod(ctx, rpcMethodName) - for _, o := range options { - ctx = o(ctx) - } +func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request) (context.Context, metadata.MD, error) { var pairs []string timeout := DefaultContextTimeout if tm := req.Header.Get(metadataGrpcTimeout); tm != "" { @@ -149,7 +132,6 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM } if timeout != 0 { - //nolint:govet // The context outlives this function ctx, _ = context.WithTimeout(ctx, timeout) } if len(pairs) == 0 { @@ -307,39 +289,3 @@ func isPermanentHTTPHeader(hdr string) bool { } return false } - -// RPCMethod returns the method string for the server context. The returned -// string is in the format of "/package.service/method". -func RPCMethod(ctx context.Context) (string, bool) { - m := ctx.Value(rpcMethodKey{}) - if m == nil { - return "", false - } - ms, ok := m.(string) - if !ok { - return "", false - } - return ms, true -} - -func withRPCMethod(ctx context.Context, rpcMethodName string) context.Context { - return context.WithValue(ctx, rpcMethodKey{}, rpcMethodName) -} - -// HTTPPathPattern returns the HTTP path pattern string relating to the HTTP handler, if one exists. -// The format of the returned string is defined by the google.api.http path template type. -func HTTPPathPattern(ctx context.Context) (string, bool) { - m := ctx.Value(httpPathPatternKey{}) - if m == nil { - return "", false - } - ms, ok := m.(string) - if !ok { - return "", false - } - return ms, true -} - -func withHTTPPathPattern(ctx context.Context, httpPathPattern string) context.Context { - return context.WithValue(ctx, httpPathPatternKey{}, httpPathPattern) -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/convert.go similarity index 80% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/convert.go index e6bc4e6ceece1..2c279344dc414 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/convert.go @@ -6,10 +6,10 @@ import ( "strconv" "strings" - "google.golang.org/protobuf/encoding/protojson" - "google.golang.org/protobuf/types/known/durationpb" - "google.golang.org/protobuf/types/known/timestamppb" - "google.golang.org/protobuf/types/known/wrapperspb" + "github.com/golang/protobuf/jsonpb" + "github.com/golang/protobuf/ptypes/duration" + "github.com/golang/protobuf/ptypes/timestamp" + "github.com/golang/protobuf/ptypes/wrappers" ) // String just returns the given string. @@ -205,11 +205,9 @@ func BytesSlice(val, sep string) ([][]byte, error) { } // Timestamp converts the given RFC3339 formatted string into a timestamp.Timestamp. -func Timestamp(val string) (*timestamppb.Timestamp, error) { - var r timestamppb.Timestamp - val = strconv.Quote(strings.Trim(val, `"`)) - unmarshaler := &protojson.UnmarshalOptions{} - err := unmarshaler.Unmarshal([]byte(val), &r) +func Timestamp(val string) (*timestamp.Timestamp, error) { + var r timestamp.Timestamp + err := jsonpb.UnmarshalString(val, &r) if err != nil { return nil, err } @@ -217,11 +215,9 @@ func Timestamp(val string) (*timestamppb.Timestamp, error) { } // Duration converts the given string into a timestamp.Duration. -func Duration(val string) (*durationpb.Duration, error) { - var r durationpb.Duration - val = strconv.Quote(strings.Trim(val, `"`)) - unmarshaler := &protojson.UnmarshalOptions{} - err := unmarshaler.Unmarshal([]byte(val), &r) +func Duration(val string) (*duration.Duration, error) { + var r duration.Duration + err := jsonpb.UnmarshalString(val, &r) if err != nil { return nil, err } @@ -269,54 +265,54 @@ func EnumSlice(val, sep string, enumValMap map[string]int32) ([]int32, error) { */ // StringValue well-known type support as wrapper around string type -func StringValue(val string) (*wrapperspb.StringValue, error) { - return &wrapperspb.StringValue{Value: val}, nil +func StringValue(val string) (*wrappers.StringValue, error) { + return &wrappers.StringValue{Value: val}, nil } // FloatValue well-known type support as wrapper around float32 type -func FloatValue(val string) (*wrapperspb.FloatValue, error) { +func FloatValue(val string) (*wrappers.FloatValue, error) { parsedVal, err := Float32(val) - return &wrapperspb.FloatValue{Value: parsedVal}, err + return &wrappers.FloatValue{Value: parsedVal}, err } // DoubleValue well-known type support as wrapper around float64 type -func DoubleValue(val string) (*wrapperspb.DoubleValue, error) { +func DoubleValue(val string) (*wrappers.DoubleValue, error) { parsedVal, err := Float64(val) - return &wrapperspb.DoubleValue{Value: parsedVal}, err + return &wrappers.DoubleValue{Value: parsedVal}, err } // BoolValue well-known type support as wrapper around bool type -func BoolValue(val string) (*wrapperspb.BoolValue, error) { +func BoolValue(val string) (*wrappers.BoolValue, error) { parsedVal, err := Bool(val) - return &wrapperspb.BoolValue{Value: parsedVal}, err + return &wrappers.BoolValue{Value: parsedVal}, err } // Int32Value well-known type support as wrapper around int32 type -func Int32Value(val string) (*wrapperspb.Int32Value, error) { +func Int32Value(val string) (*wrappers.Int32Value, error) { parsedVal, err := Int32(val) - return &wrapperspb.Int32Value{Value: parsedVal}, err + return &wrappers.Int32Value{Value: parsedVal}, err } // UInt32Value well-known type support as wrapper around uint32 type -func UInt32Value(val string) (*wrapperspb.UInt32Value, error) { +func UInt32Value(val string) (*wrappers.UInt32Value, error) { parsedVal, err := Uint32(val) - return &wrapperspb.UInt32Value{Value: parsedVal}, err + return &wrappers.UInt32Value{Value: parsedVal}, err } // Int64Value well-known type support as wrapper around int64 type -func Int64Value(val string) (*wrapperspb.Int64Value, error) { +func Int64Value(val string) (*wrappers.Int64Value, error) { parsedVal, err := Int64(val) - return &wrapperspb.Int64Value{Value: parsedVal}, err + return &wrappers.Int64Value{Value: parsedVal}, err } // UInt64Value well-known type support as wrapper around uint64 type -func UInt64Value(val string) (*wrapperspb.UInt64Value, error) { +func UInt64Value(val string) (*wrappers.UInt64Value, error) { parsedVal, err := Uint64(val) - return &wrapperspb.UInt64Value{Value: parsedVal}, err + return &wrappers.UInt64Value{Value: parsedVal}, err } // BytesValue well-known type support as wrapper around bytes[] type -func BytesValue(val string) (*wrapperspb.BytesValue, error) { +func BytesValue(val string) (*wrappers.BytesValue, error) { parsedVal, err := Bytes(val) - return &wrapperspb.BytesValue{Value: parsedVal}, err + return &wrappers.BytesValue{Value: parsedVal}, err } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/doc.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/doc.go similarity index 100% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/doc.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/doc.go diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/errors.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/errors.go new file mode 100644 index 0000000000000..b2ce743bddcd6 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/errors.go @@ -0,0 +1,186 @@ +package runtime + +import ( + "context" + "io" + "net/http" + "strings" + + "github.com/grpc-ecosystem/grpc-gateway/internal" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/status" +) + +// HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status. +// See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto +func HTTPStatusFromCode(code codes.Code) int { + switch code { + case codes.OK: + return http.StatusOK + case codes.Canceled: + return http.StatusRequestTimeout + case codes.Unknown: + return http.StatusInternalServerError + case codes.InvalidArgument: + return http.StatusBadRequest + case codes.DeadlineExceeded: + return http.StatusGatewayTimeout + case codes.NotFound: + return http.StatusNotFound + case codes.AlreadyExists: + return http.StatusConflict + case codes.PermissionDenied: + return http.StatusForbidden + case codes.Unauthenticated: + return http.StatusUnauthorized + case codes.ResourceExhausted: + return http.StatusTooManyRequests + case codes.FailedPrecondition: + // Note, this deliberately doesn't translate to the similarly named '412 Precondition Failed' HTTP response status. + return http.StatusBadRequest + case codes.Aborted: + return http.StatusConflict + case codes.OutOfRange: + return http.StatusBadRequest + case codes.Unimplemented: + return http.StatusNotImplemented + case codes.Internal: + return http.StatusInternalServerError + case codes.Unavailable: + return http.StatusServiceUnavailable + case codes.DataLoss: + return http.StatusInternalServerError + } + + grpclog.Infof("Unknown gRPC error code: %v", code) + return http.StatusInternalServerError +} + +var ( + // HTTPError replies to the request with an error. + // + // HTTPError is called: + // - From generated per-endpoint gateway handler code, when calling the backend results in an error. + // - From gateway runtime code, when forwarding the response message results in an error. + // + // The default value for HTTPError calls the custom error handler configured on the ServeMux via the + // WithProtoErrorHandler serve option if that option was used, calling GlobalHTTPErrorHandler otherwise. + // + // To customize the error handling of a particular ServeMux instance, use the WithProtoErrorHandler + // serve option. + // + // To customize the error format for all ServeMux instances not using the WithProtoErrorHandler serve + // option, set GlobalHTTPErrorHandler to a custom function. + // + // Setting this variable directly to customize error format is deprecated. + HTTPError = MuxOrGlobalHTTPError + + // GlobalHTTPErrorHandler is the HTTPError handler for all ServeMux instances not using the + // WithProtoErrorHandler serve option. + // + // You can set a custom function to this variable to customize error format. + GlobalHTTPErrorHandler = DefaultHTTPError + + // OtherErrorHandler handles gateway errors from parsing and routing client requests for all + // ServeMux instances not using the WithProtoErrorHandler serve option. + // + // It returns the following error codes: StatusMethodNotAllowed StatusNotFound StatusBadRequest + // + // To customize parsing and routing error handling of a particular ServeMux instance, use the + // WithProtoErrorHandler serve option. + // + // To customize parsing and routing error handling of all ServeMux instances not using the + // WithProtoErrorHandler serve option, set a custom function to this variable. + OtherErrorHandler = DefaultOtherErrorHandler +) + +// MuxOrGlobalHTTPError uses the mux-configured error handler, falling back to GlobalErrorHandler. +func MuxOrGlobalHTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error) { + if mux.protoErrorHandler != nil { + mux.protoErrorHandler(ctx, mux, marshaler, w, r, err) + } else { + GlobalHTTPErrorHandler(ctx, mux, marshaler, w, r, err) + } +} + +// DefaultHTTPError is the default implementation of HTTPError. +// If "err" is an error from gRPC system, the function replies with the status code mapped by HTTPStatusFromCode. +// If otherwise, it replies with http.StatusInternalServerError. +// +// The response body returned by this function is a JSON object, +// which contains a member whose key is "error" and whose value is err.Error(). +func DefaultHTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error) { + const fallback = `{"error": "failed to marshal error message"}` + + s, ok := status.FromError(err) + if !ok { + s = status.New(codes.Unknown, err.Error()) + } + + w.Header().Del("Trailer") + w.Header().Del("Transfer-Encoding") + + contentType := marshaler.ContentType() + // Check marshaler on run time in order to keep backwards compatibility + // An interface param needs to be added to the ContentType() function on + // the Marshal interface to be able to remove this check + if typeMarshaler, ok := marshaler.(contentTypeMarshaler); ok { + pb := s.Proto() + contentType = typeMarshaler.ContentTypeFromMessage(pb) + } + w.Header().Set("Content-Type", contentType) + + body := &internal.Error{ + Error: s.Message(), + Message: s.Message(), + Code: int32(s.Code()), + Details: s.Proto().GetDetails(), + } + + buf, merr := marshaler.Marshal(body) + if merr != nil { + grpclog.Infof("Failed to marshal error message %q: %v", body, merr) + w.WriteHeader(http.StatusInternalServerError) + if _, err := io.WriteString(w, fallback); err != nil { + grpclog.Infof("Failed to write response: %v", err) + } + return + } + + md, ok := ServerMetadataFromContext(ctx) + if !ok { + grpclog.Infof("Failed to extract ServerMetadata from context") + } + + handleForwardResponseServerMetadata(w, mux, md) + + // RFC 7230 https://tools.ietf.org/html/rfc7230#section-4.1.2 + // Unless the request includes a TE header field indicating "trailers" + // is acceptable, as described in Section 4.3, a server SHOULD NOT + // generate trailer fields that it believes are necessary for the user + // agent to receive. + var wantsTrailers bool + + if te := r.Header.Get("TE"); strings.Contains(strings.ToLower(te), "trailers") { + wantsTrailers = true + handleForwardResponseTrailerHeader(w, md) + w.Header().Set("Transfer-Encoding", "chunked") + } + + st := HTTPStatusFromCode(s.Code()) + w.WriteHeader(st) + if _, err := w.Write(buf); err != nil { + grpclog.Infof("Failed to write response: %v", err) + } + + if wantsTrailers { + handleForwardResponseTrailer(w, md) + } +} + +// DefaultOtherErrorHandler is the default implementation of OtherErrorHandler. +// It simply writes a string representation of the given error into "w". +func DefaultOtherErrorHandler(w http.ResponseWriter, _ *http.Request, msg string, code int) { + http.Error(w, msg, code) +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/fieldmask.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/fieldmask.go new file mode 100644 index 0000000000000..aef645e40b92d --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/fieldmask.go @@ -0,0 +1,89 @@ +package runtime + +import ( + "encoding/json" + "io" + "strings" + + descriptor2 "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/protoc-gen-go/descriptor" + "google.golang.org/genproto/protobuf/field_mask" +) + +func translateName(name string, md *descriptor.DescriptorProto) (string, *descriptor.DescriptorProto) { + // TODO - should really gate this with a test that the marshaller has used json names + if md != nil { + for _, f := range md.Field { + if f.JsonName != nil && f.Name != nil && *f.JsonName == name { + var subType *descriptor.DescriptorProto + + // If the field has a TypeName then we retrieve the nested type for translating the embedded message names. + if f.TypeName != nil { + typeSplit := strings.Split(*f.TypeName, ".") + typeName := typeSplit[len(typeSplit)-1] + for _, t := range md.NestedType { + if typeName == *t.Name { + subType = t + } + } + } + return *f.Name, subType + } + } + } + return name, nil +} + +// FieldMaskFromRequestBody creates a FieldMask printing all complete paths from the JSON body. +func FieldMaskFromRequestBody(r io.Reader, md *descriptor.DescriptorProto) (*field_mask.FieldMask, error) { + fm := &field_mask.FieldMask{} + var root interface{} + if err := json.NewDecoder(r).Decode(&root); err != nil { + if err == io.EOF { + return fm, nil + } + return nil, err + } + + queue := []fieldMaskPathItem{{node: root, md: md}} + for len(queue) > 0 { + // dequeue an item + item := queue[0] + queue = queue[1:] + + if m, ok := item.node.(map[string]interface{}); ok { + // if the item is an object, then enqueue all of its children + for k, v := range m { + protoName, subMd := translateName(k, item.md) + if subMsg, ok := v.(descriptor2.Message); ok { + _, subMd = descriptor2.ForMessage(subMsg) + } + + var path string + if item.path == "" { + path = protoName + } else { + path = item.path + "." + protoName + } + queue = append(queue, fieldMaskPathItem{path: path, node: v, md: subMd}) + } + } else if len(item.path) > 0 { + // otherwise, it's a leaf node so print its path + fm.Paths = append(fm.Paths, item.path) + } + } + + return fm, nil +} + +// fieldMaskPathItem stores a in-progress deconstruction of a path for a fieldmask +type fieldMaskPathItem struct { + // the list of prior fields leading up to node connected by dots + path string + + // a generic decoded json object the current item to inspect for further path extraction + node interface{} + + // descriptor for parent message + md *descriptor.DescriptorProto +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/handler.go similarity index 77% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/handler.go index d1e21df4810a0..e6e8f286e1294 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/handler.go @@ -2,19 +2,19 @@ package runtime import ( "context" + "errors" "fmt" "io" "net/http" "net/textproto" - "strings" - "google.golang.org/genproto/googleapis/api/httpbody" - "google.golang.org/grpc/codes" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/internal" "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" - "google.golang.org/protobuf/proto" ) +var errEmptyResponse = errors.New("empty response") + // ForwardResponseStream forwards the stream from gRPC server to REST client. func ForwardResponseStream(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, req *http.Request, recv func() (proto.Message, error), opts ...func(context.Context, http.ResponseWriter, proto.Message) error) { f, ok := w.(http.Flusher) @@ -33,6 +33,7 @@ func ForwardResponseStream(ctx context.Context, mux *ServeMux, marshaler Marshal handleForwardResponseServerMetadata(w, mux, md) w.Header().Set("Transfer-Encoding", "chunked") + w.Header().Set("Content-Type", marshaler.ContentType()) if err := handleForwardResponseOptions(ctx, w, nil, opts); err != nil { HTTPError(ctx, mux, marshaler, w, req, err) return @@ -60,17 +61,10 @@ func ForwardResponseStream(ctx context.Context, mux *ServeMux, marshaler Marshal return } - if !wroteHeader { - w.Header().Set("Content-Type", marshaler.ContentType(resp)) - } - var buf []byte - httpBody, isHTTPBody := resp.(*httpbody.HttpBody) switch { case resp == nil: - buf, err = marshaler.Marshal(errorChunk(status.New(codes.Internal, "empty response"))) - case isHTTPBody: - buf = httpBody.GetData() + buf, err = marshaler.Marshal(errorChunk(streamError(ctx, mux.streamErrorHandler, errEmptyResponse))) default: result := map[string]interface{}{"result": resp} if rb, ok := resp.(responseBody); ok { @@ -138,22 +132,15 @@ func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marsha } handleForwardResponseServerMetadata(w, mux, md) - - // RFC 7230 https://tools.ietf.org/html/rfc7230#section-4.1.2 - // Unless the request includes a TE header field indicating "trailers" - // is acceptable, as described in Section 4.3, a server SHOULD NOT - // generate trailer fields that it believes are necessary for the user - // agent to receive. - doForwardTrailers := requestAcceptsTrailers(req) - - if doForwardTrailers { - handleForwardResponseTrailerHeader(w, md) - w.Header().Set("Transfer-Encoding", "chunked") - } - handleForwardResponseTrailerHeader(w, md) - contentType := marshaler.ContentType(resp) + contentType := marshaler.ContentType() + // Check marshaler on run time in order to keep backwards compatibility + // An interface param needs to be added to the ContentType() function on + // the Marshal interface to be able to remove this check + if typeMarshaler, ok := marshaler.(contentTypeMarshaler); ok { + contentType = typeMarshaler.ContentTypeFromMessage(resp) + } w.Header().Set("Content-Type", contentType) if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil { @@ -177,14 +164,7 @@ func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marsha grpclog.Infof("Failed to write response: %v", err) } - if doForwardTrailers { - handleForwardResponseTrailer(w, md) - } -} - -func requestAcceptsTrailers(req *http.Request) bool { - te := req.Header.Get("TE") - return strings.Contains(strings.ToLower(te), "trailers") + handleForwardResponseTrailer(w, md) } func handleForwardResponseOptions(ctx context.Context, w http.ResponseWriter, resp proto.Message, opts []func(context.Context, http.ResponseWriter, proto.Message) error) error { @@ -201,13 +181,11 @@ func handleForwardResponseOptions(ctx context.Context, w http.ResponseWriter, re } func handleForwardResponseStreamError(ctx context.Context, wroteHeader bool, marshaler Marshaler, w http.ResponseWriter, req *http.Request, mux *ServeMux, err error) { - st := mux.streamErrorHandler(ctx, err) - msg := errorChunk(st) + serr := streamError(ctx, mux.streamErrorHandler, err) if !wroteHeader { - w.Header().Set("Content-Type", marshaler.ContentType(msg)) - w.WriteHeader(HTTPStatusFromCode(st.Code())) + w.WriteHeader(int(serr.HttpCode)) } - buf, merr := marshaler.Marshal(msg) + buf, merr := marshaler.Marshal(errorChunk(serr)) if merr != nil { grpclog.Infof("Failed to marshal an error: %v", merr) return @@ -218,6 +196,17 @@ func handleForwardResponseStreamError(ctx context.Context, wroteHeader bool, mar } } -func errorChunk(st *status.Status) map[string]proto.Message { - return map[string]proto.Message{"error": st.Proto()} +// streamError returns the payload for the final message in a response stream +// that represents the given err. +func streamError(ctx context.Context, errHandler StreamErrorHandlerFunc, err error) *StreamError { + serr := errHandler(ctx, err) + if serr != nil { + return serr + } + // TODO: log about misbehaving stream error handler? + return DefaultHTTPStreamErrorHandler(ctx, err) +} + +func errorChunk(err *StreamError) map[string]proto.Message { + return map[string]proto.Message{"error": (*internal.StreamError)(err)} } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_httpbodyproto.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_httpbodyproto.go similarity index 54% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_httpbodyproto.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_httpbodyproto.go index b86135c889b9f..525b0338c7471 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_httpbodyproto.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_httpbodyproto.go @@ -4,6 +4,13 @@ import ( "google.golang.org/genproto/googleapis/api/httpbody" ) +// SetHTTPBodyMarshaler overwrite the default marshaler with the HTTPBodyMarshaler +func SetHTTPBodyMarshaler(serveMux *ServeMux) { + serveMux.marshalers.mimeMap[MIMEWildcard] = &HTTPBodyMarshaler{ + Marshaler: &JSONPb{OrigName: true}, + } +} + // HTTPBodyMarshaler is a Marshaler which supports marshaling of a // google.api.HttpBody message as the full response body if it is // the actual message used as the response. If not, then this will @@ -12,14 +19,18 @@ type HTTPBodyMarshaler struct { Marshaler } -// ContentType returns its specified content type in case v is a -// google.api.HttpBody message, otherwise it will fall back to the default Marshalers -// content type. -func (h *HTTPBodyMarshaler) ContentType(v interface{}) string { +// ContentType implementation to keep backwards compatibility with marshal interface +func (h *HTTPBodyMarshaler) ContentType() string { + return h.ContentTypeFromMessage(nil) +} + +// ContentTypeFromMessage in case v is a google.api.HttpBody message it returns +// its specified content type otherwise fall back to the default Marshaler. +func (h *HTTPBodyMarshaler) ContentTypeFromMessage(v interface{}) string { if httpBody, ok := v.(*httpbody.HttpBody); ok { return httpBody.GetContentType() } - return h.Marshaler.ContentType(v) + return h.Marshaler.ContentType() } // Marshal marshals "v" by returning the body bytes if v is a diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_json.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json.go similarity index 95% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_json.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json.go index d6aa82578369a..f9d3a585a4c05 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_json.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_json.go @@ -15,7 +15,7 @@ import ( type JSONBuiltin struct{} // ContentType always Returns "application/json". -func (*JSONBuiltin) ContentType(_ interface{}) string { +func (*JSONBuiltin) ContentType() string { return "application/json" } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb.go similarity index 58% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb.go index 7387c8e397690..f0de351b212dd 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_jsonpb.go @@ -6,25 +6,21 @@ import ( "fmt" "io" "reflect" - "strconv" - "google.golang.org/protobuf/encoding/protojson" - "google.golang.org/protobuf/proto" + "github.com/golang/protobuf/jsonpb" + "github.com/golang/protobuf/proto" ) // JSONPb is a Marshaler which marshals/unmarshals into/from JSON -// with the "google.golang.org/protobuf/encoding/protojson" marshaler. -// It supports the full functionality of protobuf unlike JSONBuiltin. +// with the "github.com/golang/protobuf/jsonpb". +// It supports fully functionality of protobuf unlike JSONBuiltin. // // The NewDecoder method returns a DecoderWrapper, so the underlying // *json.Decoder methods can be used. -type JSONPb struct { - protojson.MarshalOptions - protojson.UnmarshalOptions -} +type JSONPb jsonpb.Marshaler // ContentType always returns "application/json". -func (*JSONPb) ContentType(_ interface{}) string { +func (*JSONPb) ContentType() string { return "application/json" } @@ -51,13 +47,7 @@ func (j *JSONPb) marshalTo(w io.Writer, v interface{}) error { _, err = w.Write(buf) return err } - b, err := j.MarshalOptions.Marshal(p) - if err != nil { - return err - } - - _, err = w.Write(b) - return err + return (*jsonpb.Marshaler)(j).Marshal(w, p) } var ( @@ -66,8 +56,8 @@ var ( ) // marshalNonProto marshals a non-message field of a protobuf message. -// This function does not correctly marshal arbitrary data structures into JSON, -// it is only capable of marshaling non-message field values of protobuf, +// This function does not correctly marshals arbitrary data structure into JSON, +// but it is only capable of marshaling non-message field values of protobuf, // i.e. primitive types, enums; pointers to primitives or enums; maps from // integer/string types to primitives/enums/pointers to messages. func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { @@ -84,7 +74,7 @@ func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { if rv.Kind() == reflect.Slice { if rv.IsNil() { - if j.EmitUnpopulated { + if j.EmitDefaults { return []byte("[]"), nil } return []byte("null"), nil @@ -103,37 +93,7 @@ func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { return nil, err } } - if err = j.marshalTo(&buf, rv.Index(i).Interface().(proto.Message)); err != nil { - return nil, err - } - } - err = buf.WriteByte(']') - if err != nil { - return nil, err - } - - return buf.Bytes(), nil - } - - if rv.Type().Elem().Implements(typeProtoEnum) { - var buf bytes.Buffer - err := buf.WriteByte('[') - if err != nil { - return nil, err - } - for i := 0; i < rv.Len(); i++ { - if i != 0 { - err = buf.WriteByte(',') - if err != nil { - return nil, err - } - } - if j.UseEnumNumbers { - _, err = buf.WriteString(strconv.FormatInt(rv.Index(i).Int(), 10)) - } else { - _, err = buf.WriteString("\"" + rv.Index(i).Interface().(protoEnum).String() + "\"") - } - if err != nil { + if err = (*jsonpb.Marshaler)(j).Marshal(&buf, rv.Index(i).Interface().(proto.Message)); err != nil { return nil, err } } @@ -160,7 +120,7 @@ func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { } return json.Marshal(m) } - if enum, ok := rv.Interface().(protoEnum); ok && !j.UseEnumNumbers { + if enum, ok := rv.Interface().(protoEnum); ok && !j.EnumsAsInts { return json.Marshal(enum.String()) } return json.Marshal(rv.Interface()) @@ -168,29 +128,25 @@ func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { // Unmarshal unmarshals JSON "data" into "v" func (j *JSONPb) Unmarshal(data []byte, v interface{}) error { - return unmarshalJSONPb(data, j.UnmarshalOptions, v) + return unmarshalJSONPb(data, v) } // NewDecoder returns a Decoder which reads JSON stream from "r". func (j *JSONPb) NewDecoder(r io.Reader) Decoder { d := json.NewDecoder(r) - return DecoderWrapper{ - Decoder: d, - UnmarshalOptions: j.UnmarshalOptions, - } + return DecoderWrapper{Decoder: d} } // DecoderWrapper is a wrapper around a *json.Decoder that adds // support for protos to the Decode method. type DecoderWrapper struct { *json.Decoder - protojson.UnmarshalOptions } // Decode wraps the embedded decoder's Decode method to support // protos using a jsonpb.Unmarshaler. func (d DecoderWrapper) Decode(v interface{}) error { - return decodeJSONPb(d.Decoder, d.UnmarshalOptions, v) + return decodeJSONPb(d.Decoder, v) } // NewEncoder returns an Encoder which writes JSON stream into "w". @@ -206,28 +162,21 @@ func (j *JSONPb) NewEncoder(w io.Writer) Encoder { }) } -func unmarshalJSONPb(data []byte, unmarshaler protojson.UnmarshalOptions, v interface{}) error { +func unmarshalJSONPb(data []byte, v interface{}) error { d := json.NewDecoder(bytes.NewReader(data)) - return decodeJSONPb(d, unmarshaler, v) + return decodeJSONPb(d, v) } -func decodeJSONPb(d *json.Decoder, unmarshaler protojson.UnmarshalOptions, v interface{}) error { +func decodeJSONPb(d *json.Decoder, v interface{}) error { p, ok := v.(proto.Message) if !ok { - return decodeNonProtoField(d, unmarshaler, v) + return decodeNonProtoField(d, v) } - - // Decode into bytes for marshalling - var b json.RawMessage - err := d.Decode(&b) - if err != nil { - return err - } - - return unmarshaler.Unmarshal([]byte(b), p) + unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: allowUnknownFields} + return unmarshaler.UnmarshalNext(d, p) } -func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions, v interface{}) error { +func decodeNonProtoField(d *json.Decoder, v interface{}) error { rv := reflect.ValueOf(v) if rv.Kind() != reflect.Ptr { return fmt.Errorf("%T is not a pointer", v) @@ -237,14 +186,8 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions rv.Set(reflect.New(rv.Type().Elem())) } if rv.Type().ConvertibleTo(typeProtoMessage) { - // Decode into bytes for marshalling - var b json.RawMessage - err := d.Decode(&b) - if err != nil { - return err - } - - return unmarshaler.Unmarshal([]byte(b), rv.Interface().(proto.Message)) + unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: allowUnknownFields} + return unmarshaler.UnmarshalNext(d, rv.Interface().(proto.Message)) } rv = rv.Elem() } @@ -268,45 +211,24 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions } bk := result[0] bv := reflect.New(rv.Type().Elem()) - if v == nil { - null := json.RawMessage("null") - v = &null - } - if err := unmarshalJSONPb([]byte(*v), unmarshaler, bv.Interface()); err != nil { + if err := unmarshalJSONPb([]byte(*v), bv.Interface()); err != nil { return err } rv.SetMapIndex(bk, bv.Elem()) } return nil } - if rv.Kind() == reflect.Slice { - var sl []json.RawMessage - if err := d.Decode(&sl); err != nil { - return err - } - if sl != nil { - rv.Set(reflect.MakeSlice(rv.Type(), 0, 0)) - } - for _, item := range sl { - bv := reflect.New(rv.Type().Elem()) - if err := unmarshalJSONPb([]byte(item), unmarshaler, bv.Interface()); err != nil { - return err - } - rv.Set(reflect.Append(rv, bv.Elem())) - } - return nil - } if _, ok := rv.Interface().(protoEnum); ok { var repr interface{} if err := d.Decode(&repr); err != nil { return err } - switch v := repr.(type) { + switch repr.(type) { case string: // TODO(yugui) Should use proto.StructProperties? return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface()) case float64: - rv.Set(reflect.ValueOf(int32(v)).Convert(rv.Type())) + rv.Set(reflect.ValueOf(int32(repr.(float64))).Convert(rv.Type())) return nil default: return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface()) @@ -320,8 +242,6 @@ type protoEnum interface { EnumDescriptor() ([]byte, []int) } -var typeProtoEnum = reflect.TypeOf((*protoEnum)(nil)).Elem() - var typeProtoMessage = reflect.TypeOf((*proto.Message)(nil)).Elem() // Delimiter for newline encoded JSON streams. @@ -329,16 +249,14 @@ func (j *JSONPb) Delimiter() []byte { return []byte("\n") } -var ( - convFromType = map[reflect.Kind]reflect.Value{ - reflect.String: reflect.ValueOf(String), - reflect.Bool: reflect.ValueOf(Bool), - reflect.Float64: reflect.ValueOf(Float64), - reflect.Float32: reflect.ValueOf(Float32), - reflect.Int64: reflect.ValueOf(Int64), - reflect.Int32: reflect.ValueOf(Int32), - reflect.Uint64: reflect.ValueOf(Uint64), - reflect.Uint32: reflect.ValueOf(Uint32), - reflect.Slice: reflect.ValueOf(Bytes), - } -) +// allowUnknownFields helps not to return an error when the destination +// is a struct and the input contains object keys which do not match any +// non-ignored, exported fields in the destination. +var allowUnknownFields = true + +// DisallowUnknownFields enables option in decoder (unmarshaller) to +// return an error when it finds an unknown field. This function must be +// called before using the JSON marshaller. +func DisallowUnknownFields() { + allowUnknownFields = false +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto.go similarity index 93% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto.go index 007f8f1a2c7f1..f65d1a2676b87 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshal_proto.go @@ -4,16 +4,15 @@ import ( "io" "errors" + "github.com/golang/protobuf/proto" "io/ioutil" - - "google.golang.org/protobuf/proto" ) // ProtoMarshaller is a Marshaller which marshals/unmarshals into/from serialize proto bytes type ProtoMarshaller struct{} // ContentType always returns "application/octet-stream". -func (*ProtoMarshaller) ContentType(_ interface{}) string { +func (*ProtoMarshaller) ContentType() string { return "application/octet-stream" } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler.go similarity index 80% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler.go index 2c0d25ff4935a..46153294217fd 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler.go @@ -16,9 +16,14 @@ type Marshaler interface { // NewEncoder returns an Encoder which writes bytes sequence into "w". NewEncoder(w io.Writer) Encoder // ContentType returns the Content-Type which this marshaler is responsible for. - // The parameter describes the type which is being marshalled, which can sometimes - // affect the content type returned. - ContentType(v interface{}) string + ContentType() string +} + +// Marshalers that implement contentTypeMarshaler will have their ContentTypeFromMessage method called +// to set the Content-Type header on the response +type contentTypeMarshaler interface { + // ContentTypeFromMessage returns the Content-Type this marshaler produces from the provided message + ContentTypeFromMessage(v interface{}) string } // Decoder decodes a byte sequence diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry.go similarity index 91% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry.go index a714de0240682..8dd5c24db4279 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/marshaler_registry.go @@ -6,7 +6,6 @@ import ( "net/http" "google.golang.org/grpc/grpclog" - "google.golang.org/protobuf/encoding/protojson" ) // MIMEWildcard is the fallback MIME type used for requests which do not match @@ -17,16 +16,7 @@ var ( acceptHeader = http.CanonicalHeaderKey("Accept") contentTypeHeader = http.CanonicalHeaderKey("Content-Type") - defaultMarshaler = &HTTPBodyMarshaler{ - Marshaler: &JSONPb{ - MarshalOptions: protojson.MarshalOptions{ - EmitUnpopulated: true, - }, - UnmarshalOptions: protojson.UnmarshalOptions{ - DiscardUnknown: true, - }, - }, - } + defaultMarshaler = &JSONPb{OrigName: true} ) // MarshalerForRequest returns the inbound/outbound marshalers for this request. diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/mux.go similarity index 59% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/mux.go index 46a4aabaf9555..523a9cb43c930 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/mux.go @@ -2,47 +2,28 @@ package runtime import ( "context" - "errors" "fmt" "net/http" "net/textproto" "strings" - "github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule" + "github.com/golang/protobuf/proto" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" - "google.golang.org/protobuf/proto" -) - -// UnescapingMode defines the behavior of ServeMux when unescaping path parameters. -type UnescapingMode int - -const ( - // UnescapingModeLegacy is the default V2 behavior, which escapes the entire - // path string before doing any routing. - UnescapingModeLegacy UnescapingMode = iota - - // EscapingTypeExceptReserved unescapes all path parameters except RFC 6570 - // reserved characters. - UnescapingModeAllExceptReserved - - // EscapingTypeExceptSlash unescapes URL path parameters except path - // seperators, which will be left as "%2F". - UnescapingModeAllExceptSlash - - // URL path parameters will be fully decoded. - UnescapingModeAllCharacters - - // UnescapingModeDefault is the default escaping type. - // TODO(v3): default this to UnescapingModeAllExceptReserved per grpc-httpjson-transcoding's - // reference implementation - UnescapingModeDefault = UnescapingModeLegacy ) // A HandlerFunc handles a specific pair of path pattern and HTTP method. type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) +// ErrUnknownURI is the error supplied to a custom ProtoErrorHandlerFunc when +// a request is received with a URI path that does not match any registered +// service method. +// +// Since gRPC servers return an "Unimplemented" code for requests with an +// unrecognized URI path, this error also has a gRPC "Unimplemented" code. +var ErrUnknownURI = status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented)) + // ServeMux is a request multiplexer for grpc-gateway. // It matches http requests to patterns and invokes the corresponding handler. type ServeMux struct { @@ -53,11 +34,10 @@ type ServeMux struct { incomingHeaderMatcher HeaderMatcherFunc outgoingHeaderMatcher HeaderMatcherFunc metadataAnnotators []func(context.Context, *http.Request) metadata.MD - errorHandler ErrorHandlerFunc streamErrorHandler StreamErrorHandlerFunc - routingErrorHandler RoutingErrorHandlerFunc + protoErrorHandler ProtoErrorHandlerFunc disablePathLengthFallback bool - unescapingMode UnescapingMode + lastMatchWins bool } // ServeMuxOption is an option that can be given to a ServeMux on construction. @@ -75,16 +55,8 @@ func WithForwardResponseOption(forwardResponseOption func(context.Context, http. } } -// WithEscapingType sets the escaping type. See the definitions of UnescapingMode -// for more information. -func WithUnescapingMode(mode UnescapingMode) ServeMuxOption { - return func(serveMux *ServeMux) { - serveMux.unescapingMode = mode - } -} - // SetQueryParameterParser sets the query parameter parser, used to populate message from query parameters. -// Configuring this will mean the generated OpenAPI output is no longer correct, and it should be +// Configuring this will mean the generated swagger output is no longer correct, and it should be // done with careful consideration. func SetQueryParameterParser(queryParameterParser QueryParameterParser) ServeMuxOption { return func(serveMux *ServeMux) { @@ -139,12 +111,21 @@ func WithMetadata(annotator func(context.Context, *http.Request) metadata.MD) Se } } -// WithErrorHandler returns a ServeMuxOption for configuring a custom error handler. +// WithProtoErrorHandler returns a ServeMuxOption for configuring a custom error handler. // -// This can be used to configure a custom error response. -func WithErrorHandler(fn ErrorHandlerFunc) ServeMuxOption { +// This can be used to handle an error as general proto message defined by gRPC. +// When this option is used, the mux uses the configured error handler instead of HTTPError and +// OtherErrorHandler. +func WithProtoErrorHandler(fn ProtoErrorHandlerFunc) ServeMuxOption { return func(serveMux *ServeMux) { - serveMux.errorHandler = fn + serveMux.protoErrorHandler = fn + } +} + +// WithDisablePathLengthFallback returns a ServeMuxOption for disable path length fallback. +func WithDisablePathLengthFallback() ServeMuxOption { + return func(serveMux *ServeMux) { + serveMux.disablePathLengthFallback = true } } @@ -153,7 +134,7 @@ func WithErrorHandler(fn ErrorHandlerFunc) ServeMuxOption { // calls. // // For stream errors that occur before any response has been written, the mux's -// ErrorHandler will be invoked. However, once data has been written, the errors must +// ProtoErrorHandler will be invoked. However, once data has been written, the errors must // be handled differently: they must be included in the response body. The response body's // final message will include the error details returned by the stream error handler. func WithStreamErrorHandler(fn StreamErrorHandlerFunc) ServeMuxOption { @@ -162,20 +143,12 @@ func WithStreamErrorHandler(fn StreamErrorHandlerFunc) ServeMuxOption { } } -// WithRoutingErrorHandler returns a ServeMuxOption for configuring a custom error handler to handle http routing errors. -// -// Method called for errors which can happen before gRPC route selected or executed. -// The following error codes: StatusMethodNotAllowed StatusNotFound StatusBadRequest -func WithRoutingErrorHandler(fn RoutingErrorHandlerFunc) ServeMuxOption { +// WithLastMatchWins returns a ServeMuxOption that will enable "last +// match wins" behavior, where if multiple path patterns match a +// request path, the last one defined in the .proto file will be used. +func WithLastMatchWins() ServeMuxOption { return func(serveMux *ServeMux) { - serveMux.routingErrorHandler = fn - } -} - -// WithDisablePathLengthFallback returns a ServeMuxOption for disable path length fallback. -func WithDisablePathLengthFallback() ServeMuxOption { - return func(serveMux *ServeMux) { - serveMux.disablePathLengthFallback = true + serveMux.lastMatchWins = true } } @@ -185,10 +158,7 @@ func NewServeMux(opts ...ServeMuxOption) *ServeMux { handlers: make(map[string][]handler), forwardResponseOptions: make([]func(context.Context, http.ResponseWriter, proto.Message) error, 0), marshalers: makeMarshalerMIMERegistry(), - errorHandler: DefaultHTTPErrorHandler, - streamErrorHandler: DefaultStreamErrorHandler, - routingErrorHandler: DefaultRoutingErrorHandler, - unescapingMode: UnescapingModeDefault, + streamErrorHandler: DefaultHTTPStreamErrorHandler, } for _, opt := range opts { @@ -210,23 +180,11 @@ func NewServeMux(opts ...ServeMuxOption) *ServeMux { // Handle associates "h" to the pair of HTTP method and path pattern. func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) { - s.handlers[meth] = append([]handler{{pat: pat, h: h}}, s.handlers[meth]...) -} - -// HandlePath allows users to configure custom path handlers. -// refer: https://grpc-ecosystem.github.io/grpc-gateway/docs/operations/inject_router/ -func (s *ServeMux) HandlePath(meth string, pathPattern string, h HandlerFunc) error { - compiler, err := httprule.Parse(pathPattern) - if err != nil { - return fmt.Errorf("parsing path pattern: %w", err) - } - tp := compiler.Compile() - pattern, err := NewPattern(tp.Version, tp.OpCodes, tp.Pool, tp.Verb) - if err != nil { - return fmt.Errorf("creating new pattern: %w", err) + if s.lastMatchWins { + s.handlers[meth] = append([]handler{handler{pat: pat, h: h}}, s.handlers[meth]...) + } else { + s.handlers[meth] = append(s.handlers[meth], handler{pat: pat, h: h}) } - s.Handle(meth, pattern, h) - return nil } // ServeHTTP dispatches the request to the first handler whose pattern matches to r.Method and r.Path. @@ -235,66 +193,48 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { path := r.URL.Path if !strings.HasPrefix(path, "/") { - _, outboundMarshaler := MarshalerForRequest(s, r) - s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusBadRequest) + if s.protoErrorHandler != nil { + _, outboundMarshaler := MarshalerForRequest(s, r) + sterr := status.Error(codes.InvalidArgument, http.StatusText(http.StatusBadRequest)) + s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) + } else { + OtherErrorHandler(w, r, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) + } return } - // TODO(v3): remove UnescapingModeLegacy - if s.unescapingMode != UnescapingModeLegacy && r.URL.RawPath != "" { - path = r.URL.RawPath - } - components := strings.Split(path[1:], "/") + l := len(components) + var verb string + if idx := strings.LastIndex(components[l-1], ":"); idx == 0 { + if s.protoErrorHandler != nil { + _, outboundMarshaler := MarshalerForRequest(s, r) + s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, ErrUnknownURI) + } else { + OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound) + } + return + } else if idx > 0 { + c := components[l-1] + components[l-1], verb = c[:idx], c[idx+1:] + } if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && s.isPathLengthFallback(r) { r.Method = strings.ToUpper(override) if err := r.ParseForm(); err != nil { - _, outboundMarshaler := MarshalerForRequest(s, r) - sterr := status.Error(codes.InvalidArgument, err.Error()) - s.errorHandler(ctx, s, outboundMarshaler, w, r, sterr) + if s.protoErrorHandler != nil { + _, outboundMarshaler := MarshalerForRequest(s, r) + sterr := status.Error(codes.InvalidArgument, err.Error()) + s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) + } else { + OtherErrorHandler(w, r, err.Error(), http.StatusBadRequest) + } return } } - - // Verb out here is to memoize for the fallback case below - var verb string - for _, h := range s.handlers[r.Method] { - // If the pattern has a verb, explicitly look for a suffix in the last - // component that matches a colon plus the verb. This allows us to - // handle some cases that otherwise can't be correctly handled by the - // former LastIndex case, such as when the verb literal itself contains - // a colon. This should work for all cases that have run through the - // parser because we know what verb we're looking for, however, there - // are still some cases that the parser itself cannot disambiguate. See - // the comment there if interested. - patVerb := h.pat.Verb() - l := len(components) - lastComponent := components[l-1] - var idx int = -1 - if patVerb != "" && strings.HasSuffix(lastComponent, ":"+patVerb) { - idx = len(lastComponent) - len(patVerb) - 1 - } - if idx == 0 { - _, outboundMarshaler := MarshalerForRequest(s, r) - s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusNotFound) - return - } - if idx > 0 { - components[l-1], verb = lastComponent[:idx], lastComponent[idx+1:] - } - - pathParams, err := h.pat.MatchAndEscape(components, verb, s.unescapingMode) + pathParams, err := h.pat.Match(components, verb) if err != nil { - var mse MalformedSequenceError - if ok := errors.As(err, &mse); ok { - _, outboundMarshaler := MarshalerForRequest(s, r) - s.errorHandler(ctx, s, outboundMarshaler, w, r, &HTTPStatusError{ - HTTPStatus: http.StatusBadRequest, - Err: mse, - }) - } continue } h.h(w, r, pathParams) @@ -302,43 +242,47 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { } // lookup other methods to handle fallback from GET to POST and - // to determine if it is NotImplemented or NotFound. + // to determine if it is MethodNotAllowed or NotFound. for m, handlers := range s.handlers { if m == r.Method { continue } for _, h := range handlers { - pathParams, err := h.pat.MatchAndEscape(components, verb, s.unescapingMode) + pathParams, err := h.pat.Match(components, verb) if err != nil { - var mse MalformedSequenceError - if ok := errors.As(err, &mse); ok { - _, outboundMarshaler := MarshalerForRequest(s, r) - s.errorHandler(ctx, s, outboundMarshaler, w, r, &HTTPStatusError{ - HTTPStatus: http.StatusBadRequest, - Err: mse, - }) - } continue } // X-HTTP-Method-Override is optional. Always allow fallback to POST. if s.isPathLengthFallback(r) { if err := r.ParseForm(); err != nil { - _, outboundMarshaler := MarshalerForRequest(s, r) - sterr := status.Error(codes.InvalidArgument, err.Error()) - s.errorHandler(ctx, s, outboundMarshaler, w, r, sterr) + if s.protoErrorHandler != nil { + _, outboundMarshaler := MarshalerForRequest(s, r) + sterr := status.Error(codes.InvalidArgument, err.Error()) + s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) + } else { + OtherErrorHandler(w, r, err.Error(), http.StatusBadRequest) + } return } h.h(w, r, pathParams) return } - _, outboundMarshaler := MarshalerForRequest(s, r) - s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusMethodNotAllowed) + if s.protoErrorHandler != nil { + _, outboundMarshaler := MarshalerForRequest(s, r) + s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, ErrUnknownURI) + } else { + OtherErrorHandler(w, r, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) + } return } } - _, outboundMarshaler := MarshalerForRequest(s, r) - s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusNotFound) + if s.protoErrorHandler != nil { + _, outboundMarshaler := MarshalerForRequest(s, r) + s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, ErrUnknownURI) + } else { + OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound) + } } // GetForwardResponseOptions returns the ForwardResponseOptions associated with this ServeMux. diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern.go similarity index 57% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern.go index df7cb81426a0b..09053695da7eb 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/pattern.go @@ -3,10 +3,9 @@ package runtime import ( "errors" "fmt" - "strconv" "strings" - "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" + "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc/grpclog" ) @@ -15,23 +14,14 @@ var ( ErrNotMatch = errors.New("not match to the path pattern") // ErrInvalidPattern indicates that the given definition of Pattern is not valid. ErrInvalidPattern = errors.New("invalid pattern") - // ErrMalformedSequence indicates that an escape sequence was malformed. - ErrMalformedSequence = errors.New("malformed escape sequence") ) -type MalformedSequenceError string - -func (e MalformedSequenceError) Error() string { - return "malformed path escape " + strconv.Quote(string(e)) -} - type op struct { code utilities.OpCode operand int } -// Pattern is a template pattern of http request paths defined in -// https://github.com/googleapis/googleapis/blob/master/google/api/http.proto +// Pattern is a template pattern of http request paths defined in github.com/googleapis/googleapis/google/api/http.proto. type Pattern struct { // ops is a list of operations ops []op @@ -45,14 +35,31 @@ type Pattern struct { tailLen int // verb is the VERB part of the path pattern. It is empty if the pattern does not have VERB part. verb string + // assumeColonVerb indicates whether a path suffix after a final + // colon may only be interpreted as a verb. + assumeColonVerb bool } +type patternOptions struct { + assumeColonVerb bool +} + +// PatternOpt is an option for creating Patterns. +type PatternOpt func(*patternOptions) + // NewPattern returns a new Pattern from the given definition values. // "ops" is a sequence of op codes. "pool" is a constant pool. // "verb" is the verb part of the pattern. It is empty if the pattern does not have the part. // "version" must be 1 for now. // It returns an error if the given definition is invalid. -func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, error) { +func NewPattern(version int, ops []int, pool []string, verb string, opts ...PatternOpt) (Pattern, error) { + options := patternOptions{ + assumeColonVerb: true, + } + for _, o := range opts { + o(&options) + } + if version != 1 { grpclog.Infof("unsupported version: %d", version) return Pattern{}, ErrInvalidPattern @@ -104,7 +111,7 @@ func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, er } stack -= op.operand if stack < 0 { - grpclog.Info("stack underflow") + grpclog.Print("stack underflow") return Pattern{}, ErrInvalidPattern } stack++ @@ -132,12 +139,13 @@ func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, er typedOps = append(typedOps, op) } return Pattern{ - ops: typedOps, - pool: pool, - vars: vars, - stacksize: maxstack, - tailLen: tailLen, - verb: verb, + ops: typedOps, + pool: pool, + vars: vars, + stacksize: maxstack, + tailLen: tailLen, + verb: verb, + assumeColonVerb: options.assumeColonVerb, }, nil } @@ -149,13 +157,12 @@ func MustPattern(p Pattern, err error) Pattern { return p } -// MatchAndEscape examines components to determine if they match to a Pattern. -// MatchAndEscape will return an error if no Patterns matched or if a pattern -// matched but contained malformed escape sequences. If successful, the function -// returns a mapping from field paths to their captured values. -func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode UnescapingMode) (map[string]string, error) { +// Match examines components if it matches to the Pattern. +// If it matches, the function returns a mapping from field paths to their captured values. +// If otherwise, the function returns an error. +func (p Pattern) Match(components []string, verb string) (map[string]string, error) { if p.verb != verb { - if p.verb != "" { + if p.assumeColonVerb || p.verb != "" { return nil, ErrNotMatch } if len(components) == 0 { @@ -164,6 +171,7 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode components = append([]string{}, components...) components[len(components)-1] += ":" + verb } + verb = "" } var pos int @@ -171,8 +179,6 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode captured := make([]string, len(p.vars)) l := len(components) for _, op := range p.ops { - var err error - switch op.code { case utilities.OpNop: continue @@ -185,10 +191,6 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode if lit := p.pool[op.operand]; c != lit { return nil, ErrNotMatch } - } else if op.code == utilities.OpPush { - if c, err = unescape(c, unescapingMode, false); err != nil { - return nil, err - } } stack = append(stack, c) pos++ @@ -198,11 +200,7 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode return nil, ErrNotMatch } end -= p.tailLen - c := strings.Join(components[pos:end], "/") - if c, err = unescape(c, unescapingMode, true); err != nil { - return nil, err - } - stack = append(stack, c) + stack = append(stack, strings.Join(components[pos:end], "/")) pos = end case utilities.OpConcatN: n := op.operand @@ -224,16 +222,6 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode return bindings, nil } -// MatchAndEscape examines components to determine if they match to a Pattern. -// It will never perform per-component unescaping (see: UnescapingModeLegacy). -// MatchAndEscape will return an error if no Patterns matched. If successful, -// the function returns a mapping from field paths to their captured values. -// -// Deprecated: Use MatchAndEscape. -func (p Pattern) Match(components []string, verb string) (map[string]string, error) { - return p.MatchAndEscape(components, verb, UnescapingModeDefault) -} - // Verb returns the verb part of the Pattern. func (p Pattern) Verb() string { return p.verb } @@ -265,119 +253,10 @@ func (p Pattern) String() string { return "/" + segs } -/* - * The following code is adopted and modified from Go's standard library - * and carries the attached license. - * - * Copyright 2009 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. - */ - -// ishex returns whether or not the given byte is a valid hex character -func ishex(c byte) bool { - switch { - case '0' <= c && c <= '9': - return true - case 'a' <= c && c <= 'f': - return true - case 'A' <= c && c <= 'F': - return true - } - return false -} - -func isRFC6570Reserved(c byte) bool { - switch c { - case '!', '#', '$', '&', '\'', '(', ')', '*', - '+', ',', '/', ':', ';', '=', '?', '@', '[', ']': - return true - default: - return false - } -} - -// unhex converts a hex point to the bit representation -func unhex(c byte) byte { - switch { - case '0' <= c && c <= '9': - return c - '0' - case 'a' <= c && c <= 'f': - return c - 'a' + 10 - case 'A' <= c && c <= 'F': - return c - 'A' + 10 - } - return 0 -} - -// shouldUnescapeWithMode returns true if the character is escapable with the -// given mode -func shouldUnescapeWithMode(c byte, mode UnescapingMode) bool { - switch mode { - case UnescapingModeAllExceptReserved: - if isRFC6570Reserved(c) { - return false - } - case UnescapingModeAllExceptSlash: - if c == '/' { - return false - } - case UnescapingModeAllCharacters: - return true - } - return true -} - -// unescape unescapes a path string using the provided mode -func unescape(s string, mode UnescapingMode, multisegment bool) (string, error) { - // TODO(v3): remove UnescapingModeLegacy - if mode == UnescapingModeLegacy { - return s, nil - } - - if !multisegment { - mode = UnescapingModeAllCharacters - } - - // Count %, check that they're well-formed. - n := 0 - for i := 0; i < len(s); { - if s[i] == '%' { - n++ - if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) { - s = s[i:] - if len(s) > 3 { - s = s[:3] - } - - return "", MalformedSequenceError(s) - } - i += 3 - } else { - i++ - } - } - - if n == 0 { - return s, nil - } - - var t strings.Builder - t.Grow(len(s)) - for i := 0; i < len(s); i++ { - switch s[i] { - case '%': - c := unhex(s[i+1])<<4 | unhex(s[i+2]) - if shouldUnescapeWithMode(c, mode) { - t.WriteByte(c) - i += 2 - continue - } - fallthrough - default: - t.WriteByte(s[i]) - } - } - - return t.String(), nil +// AssumeColonVerbOpt indicates whether a path suffix after a final +// colon may only be interpreted as a verb. +func AssumeColonVerbOpt(val bool) PatternOpt { + return PatternOpt(func(o *patternOptions) { + o.assumeColonVerb = val + }) } diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/proto2_convert.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/proto2_convert.go similarity index 98% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/proto2_convert.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/proto2_convert.go index d549407f20fbf..a3151e2a5528d 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/proto2_convert.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/proto2_convert.go @@ -1,7 +1,7 @@ package runtime import ( - "google.golang.org/protobuf/proto" + "github.com/golang/protobuf/proto" ) // StringP returns a pointer to a string whose pointee is same as the given string value. diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/proto_errors.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/proto_errors.go new file mode 100644 index 0000000000000..3fd30da22a70d --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/proto_errors.go @@ -0,0 +1,106 @@ +package runtime + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/ptypes/any" + "github.com/grpc-ecosystem/grpc-gateway/internal" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/status" +) + +// StreamErrorHandlerFunc accepts an error as a gRPC error generated via status package and translates it into a +// a proto struct used to represent error at the end of a stream. +type StreamErrorHandlerFunc func(context.Context, error) *StreamError + +// StreamError is the payload for the final message in a server stream in the event that the server returns an +// error after a response message has already been sent. +type StreamError internal.StreamError + +// ProtoErrorHandlerFunc handles the error as a gRPC error generated via status package and replies to the request. +type ProtoErrorHandlerFunc func(context.Context, *ServeMux, Marshaler, http.ResponseWriter, *http.Request, error) + +var _ ProtoErrorHandlerFunc = DefaultHTTPProtoErrorHandler + +// DefaultHTTPProtoErrorHandler is an implementation of HTTPError. +// If "err" is an error from gRPC system, the function replies with the status code mapped by HTTPStatusFromCode. +// If otherwise, it replies with http.StatusInternalServerError. +// +// The response body returned by this function is a Status message marshaled by a Marshaler. +// +// Do not set this function to HTTPError variable directly, use WithProtoErrorHandler option instead. +func DefaultHTTPProtoErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, _ *http.Request, err error) { + // return Internal when Marshal failed + const fallback = `{"code": 13, "message": "failed to marshal error message"}` + + s, ok := status.FromError(err) + if !ok { + s = status.New(codes.Unknown, err.Error()) + } + + w.Header().Del("Trailer") + + contentType := marshaler.ContentType() + // Check marshaler on run time in order to keep backwards compatibility + // An interface param needs to be added to the ContentType() function on + // the Marshal interface to be able to remove this check + if typeMarshaler, ok := marshaler.(contentTypeMarshaler); ok { + pb := s.Proto() + contentType = typeMarshaler.ContentTypeFromMessage(pb) + } + w.Header().Set("Content-Type", contentType) + + buf, merr := marshaler.Marshal(s.Proto()) + if merr != nil { + grpclog.Infof("Failed to marshal error message %q: %v", s.Proto(), merr) + w.WriteHeader(http.StatusInternalServerError) + if _, err := io.WriteString(w, fallback); err != nil { + grpclog.Infof("Failed to write response: %v", err) + } + return + } + + md, ok := ServerMetadataFromContext(ctx) + if !ok { + grpclog.Infof("Failed to extract ServerMetadata from context") + } + + handleForwardResponseServerMetadata(w, mux, md) + handleForwardResponseTrailerHeader(w, md) + st := HTTPStatusFromCode(s.Code()) + w.WriteHeader(st) + if _, err := w.Write(buf); err != nil { + grpclog.Infof("Failed to write response: %v", err) + } + + handleForwardResponseTrailer(w, md) +} + +// DefaultHTTPStreamErrorHandler converts the given err into a *StreamError via +// default logic. +// +// It extracts the gRPC status from err if possible. The fields of the status are +// used to populate the returned StreamError, and the HTTP status code is derived +// from the gRPC code via HTTPStatusFromCode. If the given err does not contain a +// gRPC status, an "Unknown" gRPC code is used and "Internal Server Error" HTTP code. +func DefaultHTTPStreamErrorHandler(_ context.Context, err error) *StreamError { + grpcCode := codes.Unknown + grpcMessage := err.Error() + var grpcDetails []*any.Any + if s, ok := status.FromError(err); ok { + grpcCode = s.Code() + grpcMessage = s.Message() + grpcDetails = s.Proto().GetDetails() + } + httpCode := HTTPStatusFromCode(grpcCode) + return &StreamError{ + GrpcCode: int32(grpcCode), + HttpCode: int32(httpCode), + Message: grpcMessage, + HttpStatus: http.StatusText(httpCode), + Details: grpcDetails, + } +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/query.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/query.go new file mode 100644 index 0000000000000..ba66842c33090 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/runtime/query.go @@ -0,0 +1,406 @@ +package runtime + +import ( + "encoding/base64" + "fmt" + "net/url" + "reflect" + "regexp" + "strconv" + "strings" + "time" + + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc/grpclog" +) + +var valuesKeyRegexp = regexp.MustCompile("^(.*)\\[(.*)\\]$") + +var currentQueryParser QueryParameterParser = &defaultQueryParser{} + +// QueryParameterParser defines interface for all query parameter parsers +type QueryParameterParser interface { + Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error +} + +// PopulateQueryParameters parses query parameters +// into "msg" using current query parser +func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error { + return currentQueryParser.Parse(msg, values, filter) +} + +type defaultQueryParser struct{} + +// Parse populates "values" into "msg". +// A value is ignored if its key starts with one of the elements in "filter". +func (*defaultQueryParser) Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error { + for key, values := range values { + match := valuesKeyRegexp.FindStringSubmatch(key) + if len(match) == 3 { + key = match[1] + values = append([]string{match[2]}, values...) + } + fieldPath := strings.Split(key, ".") + if filter.HasCommonPrefix(fieldPath) { + continue + } + if err := populateFieldValueFromPath(msg, fieldPath, values); err != nil { + return err + } + } + return nil +} + +// PopulateFieldFromPath sets a value in a nested Protobuf structure. +// It instantiates missing protobuf fields as it goes. +func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error { + fieldPath := strings.Split(fieldPathString, ".") + return populateFieldValueFromPath(msg, fieldPath, []string{value}) +} + +func populateFieldValueFromPath(msg proto.Message, fieldPath []string, values []string) error { + m := reflect.ValueOf(msg) + if m.Kind() != reflect.Ptr { + return fmt.Errorf("unexpected type %T: %v", msg, msg) + } + var props *proto.Properties + m = m.Elem() + for i, fieldName := range fieldPath { + isLast := i == len(fieldPath)-1 + if !isLast && m.Kind() != reflect.Struct { + return fmt.Errorf("non-aggregate type in the mid of path: %s", strings.Join(fieldPath, ".")) + } + var f reflect.Value + var err error + f, props, err = fieldByProtoName(m, fieldName) + if err != nil { + return err + } else if !f.IsValid() { + grpclog.Infof("field not found in %T: %s", msg, strings.Join(fieldPath, ".")) + return nil + } + + switch f.Kind() { + case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64: + if !isLast { + return fmt.Errorf("unexpected nested field %s in %s", fieldPath[i+1], strings.Join(fieldPath[:i+1], ".")) + } + m = f + case reflect.Slice: + if !isLast { + return fmt.Errorf("unexpected repeated field in %s", strings.Join(fieldPath, ".")) + } + // Handle []byte + if f.Type().Elem().Kind() == reflect.Uint8 { + m = f + break + } + return populateRepeatedField(f, values, props) + case reflect.Ptr: + if f.IsNil() { + m = reflect.New(f.Type().Elem()) + f.Set(m.Convert(f.Type())) + } + m = f.Elem() + continue + case reflect.Struct: + m = f + continue + case reflect.Map: + if !isLast { + return fmt.Errorf("unexpected nested field %s in %s", fieldPath[i+1], strings.Join(fieldPath[:i+1], ".")) + } + return populateMapField(f, values, props) + default: + return fmt.Errorf("unexpected type %s in %T", f.Type(), msg) + } + } + switch len(values) { + case 0: + return fmt.Errorf("no value of field: %s", strings.Join(fieldPath, ".")) + case 1: + default: + grpclog.Infof("too many field values: %s", strings.Join(fieldPath, ".")) + } + return populateField(m, values[0], props) +} + +// fieldByProtoName looks up a field whose corresponding protobuf field name is "name". +// "m" must be a struct value. It returns zero reflect.Value if no such field found. +func fieldByProtoName(m reflect.Value, name string) (reflect.Value, *proto.Properties, error) { + props := proto.GetProperties(m.Type()) + + // look up field name in oneof map + for _, op := range props.OneofTypes { + if name == op.Prop.OrigName || name == op.Prop.JSONName { + v := reflect.New(op.Type.Elem()) + field := m.Field(op.Field) + if !field.IsNil() { + return reflect.Value{}, nil, fmt.Errorf("field already set for %s oneof", props.Prop[op.Field].OrigName) + } + field.Set(v) + return v.Elem().Field(0), op.Prop, nil + } + } + + for _, p := range props.Prop { + if p.OrigName == name { + return m.FieldByName(p.Name), p, nil + } + if p.JSONName == name { + return m.FieldByName(p.Name), p, nil + } + } + return reflect.Value{}, nil, nil +} + +func populateMapField(f reflect.Value, values []string, props *proto.Properties) error { + if len(values) != 2 { + return fmt.Errorf("more than one value provided for key %s in map %s", values[0], props.Name) + } + + key, value := values[0], values[1] + keyType := f.Type().Key() + valueType := f.Type().Elem() + if f.IsNil() { + f.Set(reflect.MakeMap(f.Type())) + } + + keyConv, ok := convFromType[keyType.Kind()] + if !ok { + return fmt.Errorf("unsupported key type %s in map %s", keyType, props.Name) + } + valueConv, ok := convFromType[valueType.Kind()] + if !ok { + return fmt.Errorf("unsupported value type %s in map %s", valueType, props.Name) + } + + keyV := keyConv.Call([]reflect.Value{reflect.ValueOf(key)}) + if err := keyV[1].Interface(); err != nil { + return err.(error) + } + valueV := valueConv.Call([]reflect.Value{reflect.ValueOf(value)}) + if err := valueV[1].Interface(); err != nil { + return err.(error) + } + + f.SetMapIndex(keyV[0].Convert(keyType), valueV[0].Convert(valueType)) + + return nil +} + +func populateRepeatedField(f reflect.Value, values []string, props *proto.Properties) error { + elemType := f.Type().Elem() + + // is the destination field a slice of an enumeration type? + if enumValMap := proto.EnumValueMap(props.Enum); enumValMap != nil { + return populateFieldEnumRepeated(f, values, enumValMap) + } + + conv, ok := convFromType[elemType.Kind()] + if !ok { + return fmt.Errorf("unsupported field type %s", elemType) + } + f.Set(reflect.MakeSlice(f.Type(), len(values), len(values)).Convert(f.Type())) + for i, v := range values { + result := conv.Call([]reflect.Value{reflect.ValueOf(v)}) + if err := result[1].Interface(); err != nil { + return err.(error) + } + f.Index(i).Set(result[0].Convert(f.Index(i).Type())) + } + return nil +} + +func populateField(f reflect.Value, value string, props *proto.Properties) error { + i := f.Addr().Interface() + + // Handle protobuf well known types + var name string + switch m := i.(type) { + case interface{ XXX_WellKnownType() string }: + name = m.XXX_WellKnownType() + case proto.Message: + const wktPrefix = "google.protobuf." + if fullName := proto.MessageName(m); strings.HasPrefix(fullName, wktPrefix) { + name = fullName[len(wktPrefix):] + } + } + switch name { + case "Timestamp": + if value == "null" { + f.FieldByName("Seconds").SetInt(0) + f.FieldByName("Nanos").SetInt(0) + return nil + } + + t, err := time.Parse(time.RFC3339Nano, value) + if err != nil { + return fmt.Errorf("bad Timestamp: %v", err) + } + f.FieldByName("Seconds").SetInt(int64(t.Unix())) + f.FieldByName("Nanos").SetInt(int64(t.Nanosecond())) + return nil + case "Duration": + if value == "null" { + f.FieldByName("Seconds").SetInt(0) + f.FieldByName("Nanos").SetInt(0) + return nil + } + d, err := time.ParseDuration(value) + if err != nil { + return fmt.Errorf("bad Duration: %v", err) + } + + ns := d.Nanoseconds() + s := ns / 1e9 + ns %= 1e9 + f.FieldByName("Seconds").SetInt(s) + f.FieldByName("Nanos").SetInt(ns) + return nil + case "DoubleValue": + fallthrough + case "FloatValue": + float64Val, err := strconv.ParseFloat(value, 64) + if err != nil { + return fmt.Errorf("bad DoubleValue: %s", value) + } + f.FieldByName("Value").SetFloat(float64Val) + return nil + case "Int64Value": + fallthrough + case "Int32Value": + int64Val, err := strconv.ParseInt(value, 10, 64) + if err != nil { + return fmt.Errorf("bad DoubleValue: %s", value) + } + f.FieldByName("Value").SetInt(int64Val) + return nil + case "UInt64Value": + fallthrough + case "UInt32Value": + uint64Val, err := strconv.ParseUint(value, 10, 64) + if err != nil { + return fmt.Errorf("bad DoubleValue: %s", value) + } + f.FieldByName("Value").SetUint(uint64Val) + return nil + case "BoolValue": + if value == "true" { + f.FieldByName("Value").SetBool(true) + } else if value == "false" { + f.FieldByName("Value").SetBool(false) + } else { + return fmt.Errorf("bad BoolValue: %s", value) + } + return nil + case "StringValue": + f.FieldByName("Value").SetString(value) + return nil + case "BytesValue": + bytesVal, err := base64.StdEncoding.DecodeString(value) + if err != nil { + return fmt.Errorf("bad BytesValue: %s", value) + } + f.FieldByName("Value").SetBytes(bytesVal) + return nil + case "FieldMask": + p := f.FieldByName("Paths") + for _, v := range strings.Split(value, ",") { + if v != "" { + p.Set(reflect.Append(p, reflect.ValueOf(v))) + } + } + return nil + } + + // Handle Time and Duration stdlib types + switch t := i.(type) { + case *time.Time: + pt, err := time.Parse(time.RFC3339Nano, value) + if err != nil { + return fmt.Errorf("bad Timestamp: %v", err) + } + *t = pt + return nil + case *time.Duration: + d, err := time.ParseDuration(value) + if err != nil { + return fmt.Errorf("bad Duration: %v", err) + } + *t = d + return nil + } + + // is the destination field an enumeration type? + if enumValMap := proto.EnumValueMap(props.Enum); enumValMap != nil { + return populateFieldEnum(f, value, enumValMap) + } + + conv, ok := convFromType[f.Kind()] + if !ok { + return fmt.Errorf("field type %T is not supported in query parameters", i) + } + result := conv.Call([]reflect.Value{reflect.ValueOf(value)}) + if err := result[1].Interface(); err != nil { + return err.(error) + } + f.Set(result[0].Convert(f.Type())) + return nil +} + +func convertEnum(value string, t reflect.Type, enumValMap map[string]int32) (reflect.Value, error) { + // see if it's an enumeration string + if enumVal, ok := enumValMap[value]; ok { + return reflect.ValueOf(enumVal).Convert(t), nil + } + + // check for an integer that matches an enumeration value + eVal, err := strconv.Atoi(value) + if err != nil { + return reflect.Value{}, fmt.Errorf("%s is not a valid %s", value, t) + } + for _, v := range enumValMap { + if v == int32(eVal) { + return reflect.ValueOf(eVal).Convert(t), nil + } + } + return reflect.Value{}, fmt.Errorf("%s is not a valid %s", value, t) +} + +func populateFieldEnum(f reflect.Value, value string, enumValMap map[string]int32) error { + cval, err := convertEnum(value, f.Type(), enumValMap) + if err != nil { + return err + } + f.Set(cval) + return nil +} + +func populateFieldEnumRepeated(f reflect.Value, values []string, enumValMap map[string]int32) error { + elemType := f.Type().Elem() + f.Set(reflect.MakeSlice(f.Type(), len(values), len(values)).Convert(f.Type())) + for i, v := range values { + result, err := convertEnum(v, elemType, enumValMap) + if err != nil { + return err + } + f.Index(i).Set(result) + } + return nil +} + +var ( + convFromType = map[reflect.Kind]reflect.Value{ + reflect.String: reflect.ValueOf(String), + reflect.Bool: reflect.ValueOf(Bool), + reflect.Float64: reflect.ValueOf(Float64), + reflect.Float32: reflect.ValueOf(Float32), + reflect.Int64: reflect.ValueOf(Int64), + reflect.Int32: reflect.ValueOf(Int32), + reflect.Uint64: reflect.ValueOf(Uint64), + reflect.Uint32: reflect.ValueOf(Uint32), + reflect.Slice: reflect.ValueOf(Bytes), + } +) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/BUILD.bazel similarity index 59% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/BUILD.bazel rename to vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/BUILD.bazel index 5d8d12bc42117..7109d79323187 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/BUILD.bazel +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/BUILD.bazel @@ -3,25 +3,19 @@ load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") package(default_visibility = ["//visibility:public"]) go_library( - name = "utilities", + name = "go_default_library", srcs = [ "doc.go", "pattern.go", "readerfactory.go", "trie.go", ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/v2/utilities", + importpath = "github.com/grpc-ecosystem/grpc-gateway/utilities", ) go_test( - name = "utilities_test", + name = "go_default_test", size = "small", srcs = ["trie_test.go"], - deps = [":utilities"], -) - -alias( - name = "go_default_library", - actual = ":utilities", - visibility = ["//visibility:public"], + embed = [":go_default_library"], ) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/doc.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/doc.go similarity index 100% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/doc.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/doc.go diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/pattern.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/pattern.go similarity index 100% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/pattern.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/pattern.go diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/readerfactory.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/readerfactory.go similarity index 100% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/readerfactory.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/readerfactory.go diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/trie.go similarity index 98% rename from vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go rename to vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/trie.go index af3b703d50571..c2b7b30dd9177 100644 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/utilities/trie.go @@ -145,7 +145,10 @@ func (l byLex) Less(i, j int) bool { return false } } - return k < len(sj) + if k < len(sj) { + return true + } + return false } // HasCommonPrefix determines if any sequence in the DoubleArray is a prefix of the given sequence. diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/BUILD.bazel deleted file mode 100644 index f694f3c0d035a..0000000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/BUILD.bazel +++ /dev/null @@ -1,35 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -package(default_visibility = ["//visibility:public"]) - -go_library( - name = "httprule", - srcs = [ - "compile.go", - "parse.go", - "types.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule", - deps = ["//utilities"], -) - -go_test( - name = "httprule_test", - size = "small", - srcs = [ - "compile_test.go", - "parse_test.go", - "types_test.go", - ], - embed = [":httprule"], - deps = [ - "//utilities", - "@com_github_golang_glog//:glog", - ], -) - -alias( - name = "go_default_library", - actual = ":httprule", - visibility = ["//:__subpackages__"], -) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/compile.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/compile.go deleted file mode 100644 index 3cd9372959d36..0000000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/compile.go +++ /dev/null @@ -1,121 +0,0 @@ -package httprule - -import ( - "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" -) - -const ( - opcodeVersion = 1 -) - -// Template is a compiled representation of path templates. -type Template struct { - // Version is the version number of the format. - Version int - // OpCodes is a sequence of operations. - OpCodes []int - // Pool is a constant pool - Pool []string - // Verb is a VERB part in the template. - Verb string - // Fields is a list of field paths bound in this template. - Fields []string - // Original template (example: /v1/a_bit_of_everything) - Template string -} - -// Compiler compiles utilities representation of path templates into marshallable operations. -// They can be unmarshalled by runtime.NewPattern. -type Compiler interface { - Compile() Template -} - -type op struct { - // code is the opcode of the operation - code utilities.OpCode - - // str is a string operand of the code. - // num is ignored if str is not empty. - str string - - // num is a numeric operand of the code. - num int -} - -func (w wildcard) compile() []op { - return []op{ - {code: utilities.OpPush}, - } -} - -func (w deepWildcard) compile() []op { - return []op{ - {code: utilities.OpPushM}, - } -} - -func (l literal) compile() []op { - return []op{ - { - code: utilities.OpLitPush, - str: string(l), - }, - } -} - -func (v variable) compile() []op { - var ops []op - for _, s := range v.segments { - ops = append(ops, s.compile()...) - } - ops = append(ops, op{ - code: utilities.OpConcatN, - num: len(v.segments), - }, op{ - code: utilities.OpCapture, - str: v.path, - }) - - return ops -} - -func (t template) Compile() Template { - var rawOps []op - for _, s := range t.segments { - rawOps = append(rawOps, s.compile()...) - } - - var ( - ops []int - pool []string - fields []string - ) - consts := make(map[string]int) - for _, op := range rawOps { - ops = append(ops, int(op.code)) - if op.str == "" { - ops = append(ops, op.num) - } else { - // eof segment literal represents the "/" path pattern - if op.str == eof { - op.str = "" - } - if _, ok := consts[op.str]; !ok { - consts[op.str] = len(pool) - pool = append(pool, op.str) - } - ops = append(ops, consts[op.str]) - } - if op.code == utilities.OpCapture { - fields = append(fields, op.str) - } - } - return Template{ - Version: opcodeVersion, - OpCodes: ops, - Pool: pool, - Verb: t.verb, - Fields: fields, - Template: t.template, - } -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/fuzz.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/fuzz.go deleted file mode 100644 index 138f7c12f0e36..0000000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/fuzz.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build gofuzz - -package httprule - -func Fuzz(data []byte) int { - _, err := Parse(string(data)) - if err != nil { - return 0 - } - return 0 -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go deleted file mode 100644 index 5edd784e62ade..0000000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go +++ /dev/null @@ -1,368 +0,0 @@ -package httprule - -import ( - "fmt" - "strings" -) - -// InvalidTemplateError indicates that the path template is not valid. -type InvalidTemplateError struct { - tmpl string - msg string -} - -func (e InvalidTemplateError) Error() string { - return fmt.Sprintf("%s: %s", e.msg, e.tmpl) -} - -// Parse parses the string representation of path template -func Parse(tmpl string) (Compiler, error) { - if !strings.HasPrefix(tmpl, "/") { - return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"} - } - tokens, verb := tokenize(tmpl[1:]) - - p := parser{tokens: tokens} - segs, err := p.topLevelSegments() - if err != nil { - return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()} - } - - return template{ - segments: segs, - verb: verb, - template: tmpl, - }, nil -} - -func tokenize(path string) (tokens []string, verb string) { - if path == "" { - return []string{eof}, "" - } - - const ( - init = iota - field - nested - ) - st := init - for path != "" { - var idx int - switch st { - case init: - idx = strings.IndexAny(path, "/{") - case field: - idx = strings.IndexAny(path, ".=}") - case nested: - idx = strings.IndexAny(path, "/}") - } - if idx < 0 { - tokens = append(tokens, path) - break - } - switch r := path[idx]; r { - case '/', '.': - case '{': - st = field - case '=': - st = nested - case '}': - st = init - } - if idx == 0 { - tokens = append(tokens, path[idx:idx+1]) - } else { - tokens = append(tokens, path[:idx], path[idx:idx+1]) - } - path = path[idx+1:] - } - - l := len(tokens) - // See - // https://github.com/grpc-ecosystem/grpc-gateway/pull/1947#issuecomment-774523693 ; - // although normal and backwards-compat logic here is to use the last index - // of a colon, if the final segment is a variable followed by a colon, the - // part following the colon must be a verb. Hence if the previous token is - // an end var marker, we switch the index we're looking for to Index instead - // of LastIndex, so that we correctly grab the remaining part of the path as - // the verb. - var penultimateTokenIsEndVar bool - switch l { - case 0, 1: - // Not enough to be variable so skip this logic and don't result in an - // invalid index - default: - penultimateTokenIsEndVar = tokens[l-2] == "}" - } - t := tokens[l-1] - var idx int - if penultimateTokenIsEndVar { - idx = strings.Index(t, ":") - } else { - idx = strings.LastIndex(t, ":") - } - if idx == 0 { - tokens, verb = tokens[:l-1], t[1:] - } else if idx > 0 { - tokens[l-1], verb = t[:idx], t[idx+1:] - } - tokens = append(tokens, eof) - return tokens, verb -} - -// parser is a parser of the template syntax defined in github.com/googleapis/googleapis/google/api/http.proto. -type parser struct { - tokens []string - accepted []string -} - -// topLevelSegments is the target of this parser. -func (p *parser) topLevelSegments() ([]segment, error) { - if _, err := p.accept(typeEOF); err == nil { - p.tokens = p.tokens[:0] - return []segment{literal(eof)}, nil - } - segs, err := p.segments() - if err != nil { - return nil, err - } - if _, err := p.accept(typeEOF); err != nil { - return nil, fmt.Errorf("unexpected token %q after segments %q", p.tokens[0], strings.Join(p.accepted, "")) - } - return segs, nil -} - -func (p *parser) segments() ([]segment, error) { - s, err := p.segment() - if err != nil { - return nil, err - } - - segs := []segment{s} - for { - if _, err := p.accept("/"); err != nil { - return segs, nil - } - s, err := p.segment() - if err != nil { - return segs, err - } - segs = append(segs, s) - } -} - -func (p *parser) segment() (segment, error) { - if _, err := p.accept("*"); err == nil { - return wildcard{}, nil - } - if _, err := p.accept("**"); err == nil { - return deepWildcard{}, nil - } - if l, err := p.literal(); err == nil { - return l, nil - } - - v, err := p.variable() - if err != nil { - return nil, fmt.Errorf("segment neither wildcards, literal or variable: %v", err) - } - return v, err -} - -func (p *parser) literal() (segment, error) { - lit, err := p.accept(typeLiteral) - if err != nil { - return nil, err - } - return literal(lit), nil -} - -func (p *parser) variable() (segment, error) { - if _, err := p.accept("{"); err != nil { - return nil, err - } - - path, err := p.fieldPath() - if err != nil { - return nil, err - } - - var segs []segment - if _, err := p.accept("="); err == nil { - segs, err = p.segments() - if err != nil { - return nil, fmt.Errorf("invalid segment in variable %q: %v", path, err) - } - } else { - segs = []segment{wildcard{}} - } - - if _, err := p.accept("}"); err != nil { - return nil, fmt.Errorf("unterminated variable segment: %s", path) - } - return variable{ - path: path, - segments: segs, - }, nil -} - -func (p *parser) fieldPath() (string, error) { - c, err := p.accept(typeIdent) - if err != nil { - return "", err - } - components := []string{c} - for { - if _, err = p.accept("."); err != nil { - return strings.Join(components, "."), nil - } - c, err := p.accept(typeIdent) - if err != nil { - return "", fmt.Errorf("invalid field path component: %v", err) - } - components = append(components, c) - } -} - -// A termType is a type of terminal symbols. -type termType string - -// These constants define some of valid values of termType. -// They improve readability of parse functions. -// -// You can also use "/", "*", "**", "." or "=" as valid values. -const ( - typeIdent = termType("ident") - typeLiteral = termType("literal") - typeEOF = termType("$") -) - -const ( - // eof is the terminal symbol which always appears at the end of token sequence. - eof = "\u0000" -) - -// accept tries to accept a token in "p". -// This function consumes a token and returns it if it matches to the specified "term". -// If it doesn't match, the function does not consume any tokens and return an error. -func (p *parser) accept(term termType) (string, error) { - t := p.tokens[0] - switch term { - case "/", "*", "**", ".", "=", "{", "}": - if t != string(term) && t != "/" { - return "", fmt.Errorf("expected %q but got %q", term, t) - } - case typeEOF: - if t != eof { - return "", fmt.Errorf("expected EOF but got %q", t) - } - case typeIdent: - if err := expectIdent(t); err != nil { - return "", err - } - case typeLiteral: - if err := expectPChars(t); err != nil { - return "", err - } - default: - return "", fmt.Errorf("unknown termType %q", term) - } - p.tokens = p.tokens[1:] - p.accepted = append(p.accepted, t) - return t, nil -} - -// expectPChars determines if "t" consists of only pchars defined in RFC3986. -// -// https://www.ietf.org/rfc/rfc3986.txt, P.49 -// pchar = unreserved / pct-encoded / sub-delims / ":" / "@" -// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" -// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" -// / "*" / "+" / "," / ";" / "=" -// pct-encoded = "%" HEXDIG HEXDIG -func expectPChars(t string) error { - const ( - init = iota - pct1 - pct2 - ) - st := init - for _, r := range t { - if st != init { - if !isHexDigit(r) { - return fmt.Errorf("invalid hexdigit: %c(%U)", r, r) - } - switch st { - case pct1: - st = pct2 - case pct2: - st = init - } - continue - } - - // unreserved - switch { - case 'A' <= r && r <= 'Z': - continue - case 'a' <= r && r <= 'z': - continue - case '0' <= r && r <= '9': - continue - } - switch r { - case '-', '.', '_', '~': - // unreserved - case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': - // sub-delims - case ':', '@': - // rest of pchar - case '%': - // pct-encoded - st = pct1 - default: - return fmt.Errorf("invalid character in path segment: %q(%U)", r, r) - } - } - if st != init { - return fmt.Errorf("invalid percent-encoding in %q", t) - } - return nil -} - -// expectIdent determines if "ident" is a valid identifier in .proto schema ([[:alpha:]_][[:alphanum:]_]*). -func expectIdent(ident string) error { - if ident == "" { - return fmt.Errorf("empty identifier") - } - for pos, r := range ident { - switch { - case '0' <= r && r <= '9': - if pos == 0 { - return fmt.Errorf("identifier starting with digit: %s", ident) - } - continue - case 'A' <= r && r <= 'Z': - continue - case 'a' <= r && r <= 'z': - continue - case r == '_': - continue - default: - return fmt.Errorf("invalid character %q(%U) in identifier: %s", r, r, ident) - } - } - return nil -} - -func isHexDigit(r rune) bool { - switch { - case '0' <= r && r <= '9': - return true - case 'A' <= r && r <= 'F': - return true - case 'a' <= r && r <= 'f': - return true - } - return false -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/types.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/types.go deleted file mode 100644 index 5a814a0004cec..0000000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/types.go +++ /dev/null @@ -1,60 +0,0 @@ -package httprule - -import ( - "fmt" - "strings" -) - -type template struct { - segments []segment - verb string - template string -} - -type segment interface { - fmt.Stringer - compile() (ops []op) -} - -type wildcard struct{} - -type deepWildcard struct{} - -type literal string - -type variable struct { - path string - segments []segment -} - -func (wildcard) String() string { - return "*" -} - -func (deepWildcard) String() string { - return "**" -} - -func (l literal) String() string { - return string(l) -} - -func (v variable) String() string { - var segs []string - for _, s := range v.segments { - segs = append(segs, s.String()) - } - return fmt.Sprintf("{%s=%s}", v.path, strings.Join(segs, "/")) -} - -func (t template) String() string { - var segs []string - for _, s := range t.segments { - segs = append(segs, s.String()) - } - str := strings.Join(segs, "/") - if t.verb != "" { - str = fmt.Sprintf("%s:%s", str, t.verb) - } - return "/" + str -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel deleted file mode 100644 index 95f867a5286cb..0000000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel +++ /dev/null @@ -1,91 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") - -package(default_visibility = ["//visibility:public"]) - -go_library( - name = "runtime", - srcs = [ - "context.go", - "convert.go", - "doc.go", - "errors.go", - "fieldmask.go", - "handler.go", - "marshal_httpbodyproto.go", - "marshal_json.go", - "marshal_jsonpb.go", - "marshal_proto.go", - "marshaler.go", - "marshaler_registry.go", - "mux.go", - "pattern.go", - "proto2_convert.go", - "query.go", - ], - importpath = "github.com/grpc-ecosystem/grpc-gateway/v2/runtime", - deps = [ - "//internal/httprule", - "//utilities", - "@go_googleapis//google/api:httpbody_go_proto", - "@io_bazel_rules_go//proto/wkt:field_mask_go_proto", - "@org_golang_google_grpc//codes", - "@org_golang_google_grpc//grpclog", - "@org_golang_google_grpc//metadata", - "@org_golang_google_grpc//status", - "@org_golang_google_protobuf//encoding/protojson", - "@org_golang_google_protobuf//proto", - "@org_golang_google_protobuf//reflect/protoreflect", - "@org_golang_google_protobuf//reflect/protoregistry", - "@org_golang_google_protobuf//types/known/durationpb", - "@org_golang_google_protobuf//types/known/timestamppb", - "@org_golang_google_protobuf//types/known/wrapperspb", - ], -) - -go_test( - name = "runtime_test", - size = "small", - srcs = [ - "context_test.go", - "convert_test.go", - "errors_test.go", - "fieldmask_test.go", - "handler_test.go", - "marshal_httpbodyproto_test.go", - "marshal_json_test.go", - "marshal_jsonpb_test.go", - "marshal_proto_test.go", - "marshaler_registry_test.go", - "mux_test.go", - "pattern_test.go", - "query_test.go", - ], - embed = [":runtime"], - deps = [ - "//runtime/internal/examplepb", - "//utilities", - "@com_github_google_go_cmp//cmp", - "@com_github_google_go_cmp//cmp/cmpopts", - "@go_googleapis//google/api:httpbody_go_proto", - "@go_googleapis//google/rpc:errdetails_go_proto", - "@go_googleapis//google/rpc:status_go_proto", - "@io_bazel_rules_go//proto/wkt:field_mask_go_proto", - "@org_golang_google_grpc//codes", - "@org_golang_google_grpc//metadata", - "@org_golang_google_grpc//status", - "@org_golang_google_protobuf//encoding/protojson", - "@org_golang_google_protobuf//proto", - "@org_golang_google_protobuf//testing/protocmp", - "@org_golang_google_protobuf//types/known/durationpb", - "@org_golang_google_protobuf//types/known/emptypb", - "@org_golang_google_protobuf//types/known/structpb", - "@org_golang_google_protobuf//types/known/timestamppb", - "@org_golang_google_protobuf//types/known/wrapperspb", - ], -) - -alias( - name = "go_default_library", - actual = ":runtime", - visibility = ["//visibility:public"], -) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go deleted file mode 100644 index d9e0013c43927..0000000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go +++ /dev/null @@ -1,180 +0,0 @@ -package runtime - -import ( - "context" - "errors" - "io" - "net/http" - - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/status" -) - -// ErrorHandlerFunc is the signature used to configure error handling. -type ErrorHandlerFunc func(context.Context, *ServeMux, Marshaler, http.ResponseWriter, *http.Request, error) - -// StreamErrorHandlerFunc is the signature used to configure stream error handling. -type StreamErrorHandlerFunc func(context.Context, error) *status.Status - -// RoutingErrorHandlerFunc is the signature used to configure error handling for routing errors. -type RoutingErrorHandlerFunc func(context.Context, *ServeMux, Marshaler, http.ResponseWriter, *http.Request, int) - -// HTTPStatusError is the error to use when needing to provide a different HTTP status code for an error -// passed to the DefaultRoutingErrorHandler. -type HTTPStatusError struct { - HTTPStatus int - Err error -} - -func (e *HTTPStatusError) Error() string { - return e.Err.Error() -} - -// HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status. -// See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto -func HTTPStatusFromCode(code codes.Code) int { - switch code { - case codes.OK: - return http.StatusOK - case codes.Canceled: - return http.StatusRequestTimeout - case codes.Unknown: - return http.StatusInternalServerError - case codes.InvalidArgument: - return http.StatusBadRequest - case codes.DeadlineExceeded: - return http.StatusGatewayTimeout - case codes.NotFound: - return http.StatusNotFound - case codes.AlreadyExists: - return http.StatusConflict - case codes.PermissionDenied: - return http.StatusForbidden - case codes.Unauthenticated: - return http.StatusUnauthorized - case codes.ResourceExhausted: - return http.StatusTooManyRequests - case codes.FailedPrecondition: - // Note, this deliberately doesn't translate to the similarly named '412 Precondition Failed' HTTP response status. - return http.StatusBadRequest - case codes.Aborted: - return http.StatusConflict - case codes.OutOfRange: - return http.StatusBadRequest - case codes.Unimplemented: - return http.StatusNotImplemented - case codes.Internal: - return http.StatusInternalServerError - case codes.Unavailable: - return http.StatusServiceUnavailable - case codes.DataLoss: - return http.StatusInternalServerError - } - - grpclog.Infof("Unknown gRPC error code: %v", code) - return http.StatusInternalServerError -} - -// HTTPError uses the mux-configured error handler. -func HTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error) { - mux.errorHandler(ctx, mux, marshaler, w, r, err) -} - -// DefaultHTTPErrorHandler is the default error handler. -// If "err" is a gRPC Status, the function replies with the status code mapped by HTTPStatusFromCode. -// If "err" is a HTTPStatusError, the function replies with the status code provide by that struct. This is -// intended to allow passing through of specific statuses via the function set via WithRoutingErrorHandler -// for the ServeMux constructor to handle edge cases which the standard mappings in HTTPStatusFromCode -// are insufficient for. -// If otherwise, it replies with http.StatusInternalServerError. -// -// The response body written by this function is a Status message marshaled by the Marshaler. -func DefaultHTTPErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error) { - // return Internal when Marshal failed - const fallback = `{"code": 13, "message": "failed to marshal error message"}` - - var customStatus *HTTPStatusError - if errors.As(err, &customStatus) { - err = customStatus.Err - } - - s := status.Convert(err) - pb := s.Proto() - - w.Header().Del("Trailer") - w.Header().Del("Transfer-Encoding") - - contentType := marshaler.ContentType(pb) - w.Header().Set("Content-Type", contentType) - - if s.Code() == codes.Unauthenticated { - w.Header().Set("WWW-Authenticate", s.Message()) - } - - buf, merr := marshaler.Marshal(pb) - if merr != nil { - grpclog.Infof("Failed to marshal error message %q: %v", s, merr) - w.WriteHeader(http.StatusInternalServerError) - if _, err := io.WriteString(w, fallback); err != nil { - grpclog.Infof("Failed to write response: %v", err) - } - return - } - - md, ok := ServerMetadataFromContext(ctx) - if !ok { - grpclog.Infof("Failed to extract ServerMetadata from context") - } - - handleForwardResponseServerMetadata(w, mux, md) - - // RFC 7230 https://tools.ietf.org/html/rfc7230#section-4.1.2 - // Unless the request includes a TE header field indicating "trailers" - // is acceptable, as described in Section 4.3, a server SHOULD NOT - // generate trailer fields that it believes are necessary for the user - // agent to receive. - doForwardTrailers := requestAcceptsTrailers(r) - - if doForwardTrailers { - handleForwardResponseTrailerHeader(w, md) - w.Header().Set("Transfer-Encoding", "chunked") - } - - st := HTTPStatusFromCode(s.Code()) - if customStatus != nil { - st = customStatus.HTTPStatus - } - - w.WriteHeader(st) - if _, err := w.Write(buf); err != nil { - grpclog.Infof("Failed to write response: %v", err) - } - - if doForwardTrailers { - handleForwardResponseTrailer(w, md) - } -} - -func DefaultStreamErrorHandler(_ context.Context, err error) *status.Status { - return status.Convert(err) -} - -// DefaultRoutingErrorHandler is our default handler for routing errors. -// By default http error codes mapped on the following error codes: -// NotFound -> grpc.NotFound -// StatusBadRequest -> grpc.InvalidArgument -// MethodNotAllowed -> grpc.Unimplemented -// Other -> grpc.Internal, method is not expecting to be called for anything else -func DefaultRoutingErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, httpStatus int) { - sterr := status.Error(codes.Internal, "Unexpected routing error") - switch httpStatus { - case http.StatusBadRequest: - sterr = status.Error(codes.InvalidArgument, http.StatusText(httpStatus)) - case http.StatusMethodNotAllowed: - sterr = status.Error(codes.Unimplemented, http.StatusText(httpStatus)) - case http.StatusNotFound: - sterr = status.Error(codes.NotFound, http.StatusText(httpStatus)) - } - mux.errorHandler(ctx, mux, marshaler, w, r, sterr) -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go deleted file mode 100644 index 0138ed2f769f7..0000000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go +++ /dev/null @@ -1,165 +0,0 @@ -package runtime - -import ( - "encoding/json" - "fmt" - "io" - "sort" - - "google.golang.org/genproto/protobuf/field_mask" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" -) - -func getFieldByName(fields protoreflect.FieldDescriptors, name string) protoreflect.FieldDescriptor { - fd := fields.ByName(protoreflect.Name(name)) - if fd != nil { - return fd - } - - return fields.ByJSONName(name) -} - -// FieldMaskFromRequestBody creates a FieldMask printing all complete paths from the JSON body. -func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.FieldMask, error) { - fm := &field_mask.FieldMask{} - var root interface{} - - if err := json.NewDecoder(r).Decode(&root); err != nil { - if err == io.EOF { - return fm, nil - } - return nil, err - } - - queue := []fieldMaskPathItem{{node: root, msg: msg.ProtoReflect()}} - for len(queue) > 0 { - // dequeue an item - item := queue[0] - queue = queue[1:] - - m, ok := item.node.(map[string]interface{}) - switch { - case ok: - // if the item is an object, then enqueue all of its children - for k, v := range m { - if item.msg == nil { - return nil, fmt.Errorf("JSON structure did not match request type") - } - - fd := getFieldByName(item.msg.Descriptor().Fields(), k) - if fd == nil { - return nil, fmt.Errorf("could not find field %q in %q", k, item.msg.Descriptor().FullName()) - } - - if isDynamicProtoMessage(fd.Message()) { - for _, p := range buildPathsBlindly(k, v) { - newPath := p - if item.path != "" { - newPath = item.path + "." + newPath - } - queue = append(queue, fieldMaskPathItem{path: newPath}) - } - continue - } - - if isProtobufAnyMessage(fd.Message()) { - _, hasTypeField := v.(map[string]interface{})["@type"] - if hasTypeField { - queue = append(queue, fieldMaskPathItem{path: k}) - continue - } else { - return nil, fmt.Errorf("could not find field @type in %q in message %q", k, item.msg.Descriptor().FullName()) - } - - } - - child := fieldMaskPathItem{ - node: v, - } - if item.path == "" { - child.path = string(fd.FullName().Name()) - } else { - child.path = item.path + "." + string(fd.FullName().Name()) - } - - switch { - case fd.IsList(), fd.IsMap(): - // As per: https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/field_mask.proto#L85-L86 - // Do not recurse into repeated fields. The repeated field goes on the end of the path and we stop. - fm.Paths = append(fm.Paths, child.path) - case fd.Message() != nil: - child.msg = item.msg.Get(fd).Message() - fallthrough - default: - queue = append(queue, child) - } - } - case len(item.path) > 0: - // otherwise, it's a leaf node so print its path - fm.Paths = append(fm.Paths, item.path) - } - } - - // Sort for deterministic output in the presence - // of repeated fields. - sort.Strings(fm.Paths) - - return fm, nil -} - -func isProtobufAnyMessage(md protoreflect.MessageDescriptor) bool { - return md != nil && (md.FullName() == "google.protobuf.Any") -} - -func isDynamicProtoMessage(md protoreflect.MessageDescriptor) bool { - return md != nil && (md.FullName() == "google.protobuf.Struct" || md.FullName() == "google.protobuf.Value") -} - -// buildPathsBlindly does not attempt to match proto field names to the -// json value keys. Instead it relies completely on the structure of -// the unmarshalled json contained within in. -// Returns a slice containing all subpaths with the root at the -// passed in name and json value. -func buildPathsBlindly(name string, in interface{}) []string { - m, ok := in.(map[string]interface{}) - if !ok { - return []string{name} - } - - var paths []string - queue := []fieldMaskPathItem{{path: name, node: m}} - for len(queue) > 0 { - cur := queue[0] - queue = queue[1:] - - m, ok := cur.node.(map[string]interface{}) - if !ok { - // This should never happen since we should always check that we only add - // nodes of type map[string]interface{} to the queue. - continue - } - for k, v := range m { - if mi, ok := v.(map[string]interface{}); ok { - queue = append(queue, fieldMaskPathItem{path: cur.path + "." + k, node: mi}) - } else { - // This is not a struct, so there are no more levels to descend. - curPath := cur.path + "." + k - paths = append(paths, curPath) - } - } - } - return paths -} - -// fieldMaskPathItem stores a in-progress deconstruction of a path for a fieldmask -type fieldMaskPathItem struct { - // the list of prior fields leading up to node connected by dots - path string - - // a generic decoded json object the current item to inspect for further path extraction - node interface{} - - // parent message - msg protoreflect.Message -} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go deleted file mode 100644 index fb0c84ef0cdd4..0000000000000 --- a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go +++ /dev/null @@ -1,329 +0,0 @@ -package runtime - -import ( - "encoding/base64" - "errors" - "fmt" - "net/url" - "regexp" - "strconv" - "strings" - "time" - - "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" - "google.golang.org/genproto/protobuf/field_mask" - "google.golang.org/grpc/grpclog" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" - "google.golang.org/protobuf/types/known/durationpb" - "google.golang.org/protobuf/types/known/timestamppb" - "google.golang.org/protobuf/types/known/wrapperspb" -) - -var valuesKeyRegexp = regexp.MustCompile(`^(.*)\[(.*)\]$`) - -var currentQueryParser QueryParameterParser = &defaultQueryParser{} - -// QueryParameterParser defines interface for all query parameter parsers -type QueryParameterParser interface { - Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error -} - -// PopulateQueryParameters parses query parameters -// into "msg" using current query parser -func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error { - return currentQueryParser.Parse(msg, values, filter) -} - -type defaultQueryParser struct{} - -// Parse populates "values" into "msg". -// A value is ignored if its key starts with one of the elements in "filter". -func (*defaultQueryParser) Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error { - for key, values := range values { - match := valuesKeyRegexp.FindStringSubmatch(key) - if len(match) == 3 { - key = match[1] - values = append([]string{match[2]}, values...) - } - fieldPath := strings.Split(key, ".") - if filter.HasCommonPrefix(fieldPath) { - continue - } - if err := populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, values); err != nil { - return err - } - } - return nil -} - -// PopulateFieldFromPath sets a value in a nested Protobuf structure. -func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error { - fieldPath := strings.Split(fieldPathString, ".") - return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value}) -} - -func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string) error { - if len(fieldPath) < 1 { - return errors.New("no field path") - } - if len(values) < 1 { - return errors.New("no value provided") - } - - var fieldDescriptor protoreflect.FieldDescriptor - for i, fieldName := range fieldPath { - fields := msgValue.Descriptor().Fields() - - // Get field by name - fieldDescriptor = fields.ByName(protoreflect.Name(fieldName)) - if fieldDescriptor == nil { - fieldDescriptor = fields.ByJSONName(fieldName) - if fieldDescriptor == nil { - // We're not returning an error here because this could just be - // an extra query parameter that isn't part of the request. - grpclog.Infof("field not found in %q: %q", msgValue.Descriptor().FullName(), strings.Join(fieldPath, ".")) - return nil - } - } - - // If this is the last element, we're done - if i == len(fieldPath)-1 { - break - } - - // Only singular message fields are allowed - if fieldDescriptor.Message() == nil || fieldDescriptor.Cardinality() == protoreflect.Repeated { - return fmt.Errorf("invalid path: %q is not a message", fieldName) - } - - // Get the nested message - msgValue = msgValue.Mutable(fieldDescriptor).Message() - } - - // Check if oneof already set - if of := fieldDescriptor.ContainingOneof(); of != nil { - if f := msgValue.WhichOneof(of); f != nil { - return fmt.Errorf("field already set for oneof %q", of.FullName().Name()) - } - } - - switch { - case fieldDescriptor.IsList(): - return populateRepeatedField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values) - case fieldDescriptor.IsMap(): - return populateMapField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).Map(), values) - } - - if len(values) > 1 { - return fmt.Errorf("too many values for field %q: %s", fieldDescriptor.FullName().Name(), strings.Join(values, ", ")) - } - - return populateField(fieldDescriptor, msgValue, values[0]) -} - -func populateField(fieldDescriptor protoreflect.FieldDescriptor, msgValue protoreflect.Message, value string) error { - v, err := parseField(fieldDescriptor, value) - if err != nil { - return fmt.Errorf("parsing field %q: %w", fieldDescriptor.FullName().Name(), err) - } - - msgValue.Set(fieldDescriptor, v) - return nil -} - -func populateRepeatedField(fieldDescriptor protoreflect.FieldDescriptor, list protoreflect.List, values []string) error { - for _, value := range values { - v, err := parseField(fieldDescriptor, value) - if err != nil { - return fmt.Errorf("parsing list %q: %w", fieldDescriptor.FullName().Name(), err) - } - list.Append(v) - } - - return nil -} - -func populateMapField(fieldDescriptor protoreflect.FieldDescriptor, mp protoreflect.Map, values []string) error { - if len(values) != 2 { - return fmt.Errorf("more than one value provided for key %q in map %q", values[0], fieldDescriptor.FullName()) - } - - key, err := parseField(fieldDescriptor.MapKey(), values[0]) - if err != nil { - return fmt.Errorf("parsing map key %q: %w", fieldDescriptor.FullName().Name(), err) - } - - value, err := parseField(fieldDescriptor.MapValue(), values[1]) - if err != nil { - return fmt.Errorf("parsing map value %q: %w", fieldDescriptor.FullName().Name(), err) - } - - mp.Set(key.MapKey(), value) - - return nil -} - -func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (protoreflect.Value, error) { - switch fieldDescriptor.Kind() { - case protoreflect.BoolKind: - v, err := strconv.ParseBool(value) - if err != nil { - return protoreflect.Value{}, err - } - return protoreflect.ValueOfBool(v), nil - case protoreflect.EnumKind: - enum, err := protoregistry.GlobalTypes.FindEnumByName(fieldDescriptor.Enum().FullName()) - switch { - case errors.Is(err, protoregistry.NotFound): - return protoreflect.Value{}, fmt.Errorf("enum %q is not registered", fieldDescriptor.Enum().FullName()) - case err != nil: - return protoreflect.Value{}, fmt.Errorf("failed to look up enum: %w", err) - } - // Look for enum by name - v := enum.Descriptor().Values().ByName(protoreflect.Name(value)) - if v == nil { - i, err := strconv.Atoi(value) - if err != nil { - return protoreflect.Value{}, fmt.Errorf("%q is not a valid value", value) - } - // Look for enum by number - v = enum.Descriptor().Values().ByNumber(protoreflect.EnumNumber(i)) - if v == nil { - return protoreflect.Value{}, fmt.Errorf("%q is not a valid value", value) - } - } - return protoreflect.ValueOfEnum(v.Number()), nil - case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: - v, err := strconv.ParseInt(value, 10, 32) - if err != nil { - return protoreflect.Value{}, err - } - return protoreflect.ValueOfInt32(int32(v)), nil - case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: - v, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return protoreflect.Value{}, err - } - return protoreflect.ValueOfInt64(v), nil - case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: - v, err := strconv.ParseUint(value, 10, 32) - if err != nil { - return protoreflect.Value{}, err - } - return protoreflect.ValueOfUint32(uint32(v)), nil - case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: - v, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return protoreflect.Value{}, err - } - return protoreflect.ValueOfUint64(v), nil - case protoreflect.FloatKind: - v, err := strconv.ParseFloat(value, 32) - if err != nil { - return protoreflect.Value{}, err - } - return protoreflect.ValueOfFloat32(float32(v)), nil - case protoreflect.DoubleKind: - v, err := strconv.ParseFloat(value, 64) - if err != nil { - return protoreflect.Value{}, err - } - return protoreflect.ValueOfFloat64(v), nil - case protoreflect.StringKind: - return protoreflect.ValueOfString(value), nil - case protoreflect.BytesKind: - v, err := base64.URLEncoding.DecodeString(value) - if err != nil { - return protoreflect.Value{}, err - } - return protoreflect.ValueOfBytes(v), nil - case protoreflect.MessageKind, protoreflect.GroupKind: - return parseMessage(fieldDescriptor.Message(), value) - default: - panic(fmt.Sprintf("unknown field kind: %v", fieldDescriptor.Kind())) - } -} - -func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (protoreflect.Value, error) { - var msg proto.Message - switch msgDescriptor.FullName() { - case "google.protobuf.Timestamp": - if value == "null" { - break - } - t, err := time.Parse(time.RFC3339Nano, value) - if err != nil { - return protoreflect.Value{}, err - } - msg = timestamppb.New(t) - case "google.protobuf.Duration": - if value == "null" { - break - } - d, err := time.ParseDuration(value) - if err != nil { - return protoreflect.Value{}, err - } - msg = durationpb.New(d) - case "google.protobuf.DoubleValue": - v, err := strconv.ParseFloat(value, 64) - if err != nil { - return protoreflect.Value{}, err - } - msg = &wrapperspb.DoubleValue{Value: v} - case "google.protobuf.FloatValue": - v, err := strconv.ParseFloat(value, 32) - if err != nil { - return protoreflect.Value{}, err - } - msg = &wrapperspb.FloatValue{Value: float32(v)} - case "google.protobuf.Int64Value": - v, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return protoreflect.Value{}, err - } - msg = &wrapperspb.Int64Value{Value: v} - case "google.protobuf.Int32Value": - v, err := strconv.ParseInt(value, 10, 32) - if err != nil { - return protoreflect.Value{}, err - } - msg = &wrapperspb.Int32Value{Value: int32(v)} - case "google.protobuf.UInt64Value": - v, err := strconv.ParseUint(value, 10, 64) - if err != nil { - return protoreflect.Value{}, err - } - msg = &wrapperspb.UInt64Value{Value: v} - case "google.protobuf.UInt32Value": - v, err := strconv.ParseUint(value, 10, 32) - if err != nil { - return protoreflect.Value{}, err - } - msg = &wrapperspb.UInt32Value{Value: uint32(v)} - case "google.protobuf.BoolValue": - v, err := strconv.ParseBool(value) - if err != nil { - return protoreflect.Value{}, err - } - msg = &wrapperspb.BoolValue{Value: v} - case "google.protobuf.StringValue": - msg = &wrapperspb.StringValue{Value: value} - case "google.protobuf.BytesValue": - v, err := base64.URLEncoding.DecodeString(value) - if err != nil { - return protoreflect.Value{}, err - } - msg = &wrapperspb.BytesValue{Value: v} - case "google.protobuf.FieldMask": - fm := &field_mask.FieldMask{} - fm.Paths = append(fm.Paths, strings.Split(value, ",")...) - msg = fm - default: - return protoreflect.Value{}, fmt.Errorf("unsupported message type: %q", string(msgDescriptor.FullName())) - } - - return protoreflect.ValueOfMessage(msg.ProtoReflect()), nil -} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/config.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/grpctrace.go similarity index 58% rename from vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/config.go rename to vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/grpctrace.go index 2ae8620fb6bf2..aaeb19e30d013 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/config.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/grpctrace.go @@ -12,16 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" +package otelgrpc import ( + "context" + + "google.golang.org/grpc/metadata" + "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/metric" - "go.opentelemetry.io/otel/metric/global" - "go.opentelemetry.io/otel/metric/instrument" + "go.opentelemetry.io/otel/baggage" "go.opentelemetry.io/otel/propagation" - semconv "go.opentelemetry.io/otel/semconv/v1.17.0" "go.opentelemetry.io/otel/trace" ) @@ -32,20 +33,10 @@ const ( GRPCStatusCodeKey = attribute.Key("rpc.grpc.status_code") ) -// Filter is a predicate used to determine whether a given request in -// interceptor info should be traced. A Filter must return true if -// the request should be traced. -type Filter func(*InterceptorInfo) bool - // config is a group of options for this instrumentation. type config struct { - Filter Filter Propagators propagation.TextMapPropagator TracerProvider trace.TracerProvider - MeterProvider metric.MeterProvider - - meter metric.Meter - rpcServerDuration instrument.Int64Histogram } // Option applies an option value for a config. @@ -58,22 +49,10 @@ func newConfig(opts []Option) *config { c := &config{ Propagators: otel.GetTextMapPropagator(), TracerProvider: otel.GetTracerProvider(), - MeterProvider: global.MeterProvider(), } for _, o := range opts { o.apply(c) } - - c.meter = c.MeterProvider.Meter( - instrumentationName, - metric.WithInstrumentationVersion(SemVersion()), - metric.WithSchemaURL(semconv.SchemaURL), - ) - var err error - if c.rpcServerDuration, err = c.meter.Int64Histogram("rpc.server.duration", instrument.WithUnit("ms")); err != nil { - otel.Handle(err) - } - return c } @@ -99,37 +78,57 @@ func (o tracerProviderOption) apply(c *config) { } } -// WithInterceptorFilter returns an Option to use the request filter. -func WithInterceptorFilter(f Filter) Option { - return interceptorFilterOption{f: f} +// WithTracerProvider returns an Option to use the TracerProvider when +// creating a Tracer. +func WithTracerProvider(tp trace.TracerProvider) Option { + return tracerProviderOption{tp: tp} } -type interceptorFilterOption struct { - f Filter +type metadataSupplier struct { + metadata *metadata.MD } -func (o interceptorFilterOption) apply(c *config) { - if o.f != nil { - c.Filter = o.f +// assert that metadataSupplier implements the TextMapCarrier interface +var _ propagation.TextMapCarrier = &metadataSupplier{} + +func (s *metadataSupplier) Get(key string) string { + values := s.metadata.Get(key) + if len(values) == 0 { + return "" } + return values[0] } -// WithTracerProvider returns an Option to use the TracerProvider when -// creating a Tracer. -func WithTracerProvider(tp trace.TracerProvider) Option { - return tracerProviderOption{tp: tp} +func (s *metadataSupplier) Set(key string, value string) { + s.metadata.Set(key, value) } -type meterProviderOption struct{ mp metric.MeterProvider } - -func (o meterProviderOption) apply(c *config) { - if o.mp != nil { - c.MeterProvider = o.mp +func (s *metadataSupplier) Keys() []string { + out := make([]string, 0, len(*s.metadata)) + for key := range *s.metadata { + out = append(out, key) } + return out } -// WithMeterProvider returns an Option to use the MeterProvider when -// creating a Meter. If this option is not provide the global MeterProvider will be used. -func WithMeterProvider(mp metric.MeterProvider) Option { - return meterProviderOption{mp: mp} +// Inject injects correlation context and span context into the gRPC +// metadata object. This function is meant to be used on outgoing +// requests. +func Inject(ctx context.Context, metadata *metadata.MD, opts ...Option) { + c := newConfig(opts) + c.Propagators.Inject(ctx, &metadataSupplier{ + metadata: metadata, + }) +} + +// Extract returns the correlation context and span context that +// another service encoded in the gRPC metadata object with Inject. +// This function is meant to be used on incoming requests. +func Extract(ctx context.Context, metadata *metadata.MD, opts ...Option) (baggage.Baggage, trace.SpanContext) { + c := newConfig(opts) + ctx = c.Propagators.Extract(ctx, &metadataSupplier{ + metadata: metadata, + }) + + return baggage.FromContext(ctx), trace.SpanContextFromContext(ctx) } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/interceptor.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/interceptor.go index b74d558e3777a..b1d9f643d84bc 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/interceptor.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/interceptor.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" +package otelgrpc // gRPC tracing middleware // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/rpc.md @@ -20,36 +20,41 @@ import ( "context" "io" "net" - "strconv" - "time" + + "github.com/golang/protobuf/proto" // nolint:staticcheck "google.golang.org/grpc" grpc_codes "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/status" - "google.golang.org/protobuf/proto" "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal" "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/baggage" "go.opentelemetry.io/otel/codes" - semconv "go.opentelemetry.io/otel/semconv/v1.17.0" + semconv "go.opentelemetry.io/otel/semconv/v1.7.0" "go.opentelemetry.io/otel/trace" ) type messageType attribute.KeyValue // Event adds an event of the messageType to the span associated with the -// passed context with a message id. -func (m messageType) Event(ctx context.Context, id int, _ interface{}) { +// passed context with id and size (if message is a proto message). +func (m messageType) Event(ctx context.Context, id int, message interface{}) { span := trace.SpanFromContext(ctx) - if !span.IsRecording() { - return + if p, ok := message.(proto.Message); ok { + span.AddEvent("message", trace.WithAttributes( + attribute.KeyValue(m), + RPCMessageIDKey.Int(id), + RPCMessageUncompressedSizeKey.Int(proto.Size(p)), + )) + } else { + span.AddEvent("message", trace.WithAttributes( + attribute.KeyValue(m), + RPCMessageIDKey.Int(id), + )) } - span.AddEvent("message", trace.WithAttributes( - attribute.KeyValue(m), - RPCMessageIDKey.Int(id), - )) } var ( @@ -60,12 +65,6 @@ var ( // UnaryClientInterceptor returns a grpc.UnaryClientInterceptor suitable // for use in a grpc.Dial call. func UnaryClientInterceptor(opts ...Option) grpc.UnaryClientInterceptor { - cfg := newConfig(opts) - tracer := cfg.TracerProvider.Tracer( - instrumentationName, - trace.WithInstrumentationVersion(SemVersion()), - ) - return func( ctx context.Context, method string, @@ -74,13 +73,13 @@ func UnaryClientInterceptor(opts ...Option) grpc.UnaryClientInterceptor { invoker grpc.UnaryInvoker, callOpts ...grpc.CallOption, ) error { - i := &InterceptorInfo{ - Method: method, - Type: UnaryClient, - } - if cfg.Filter != nil && !cfg.Filter(i) { - return invoker(ctx, method, req, reply, cc, callOpts...) - } + requestMetadata, _ := metadata.FromOutgoingContext(ctx) + metadataCopy := requestMetadata.Copy() + + tracer := newConfig(opts).TracerProvider.Tracer( + instrumentationName, + trace.WithInstrumentationVersion(SemVersion()), + ) name, attr := spanInfo(method, cc.Target()) var span trace.Span @@ -92,7 +91,8 @@ func UnaryClientInterceptor(opts ...Option) grpc.UnaryClientInterceptor { ) defer span.End() - ctx = inject(ctx, cfg.Propagators) + Inject(ctx, &metadataCopy, opts...) + ctx = metadata.NewOutgoingContext(ctx, metadataCopy) messageSent.Event(ctx, 1, req) @@ -235,12 +235,6 @@ func (w *clientStream) sendStreamEvent(eventType streamEventType, err error) { // StreamClientInterceptor returns a grpc.StreamClientInterceptor suitable // for use in a grpc.Dial call. func StreamClientInterceptor(opts ...Option) grpc.StreamClientInterceptor { - cfg := newConfig(opts) - tracer := cfg.TracerProvider.Tracer( - instrumentationName, - trace.WithInstrumentationVersion(SemVersion()), - ) - return func( ctx context.Context, desc *grpc.StreamDesc, @@ -249,13 +243,13 @@ func StreamClientInterceptor(opts ...Option) grpc.StreamClientInterceptor { streamer grpc.Streamer, callOpts ...grpc.CallOption, ) (grpc.ClientStream, error) { - i := &InterceptorInfo{ - Method: method, - Type: StreamClient, - } - if cfg.Filter != nil && !cfg.Filter(i) { - return streamer(ctx, desc, cc, method, callOpts...) - } + requestMetadata, _ := metadata.FromOutgoingContext(ctx) + metadataCopy := requestMetadata.Copy() + + tracer := newConfig(opts).TracerProvider.Tracer( + instrumentationName, + trace.WithInstrumentationVersion(SemVersion()), + ) name, attr := spanInfo(method, cc.Target()) var span trace.Span @@ -266,7 +260,8 @@ func StreamClientInterceptor(opts ...Option) grpc.StreamClientInterceptor { trace.WithAttributes(attr...), ) - ctx = inject(ctx, cfg.Propagators) + Inject(ctx, &metadataCopy, opts...) + ctx = metadata.NewOutgoingContext(ctx, metadataCopy) s, err := streamer(ctx, desc, cc, method, callOpts...) if err != nil { @@ -299,31 +294,26 @@ func StreamClientInterceptor(opts ...Option) grpc.StreamClientInterceptor { // UnaryServerInterceptor returns a grpc.UnaryServerInterceptor suitable // for use in a grpc.NewServer call. func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor { - cfg := newConfig(opts) - tracer := cfg.TracerProvider.Tracer( - instrumentationName, - trace.WithInstrumentationVersion(SemVersion()), - ) - return func( ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, ) (interface{}, error) { - i := &InterceptorInfo{ - UnaryServerInfo: info, - Type: UnaryServer, - } - if cfg.Filter != nil && !cfg.Filter(i) { - return handler(ctx, req) - } + requestMetadata, _ := metadata.FromIncomingContext(ctx) + metadataCopy := requestMetadata.Copy() + + bags, spanCtx := Extract(ctx, &metadataCopy, opts...) + ctx = baggage.ContextWithBaggage(ctx, bags) - ctx = extract(ctx, cfg.Propagators) + tracer := newConfig(opts).TracerProvider.Tracer( + instrumentationName, + trace.WithInstrumentationVersion(SemVersion()), + ) name, attr := spanInfo(info.FullMethod, peerFromCtx(ctx)) ctx, span := tracer.Start( - trace.ContextWithRemoteSpanContext(ctx, trace.SpanContextFromContext(ctx)), + trace.ContextWithRemoteSpanContext(ctx, spanCtx), name, trace.WithSpanKind(trace.SpanKindServer), trace.WithAttributes(attr...), @@ -332,22 +322,13 @@ func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor { messageReceived.Event(ctx, 1, req) - var statusCode grpc_codes.Code - defer func(t time.Time) { - elapsedTime := time.Since(t) / time.Millisecond - attr = append(attr, semconv.RPCGRPCStatusCodeKey.Int64(int64(statusCode))) - cfg.rpcServerDuration.Record(ctx, int64(elapsedTime), attr...) - }(time.Now()) - resp, err := handler(ctx, req) if err != nil { s, _ := status.FromError(err) - statusCode = s.Code() span.SetStatus(codes.Error, s.Message()) span.SetAttributes(statusCodeAttr(s.Code())) messageSent.Event(ctx, 1, s.Proto()) } else { - statusCode = grpc_codes.OK span.SetAttributes(statusCodeAttr(grpc_codes.OK)) messageSent.Event(ctx, 1, resp) } @@ -400,12 +381,6 @@ func wrapServerStream(ctx context.Context, ss grpc.ServerStream) *serverStream { // StreamServerInterceptor returns a grpc.StreamServerInterceptor suitable // for use in a grpc.NewServer call. func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor { - cfg := newConfig(opts) - tracer := cfg.TracerProvider.Tracer( - instrumentationName, - trace.WithInstrumentationVersion(SemVersion()), - ) - return func( srv interface{}, ss grpc.ServerStream, @@ -413,19 +388,21 @@ func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor { handler grpc.StreamHandler, ) error { ctx := ss.Context() - i := &InterceptorInfo{ - StreamServerInfo: info, - Type: StreamServer, - } - if cfg.Filter != nil && !cfg.Filter(i) { - return handler(srv, wrapServerStream(ctx, ss)) - } - ctx = extract(ctx, cfg.Propagators) + requestMetadata, _ := metadata.FromIncomingContext(ctx) + metadataCopy := requestMetadata.Copy() + + bags, spanCtx := Extract(ctx, &metadataCopy, opts...) + ctx = baggage.ContextWithBaggage(ctx, bags) + + tracer := newConfig(opts).TracerProvider.Tracer( + instrumentationName, + trace.WithInstrumentationVersion(SemVersion()), + ) name, attr := spanInfo(info.FullMethod, peerFromCtx(ctx)) ctx, span := tracer.Start( - trace.ContextWithRemoteSpanContext(ctx, trace.SpanContextFromContext(ctx)), + trace.ContextWithRemoteSpanContext(ctx, spanCtx), name, trace.WithSpanKind(trace.SpanKindServer), trace.WithAttributes(attr...), @@ -433,6 +410,7 @@ func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor { defer span.End() err := handler(srv, wrapServerStream(ctx, ss)) + if err != nil { s, _ := status.FromError(err) span.SetStatus(codes.Error, s.Message()) @@ -457,7 +435,7 @@ func spanInfo(fullMethod, peerAddress string) (string, []attribute.KeyValue) { // peerAttr returns attributes about the peer address. func peerAttr(addr string) []attribute.KeyValue { - host, p, err := net.SplitHostPort(addr) + host, port, err := net.SplitHostPort(addr) if err != nil { return []attribute.KeyValue(nil) } @@ -465,25 +443,11 @@ func peerAttr(addr string) []attribute.KeyValue { if host == "" { host = "127.0.0.1" } - port, err := strconv.Atoi(p) - if err != nil { - return []attribute.KeyValue(nil) - } - var attr []attribute.KeyValue - if ip := net.ParseIP(host); ip != nil { - attr = []attribute.KeyValue{ - semconv.NetSockPeerAddr(host), - semconv.NetSockPeerPort(port), - } - } else { - attr = []attribute.KeyValue{ - semconv.NetPeerName(host), - semconv.NetPeerPort(port), - } + return []attribute.KeyValue{ + semconv.NetPeerIPKey.String(host), + semconv.NetPeerPortKey.String(port), } - - return attr } // peerFromCtx returns a peer address from a context, if one exists. @@ -495,7 +459,7 @@ func peerFromCtx(ctx context.Context) string { return p.Addr.String() } -// statusCodeAttr returns status code attribute based on given gRPC code. +// statusCodeAttr returns status code attribute based on given gRPC code func statusCodeAttr(c grpc_codes.Code) attribute.KeyValue { return GRPCStatusCodeKey.Int64(int64(c)) } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/interceptorinfo.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/interceptorinfo.go deleted file mode 100644 index f6116946bfd85..0000000000000 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/interceptorinfo.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright The OpenTelemetry 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 otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" - -import ( - "google.golang.org/grpc" -) - -// InterceptorType is the flag to define which gRPC interceptor -// the InterceptorInfo object is. -type InterceptorType uint8 - -const ( - // UndefinedInterceptor is the type for the interceptor information that is not - // well initialized or categorized to other types. - UndefinedInterceptor InterceptorType = iota - // UnaryClient is the type for grpc.UnaryClient interceptor. - UnaryClient - // StreamClient is the type for grpc.StreamClient interceptor. - StreamClient - // UnaryServer is the type for grpc.UnaryServer interceptor. - UnaryServer - // StreamServer is the type for grpc.StreamServer interceptor. - StreamServer -) - -// InterceptorInfo is the union of some arguments to four types of -// gRPC interceptors. -type InterceptorInfo struct { - // Method is method name registered to UnaryClient and StreamClient - Method string - // UnaryServerInfo is the metadata for UnaryServer - UnaryServerInfo *grpc.UnaryServerInfo - // StreamServerInfo if the metadata for StreamServer - StreamServerInfo *grpc.StreamServerInfo - // Type is the type for interceptor - Type InterceptorType -} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal/parse.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal/parse.go index c40f87c4f9023..56a682102bb0b 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal/parse.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal/parse.go @@ -12,13 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -package internal // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal" +package internal import ( "strings" "go.opentelemetry.io/otel/attribute" - semconv "go.opentelemetry.io/otel/semconv/v1.17.0" + semconv "go.opentelemetry.io/otel/semconv/v1.7.0" ) // ParseFullMethod returns a span name following the OpenTelemetry semantic @@ -34,10 +34,10 @@ func ParseFullMethod(fullMethod string) (string, []attribute.KeyValue) { var attrs []attribute.KeyValue if service := parts[0]; service != "" { - attrs = append(attrs, semconv.RPCService(service)) + attrs = append(attrs, semconv.RPCServiceKey.String(service)) } if method := parts[1]; method != "" { - attrs = append(attrs, semconv.RPCMethod(method)) + attrs = append(attrs, semconv.RPCMethodKey.String(method)) } return name, attrs } diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/metadata_supplier.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/metadata_supplier.go deleted file mode 100644 index d91c6df2370e8..0000000000000 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/metadata_supplier.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright The OpenTelemetry 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 otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" - -import ( - "context" - - "google.golang.org/grpc/metadata" - - "go.opentelemetry.io/otel/baggage" - "go.opentelemetry.io/otel/propagation" - "go.opentelemetry.io/otel/trace" -) - -type metadataSupplier struct { - metadata *metadata.MD -} - -// assert that metadataSupplier implements the TextMapCarrier interface. -var _ propagation.TextMapCarrier = &metadataSupplier{} - -func (s *metadataSupplier) Get(key string) string { - values := s.metadata.Get(key) - if len(values) == 0 { - return "" - } - return values[0] -} - -func (s *metadataSupplier) Set(key string, value string) { - s.metadata.Set(key, value) -} - -func (s *metadataSupplier) Keys() []string { - out := make([]string, 0, len(*s.metadata)) - for key := range *s.metadata { - out = append(out, key) - } - return out -} - -// Inject injects correlation context and span context into the gRPC -// metadata object. This function is meant to be used on outgoing -// requests. -// Deprecated: Unnecessary public func. -func Inject(ctx context.Context, md *metadata.MD, opts ...Option) { - c := newConfig(opts) - c.Propagators.Inject(ctx, &metadataSupplier{ - metadata: md, - }) -} - -func inject(ctx context.Context, propagators propagation.TextMapPropagator) context.Context { - md, ok := metadata.FromOutgoingContext(ctx) - if !ok { - md = metadata.MD{} - } - propagators.Inject(ctx, &metadataSupplier{ - metadata: &md, - }) - return metadata.NewOutgoingContext(ctx, md) -} - -// Extract returns the correlation context and span context that -// another service encoded in the gRPC metadata object with Inject. -// This function is meant to be used on incoming requests. -// Deprecated: Unnecessary public func. -func Extract(ctx context.Context, md *metadata.MD, opts ...Option) (baggage.Baggage, trace.SpanContext) { - c := newConfig(opts) - ctx = c.Propagators.Extract(ctx, &metadataSupplier{ - metadata: md, - }) - - return baggage.FromContext(ctx), trace.SpanContextFromContext(ctx) -} - -func extract(ctx context.Context, propagators propagation.TextMapPropagator) context.Context { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - md = metadata.MD{} - } - - return propagators.Extract(ctx, &metadataSupplier{ - metadata: &md, - }) -} diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/semconv.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/semconv.go index b65fab308f3c2..73f14a458e19a 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/semconv.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/semconv.go @@ -12,11 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" +package otelgrpc import ( "go.opentelemetry.io/otel/attribute" - semconv "go.opentelemetry.io/otel/semconv/v1.17.0" + semconv "go.opentelemetry.io/otel/semconv/v1.7.0" ) // Semantic conventions for attribute keys for gRPC. @@ -41,7 +41,7 @@ const ( // Semantic conventions for common RPC attributes. var ( // Semantic convention for gRPC as the remoting system. - RPCSystemGRPC = semconv.RPCSystemGRPC + RPCSystemGRPC = semconv.RPCSystemKey.String("grpc") // Semantic convention for a message named message. RPCNameMessage = RPCNameKey.String("message") diff --git a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go index 78cac03ed1db1..f7c0e090794db 100644 --- a/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go +++ b/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go @@ -12,11 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" +package otelgrpc // Version is the current release version of the gRPC instrumentation. func Version() string { - return "0.40.0" + return "0.29.0" // This string is updated by the pre_release.sh script during release } diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/envconfig/envconfig.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/envconfig/envconfig.go deleted file mode 100644 index 53ff3126b6e9f..0000000000000 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/envconfig/envconfig.go +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright The OpenTelemetry 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 envconfig // import "go.opentelemetry.io/otel/exporters/otlp/internal/envconfig" - -import ( - "crypto/tls" - "crypto/x509" - "errors" - "fmt" - "net/url" - "strconv" - "strings" - "time" - - "go.opentelemetry.io/otel/internal/global" -) - -// ConfigFn is the generic function used to set a config. -type ConfigFn func(*EnvOptionsReader) - -// EnvOptionsReader reads the required environment variables. -type EnvOptionsReader struct { - GetEnv func(string) string - ReadFile func(string) ([]byte, error) - Namespace string -} - -// Apply runs every ConfigFn. -func (e *EnvOptionsReader) Apply(opts ...ConfigFn) { - for _, o := range opts { - o(e) - } -} - -// GetEnvValue gets an OTLP environment variable value of the specified key -// using the GetEnv function. -// This function prepends the OTLP specified namespace to all key lookups. -func (e *EnvOptionsReader) GetEnvValue(key string) (string, bool) { - v := strings.TrimSpace(e.GetEnv(keyWithNamespace(e.Namespace, key))) - return v, v != "" -} - -// WithString retrieves the specified config and passes it to ConfigFn as a string. -func WithString(n string, fn func(string)) func(e *EnvOptionsReader) { - return func(e *EnvOptionsReader) { - if v, ok := e.GetEnvValue(n); ok { - fn(v) - } - } -} - -// WithBool returns a ConfigFn that reads the environment variable n and if it exists passes its parsed bool value to fn. -func WithBool(n string, fn func(bool)) ConfigFn { - return func(e *EnvOptionsReader) { - if v, ok := e.GetEnvValue(n); ok { - b := strings.ToLower(v) == "true" - fn(b) - } - } -} - -// WithDuration retrieves the specified config and passes it to ConfigFn as a duration. -func WithDuration(n string, fn func(time.Duration)) func(e *EnvOptionsReader) { - return func(e *EnvOptionsReader) { - if v, ok := e.GetEnvValue(n); ok { - d, err := strconv.Atoi(v) - if err != nil { - global.Error(err, "parse duration", "input", v) - return - } - fn(time.Duration(d) * time.Millisecond) - } - } -} - -// WithHeaders retrieves the specified config and passes it to ConfigFn as a map of HTTP headers. -func WithHeaders(n string, fn func(map[string]string)) func(e *EnvOptionsReader) { - return func(e *EnvOptionsReader) { - if v, ok := e.GetEnvValue(n); ok { - fn(stringToHeader(v)) - } - } -} - -// WithURL retrieves the specified config and passes it to ConfigFn as a net/url.URL. -func WithURL(n string, fn func(*url.URL)) func(e *EnvOptionsReader) { - return func(e *EnvOptionsReader) { - if v, ok := e.GetEnvValue(n); ok { - u, err := url.Parse(v) - if err != nil { - global.Error(err, "parse url", "input", v) - return - } - fn(u) - } - } -} - -// WithCertPool returns a ConfigFn that reads the environment variable n as a filepath to a TLS certificate pool. If it exists, it is parsed as a crypto/x509.CertPool and it is passed to fn. -func WithCertPool(n string, fn func(*x509.CertPool)) ConfigFn { - return func(e *EnvOptionsReader) { - if v, ok := e.GetEnvValue(n); ok { - b, err := e.ReadFile(v) - if err != nil { - global.Error(err, "read tls ca cert file", "file", v) - return - } - c, err := createCertPool(b) - if err != nil { - global.Error(err, "create tls cert pool") - return - } - fn(c) - } - } -} - -// WithClientCert returns a ConfigFn that reads the environment variable nc and nk as filepaths to a client certificate and key pair. If they exists, they are parsed as a crypto/tls.Certificate and it is passed to fn. -func WithClientCert(nc, nk string, fn func(tls.Certificate)) ConfigFn { - return func(e *EnvOptionsReader) { - vc, okc := e.GetEnvValue(nc) - vk, okk := e.GetEnvValue(nk) - if !okc || !okk { - return - } - cert, err := e.ReadFile(vc) - if err != nil { - global.Error(err, "read tls client cert", "file", vc) - return - } - key, err := e.ReadFile(vk) - if err != nil { - global.Error(err, "read tls client key", "file", vk) - return - } - crt, err := tls.X509KeyPair(cert, key) - if err != nil { - global.Error(err, "create tls client key pair") - return - } - fn(crt) - } -} - -func keyWithNamespace(ns, key string) string { - if ns == "" { - return key - } - return fmt.Sprintf("%s_%s", ns, key) -} - -func stringToHeader(value string) map[string]string { - headersPairs := strings.Split(value, ",") - headers := make(map[string]string) - - for _, header := range headersPairs { - nameValue := strings.SplitN(header, "=", 2) - if len(nameValue) < 2 { - global.Error(errors.New("missing '="), "parse headers", "input", nameValue) - continue - } - name, err := url.QueryUnescape(nameValue[0]) - if err != nil { - global.Error(err, "escape header key", "key", nameValue[0]) - continue - } - trimmedName := strings.TrimSpace(name) - value, err := url.QueryUnescape(nameValue[1]) - if err != nil { - global.Error(err, "escape header value", "value", nameValue[1]) - continue - } - trimmedValue := strings.TrimSpace(value) - - headers[trimmedName] = trimmedValue - } - - return headers -} - -func createCertPool(certBytes []byte) (*x509.CertPool, error) { - cp := x509.NewCertPool() - if ok := cp.AppendCertsFromPEM(certBytes); !ok { - return nil, errors.New("failed to append certificate to the cert pool") - } - return cp, nil -} diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/partialsuccess.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/partialsuccess.go deleted file mode 100644 index 9ab89b375747c..0000000000000 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/partialsuccess.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright The OpenTelemetry 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 // import "go.opentelemetry.io/otel/exporters/otlp/internal" - -import "fmt" - -// PartialSuccess represents the underlying error for all handling -// OTLP partial success messages. Use `errors.Is(err, -// PartialSuccess{})` to test whether an error passed to the OTel -// error handler belongs to this category. -type PartialSuccess struct { - ErrorMessage string - RejectedItems int64 - RejectedKind string -} - -var _ error = PartialSuccess{} - -// Error implements the error interface. -func (ps PartialSuccess) Error() string { - msg := ps.ErrorMessage - if msg == "" { - msg = "empty message" - } - return fmt.Sprintf("OTLP partial success: %s (%d %s rejected)", msg, ps.RejectedItems, ps.RejectedKind) -} - -// Is supports the errors.Is() interface. -func (ps PartialSuccess) Is(err error) bool { - _, ok := err.(PartialSuccess) - return ok -} - -// TracePartialSuccessError returns an error describing a partial success -// response for the trace signal. -func TracePartialSuccessError(itemsRejected int64, errorMessage string) error { - return PartialSuccess{ - ErrorMessage: errorMessage, - RejectedItems: itemsRejected, - RejectedKind: "spans", - } -} - -// MetricPartialSuccessError returns an error describing a partial success -// response for the metric signal. -func MetricPartialSuccessError(itemsRejected int64, errorMessage string) error { - return PartialSuccess{ - ErrorMessage: errorMessage, - RejectedItems: itemsRejected, - RejectedKind: "metric data points", - } -} diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/wrappederror.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/wrappederror.go deleted file mode 100644 index 217751da552f9..0000000000000 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/wrappederror.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright The OpenTelemetry 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 // import "go.opentelemetry.io/otel/exporters/otlp/internal" - -// ErrorKind is used to identify the kind of export error -// being wrapped. -type ErrorKind int - -const ( - // TracesExport indicates the error comes from the OTLP trace exporter. - TracesExport ErrorKind = iota -) - -// prefix returns a prefix for the Error() string. -func (k ErrorKind) prefix() string { - switch k { - case TracesExport: - return "traces export: " - default: - return "unknown: " - } -} - -// wrappedExportError wraps an OTLP exporter error with the kind of -// signal that produced it. -type wrappedExportError struct { - wrap error - kind ErrorKind -} - -// WrapTracesError wraps an error from the OTLP exporter for traces. -func WrapTracesError(err error) error { - return wrappedExportError{ - wrap: err, - kind: TracesExport, - } -} - -var _ error = wrappedExportError{} - -// Error attaches a prefix corresponding to the kind of exporter. -func (t wrappedExportError) Error() string { - return t.kind.prefix() + t.wrap.Error() -} - -// Unwrap returns the wrapped error. -func (t wrappedExportError) Unwrap() error { - return t.wrap -} diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/README.md b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/README.md index 6e9cc0366ba2b..8a40a86a246fc 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/README.md +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/README.md @@ -12,8 +12,8 @@ go get -u go.opentelemetry.io/otel/exporters/otlp/otlptrace ## Examples -- [HTTP Exporter setup and examples](./otlptracehttp/example_test.go) -- [Full example of gRPC Exporter sending telemetry to a local collector](../../../example/otel-collector) +- [Exporter setup and examples](./otlptracehttp/example_test.go) +- [Full example sending telemetry to a local collector](../../../example/otel-collector) ## [`otlptrace`](https://pkg.go.dev/go.opentelemetry.io/otel/exporters/otlp/otlptrace) @@ -38,14 +38,12 @@ override the default configuration. For more information about how each of these environment variables is interpreted, see [the OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.8.0/specification/protocol/exporter.md). -| Environment variable | Option | Default value | -| ------------------------------------------------------------------------ |------------------------------ | -------------------------------------------------------- | -| `OTEL_EXPORTER_OTLP_ENDPOINT` `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | `WithEndpoint` `WithInsecure` | `https://localhost:4317` or `https://localhost:4318`[^1] | -| `OTEL_EXPORTER_OTLP_CERTIFICATE` `OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE` | `WithTLSClientConfig` | | -| `OTEL_EXPORTER_OTLP_HEADERS` `OTEL_EXPORTER_OTLP_TRACES_HEADERS` | `WithHeaders` | | -| `OTEL_EXPORTER_OTLP_COMPRESSION` `OTEL_EXPORTER_OTLP_TRACES_COMPRESSION` | `WithCompression` | | -| `OTEL_EXPORTER_OTLP_TIMEOUT` `OTEL_EXPORTER_OTLP_TRACES_TIMEOUT` | `WithTimeout` | `10s` | - -[^1]: The gRPC client defaults to `https://localhost:4317` and the HTTP client `https://localhost:4318`. +| Environment variable | Option | Default value | +| ------------------------------------------------------------------------ |------------------------------ | ----------------------------------- | +| `OTEL_EXPORTER_OTLP_ENDPOINT` `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | `WithEndpoint` `WithInsecure` | `https://localhost:4317` | +| `OTEL_EXPORTER_OTLP_CERTIFICATE` `OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE` | `WithTLSClientConfig` | | +| `OTEL_EXPORTER_OTLP_HEADERS` `OTEL_EXPORTER_OTLP_TRACES_HEADERS` | `WithHeaders` | | +| `OTEL_EXPORTER_OTLP_COMPRESSION` `OTEL_EXPORTER_OTLP_TRACES_COMPRESSION` | `WithCompression` | | +| `OTEL_EXPORTER_OTLP_TIMEOUT` `OTEL_EXPORTER_OTLP_TRACES_TIMEOUT` | `WithTimeout` | `10s` | Configuration using options have precedence over the environment variables. diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/exporter.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/exporter.go index b65802edbbdf0..7e9bb6c47ae8f 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/exporter.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/exporter.go @@ -19,7 +19,6 @@ import ( "errors" "sync" - "go.opentelemetry.io/otel/exporters/otlp/internal" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform" tracesdk "go.opentelemetry.io/otel/sdk/trace" ) @@ -46,11 +45,7 @@ func (e *Exporter) ExportSpans(ctx context.Context, ss []tracesdk.ReadOnlySpan) return nil } - err := e.client.UploadTraces(ctx, protoSpans) - if err != nil { - return internal.WrapTracesError(err) - } - return nil + return e.client.UploadTraces(ctx, protoSpans) } // Start establishes a connection to the receiving endpoint. @@ -105,14 +100,3 @@ func NewUnstarted(client Client) *Exporter { client: client, } } - -// MarshalLog is the marshaling function used by the logging system to represent this exporter. -func (e *Exporter) MarshalLog() interface{} { - return struct { - Type string - Client Client - }{ - Type: "otlptrace", - Client: e.client, - } -} diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/envconfig.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/envconfig.go index 62c5029db2ac2..77f13a1937b63 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/envconfig.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/envconfig.go @@ -16,59 +16,66 @@ package otlpconfig // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/ import ( "crypto/tls" - "crypto/x509" + "fmt" + "io/ioutil" "net/url" "os" "path" + "strconv" "strings" "time" - "go.opentelemetry.io/otel/exporters/otlp/internal/envconfig" + "go.opentelemetry.io/otel" ) -// DefaultEnvOptionsReader is the default environments reader. -var DefaultEnvOptionsReader = envconfig.EnvOptionsReader{ - GetEnv: os.Getenv, - ReadFile: os.ReadFile, - Namespace: "OTEL_EXPORTER_OTLP", +var DefaultEnvOptionsReader = EnvOptionsReader{ + GetEnv: os.Getenv, + ReadFile: ioutil.ReadFile, } -// ApplyGRPCEnvConfigs applies the env configurations for gRPC. func ApplyGRPCEnvConfigs(cfg Config) Config { - opts := getOptionsFromEnv() + return DefaultEnvOptionsReader.ApplyGRPCEnvConfigs(cfg) +} + +func ApplyHTTPEnvConfigs(cfg Config) Config { + return DefaultEnvOptionsReader.ApplyHTTPEnvConfigs(cfg) +} + +type EnvOptionsReader struct { + GetEnv func(string) string + ReadFile func(filename string) ([]byte, error) +} + +func (e *EnvOptionsReader) ApplyHTTPEnvConfigs(cfg Config) Config { + opts := e.GetOptionsFromEnv() for _, opt := range opts { - cfg = opt.ApplyGRPCOption(cfg) + cfg = opt.ApplyHTTPOption(cfg) } return cfg } -// ApplyHTTPEnvConfigs applies the env configurations for HTTP. -func ApplyHTTPEnvConfigs(cfg Config) Config { - opts := getOptionsFromEnv() +func (e *EnvOptionsReader) ApplyGRPCEnvConfigs(cfg Config) Config { + opts := e.GetOptionsFromEnv() for _, opt := range opts { - cfg = opt.ApplyHTTPOption(cfg) + cfg = opt.ApplyGRPCOption(cfg) } return cfg } -func getOptionsFromEnv() []GenericOption { - opts := []GenericOption{} +func (e *EnvOptionsReader) GetOptionsFromEnv() []GenericOption { + var opts []GenericOption - tlsConf := &tls.Config{} - DefaultEnvOptionsReader.Apply( - envconfig.WithURL("ENDPOINT", func(u *url.URL) { - opts = append(opts, withEndpointScheme(u)) - opts = append(opts, newSplitOption(func(cfg Config) Config { - cfg.Traces.Endpoint = u.Host - // For OTLP/HTTP endpoint URLs without a per-signal - // configuration, the passed endpoint is used as a base URL - // and the signals are sent to these paths relative to that. - cfg.Traces.URLPath = path.Join(u.Path, DefaultTracesPath) - return cfg - }, withEndpointForGRPC(u))) - }), - envconfig.WithURL("TRACES_ENDPOINT", func(u *url.URL) { - opts = append(opts, withEndpointScheme(u)) + // Endpoint + if v, ok := e.getEnvValue("TRACES_ENDPOINT"); ok { + u, err := url.Parse(v) + // Ignore invalid values. + if err == nil { + // This is used to set the scheme for OTLP/HTTP. + if insecureSchema(u.Scheme) { + opts = append(opts, WithInsecure()) + } else { + opts = append(opts, WithSecure()) + } opts = append(opts, newSplitOption(func(cfg Config) Config { cfg.Traces.Endpoint = u.Host // For endpoint URLs for OTLP/HTTP per-signal variables, the @@ -81,70 +88,140 @@ func getOptionsFromEnv() []GenericOption { } cfg.Traces.URLPath = path return cfg - }, withEndpointForGRPC(u))) - }), - envconfig.WithCertPool("CERTIFICATE", func(p *x509.CertPool) { tlsConf.RootCAs = p }), - envconfig.WithCertPool("TRACES_CERTIFICATE", func(p *x509.CertPool) { tlsConf.RootCAs = p }), - envconfig.WithClientCert("CLIENT_CERTIFICATE", "CLIENT_KEY", func(c tls.Certificate) { tlsConf.Certificates = []tls.Certificate{c} }), - envconfig.WithClientCert("TRACES_CLIENT_CERTIFICATE", "TRACES_CLIENT_KEY", func(c tls.Certificate) { tlsConf.Certificates = []tls.Certificate{c} }), - withTLSConfig(tlsConf, func(c *tls.Config) { opts = append(opts, WithTLSClientConfig(c)) }), - envconfig.WithBool("INSECURE", func(b bool) { opts = append(opts, withInsecure(b)) }), - envconfig.WithBool("TRACES_INSECURE", func(b bool) { opts = append(opts, withInsecure(b)) }), - envconfig.WithHeaders("HEADERS", func(h map[string]string) { opts = append(opts, WithHeaders(h)) }), - envconfig.WithHeaders("TRACES_HEADERS", func(h map[string]string) { opts = append(opts, WithHeaders(h)) }), - WithEnvCompression("COMPRESSION", func(c Compression) { opts = append(opts, WithCompression(c)) }), - WithEnvCompression("TRACES_COMPRESSION", func(c Compression) { opts = append(opts, WithCompression(c)) }), - envconfig.WithDuration("TIMEOUT", func(d time.Duration) { opts = append(opts, WithTimeout(d)) }), - envconfig.WithDuration("TRACES_TIMEOUT", func(d time.Duration) { opts = append(opts, WithTimeout(d)) }), - ) + }, func(cfg Config) Config { + // For OTLP/gRPC endpoints, this is the target to which the + // exporter is going to send telemetry. + cfg.Traces.Endpoint = path.Join(u.Host, u.Path) + return cfg + })) + } + } else if v, ok = e.getEnvValue("ENDPOINT"); ok { + u, err := url.Parse(v) + // Ignore invalid values. + if err == nil { + // This is used to set the scheme for OTLP/HTTP. + if insecureSchema(u.Scheme) { + opts = append(opts, WithInsecure()) + } else { + opts = append(opts, WithSecure()) + } + opts = append(opts, newSplitOption(func(cfg Config) Config { + cfg.Traces.Endpoint = u.Host + // For OTLP/HTTP endpoint URLs without a per-signal + // configuration, the passed endpoint is used as a base URL + // and the signals are sent to these paths relative to that. + cfg.Traces.URLPath = path.Join(u.Path, DefaultTracesPath) + return cfg + }, func(cfg Config) Config { + // For OTLP/gRPC endpoints, this is the target to which the + // exporter is going to send telemetry. + cfg.Traces.Endpoint = path.Join(u.Host, u.Path) + return cfg + })) + } + } + + // Certificate File + if path, ok := e.getEnvValue("CERTIFICATE"); ok { + if tls, err := e.readTLSConfig(path); err == nil { + opts = append(opts, WithTLSClientConfig(tls)) + } else { + otel.Handle(fmt.Errorf("failed to configure otlp exporter certificate '%s': %w", path, err)) + } + } + if path, ok := e.getEnvValue("TRACES_CERTIFICATE"); ok { + if tls, err := e.readTLSConfig(path); err == nil { + opts = append(opts, WithTLSClientConfig(tls)) + } else { + otel.Handle(fmt.Errorf("failed to configure otlp traces exporter certificate '%s': %w", path, err)) + } + } + + // Headers + if h, ok := e.getEnvValue("HEADERS"); ok { + opts = append(opts, WithHeaders(stringToHeader(h))) + } + if h, ok := e.getEnvValue("TRACES_HEADERS"); ok { + opts = append(opts, WithHeaders(stringToHeader(h))) + } + + // Compression + if c, ok := e.getEnvValue("COMPRESSION"); ok { + opts = append(opts, WithCompression(stringToCompression(c))) + } + if c, ok := e.getEnvValue("TRACES_COMPRESSION"); ok { + opts = append(opts, WithCompression(stringToCompression(c))) + } + // Timeout + if t, ok := e.getEnvValue("TIMEOUT"); ok { + if d, err := strconv.Atoi(t); err == nil { + opts = append(opts, WithTimeout(time.Duration(d)*time.Millisecond)) + } + } + if t, ok := e.getEnvValue("TRACES_TIMEOUT"); ok { + if d, err := strconv.Atoi(t); err == nil { + opts = append(opts, WithTimeout(time.Duration(d)*time.Millisecond)) + } + } return opts } -func withEndpointScheme(u *url.URL) GenericOption { - switch strings.ToLower(u.Scheme) { +func insecureSchema(schema string) bool { + switch strings.ToLower(schema) { case "http", "unix": - return WithInsecure() + return true default: - return WithSecure() + return false } } -func withEndpointForGRPC(u *url.URL) func(cfg Config) Config { - return func(cfg Config) Config { - // For OTLP/gRPC endpoints, this is the target to which the - // exporter is going to send telemetry. - cfg.Traces.Endpoint = path.Join(u.Host, u.Path) - return cfg - } +// getEnvValue gets an OTLP environment variable value of the specified key using the GetEnv function. +// This function already prepends the OTLP prefix to all key lookup. +func (e *EnvOptionsReader) getEnvValue(key string) (string, bool) { + v := strings.TrimSpace(e.GetEnv(fmt.Sprintf("OTEL_EXPORTER_OTLP_%s", key))) + return v, v != "" } -// WithEnvCompression retrieves the specified config and passes it to ConfigFn as a Compression. -func WithEnvCompression(n string, fn func(Compression)) func(e *envconfig.EnvOptionsReader) { - return func(e *envconfig.EnvOptionsReader) { - if v, ok := e.GetEnvValue(n); ok { - cp := NoCompression - if v == "gzip" { - cp = GzipCompression - } - - fn(cp) - } +func (e *EnvOptionsReader) readTLSConfig(path string) (*tls.Config, error) { + b, err := e.ReadFile(path) + if err != nil { + return nil, err } + return CreateTLSConfig(b) } -// revive:disable-next-line:flag-parameter -func withInsecure(b bool) GenericOption { - if b { - return WithInsecure() +func stringToCompression(value string) Compression { + switch value { + case "gzip": + return GzipCompression } - return WithSecure() + + return NoCompression } -func withTLSConfig(c *tls.Config, fn func(*tls.Config)) func(e *envconfig.EnvOptionsReader) { - return func(e *envconfig.EnvOptionsReader) { - if c.RootCAs != nil || len(c.Certificates) > 0 { - fn(c) +func stringToHeader(value string) map[string]string { + headersPairs := strings.Split(value, ",") + headers := make(map[string]string) + + for _, header := range headersPairs { + nameValue := strings.SplitN(header, "=", 2) + if len(nameValue) < 2 { + continue + } + name, err := url.QueryUnescape(nameValue[0]) + if err != nil { + continue } + trimmedName := strings.TrimSpace(name) + value, err := url.QueryUnescape(nameValue[1]) + if err != nil { + continue + } + trimmedValue := strings.TrimSpace(value) + + headers[trimmedName] = trimmedValue } + + return headers } diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/options.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/options.go index c48ffd530814d..e6fb14e00e8de 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/options.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/options.go @@ -25,7 +25,6 @@ import ( "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/encoding/gzip" - "go.opentelemetry.io/otel/exporters/otlp/internal" "go.opentelemetry.io/otel/exporters/otlp/internal/retry" ) @@ -66,39 +65,24 @@ type ( } ) -// NewHTTPConfig returns a new Config with all settings applied from opts and -// any unset setting using the default HTTP config values. -func NewHTTPConfig(opts ...HTTPOption) Config { - cfg := Config{ +func NewDefaultConfig() Config { + c := Config{ Traces: SignalConfig{ - Endpoint: fmt.Sprintf("%s:%d", DefaultCollectorHost, DefaultCollectorHTTPPort), + Endpoint: fmt.Sprintf("%s:%d", DefaultCollectorHost, DefaultCollectorPort), URLPath: DefaultTracesPath, Compression: NoCompression, Timeout: DefaultTimeout, }, RetryConfig: retry.DefaultConfig, } - cfg = ApplyHTTPEnvConfigs(cfg) - for _, opt := range opts { - cfg = opt.ApplyHTTPOption(cfg) - } - cfg.Traces.URLPath = internal.CleanPath(cfg.Traces.URLPath, DefaultTracesPath) - return cfg + + return c } // NewGRPCConfig returns a new Config with all settings applied from opts and // any unset setting using the default gRPC config values. func NewGRPCConfig(opts ...GRPCOption) Config { - cfg := Config{ - Traces: SignalConfig{ - Endpoint: fmt.Sprintf("%s:%d", DefaultCollectorHost, DefaultCollectorGRPCPort), - URLPath: DefaultTracesPath, - Compression: NoCompression, - Timeout: DefaultTimeout, - }, - RetryConfig: retry.DefaultConfig, - DialOptions: []grpc.DialOption{grpc.WithUserAgent(internal.GetUserAgentHeader())}, - } + cfg := NewDefaultConfig() cfg = ApplyGRPCEnvConfigs(cfg) for _, opt := range opts { cfg = opt.ApplyGRPCOption(cfg) diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/optiontypes.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/optiontypes.go index c2d6c03615262..f69e31095d21b 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/optiontypes.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig/optiontypes.go @@ -15,10 +15,9 @@ package otlpconfig // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig" const ( - // DefaultCollectorGRPCPort is the default gRPC port of the collector. - DefaultCollectorGRPCPort uint16 = 4317 - // DefaultCollectorHTTPPort is the default HTTP port of the collector. - DefaultCollectorHTTPPort uint16 = 4318 + // DefaultCollectorPort is the port the Exporter will attempt connect to + // if no collector port is provided. + DefaultCollectorPort uint16 = 4317 // DefaultCollectorHost is the host address the Exporter will attempt // connect to if no collector address is provided. DefaultCollectorHost string = "localhost" @@ -37,7 +36,7 @@ const ( GzipCompression ) -// Marshaler describes the kind of message format sent to the collector. +// Marshaler describes the kind of message format sent to the collector type Marshaler int const ( diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/attribute.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/attribute.go index ec74f1aad7581..d9086a390de05 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/attribute.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/attribute.go @@ -48,8 +48,8 @@ func Iterator(iter attribute.Iterator) []*commonpb.KeyValue { } // ResourceAttributes transforms a Resource OTLP key-values. -func ResourceAttributes(res *resource.Resource) []*commonpb.KeyValue { - return Iterator(res.Iter()) +func ResourceAttributes(resource *resource.Resource) []*commonpb.KeyValue { + return Iterator(resource.Iter()) } // KeyValue transforms an attribute KeyValue into an OTLP key-value. diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go index 7aaec38d22ae9..6246b17f578e7 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/instrumentation.go @@ -19,11 +19,11 @@ import ( commonpb "go.opentelemetry.io/proto/otlp/common/v1" ) -func InstrumentationScope(il instrumentation.Scope) *commonpb.InstrumentationScope { - if il == (instrumentation.Scope{}) { +func InstrumentationLibrary(il instrumentation.Library) *commonpb.InstrumentationLibrary { + if il == (instrumentation.Library{}) { return nil } - return &commonpb.InstrumentationScope{ + return &commonpb.InstrumentationLibrary{ Name: il.Name, Version: il.Version, } diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/span.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/span.go index b83cbd7247807..2f0f5eacb776d 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/span.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform/span.go @@ -23,6 +23,10 @@ import ( tracepb "go.opentelemetry.io/proto/otlp/trace/v1" ) +const ( + maxEventsPerSpan = 128 +) + // Spans transforms a slice of OpenTelemetry spans into a slice of OTLP // ResourceSpans. func Spans(sdl []tracesdk.ReadOnlySpan) []*tracepb.ResourceSpans { @@ -32,11 +36,11 @@ func Spans(sdl []tracesdk.ReadOnlySpan) []*tracepb.ResourceSpans { rsm := make(map[attribute.Distinct]*tracepb.ResourceSpans) - type key struct { + type ilsKey struct { r attribute.Distinct - is instrumentation.Scope + il instrumentation.Library } - ssm := make(map[key]*tracepb.ScopeSpans) + ilsm := make(map[ilsKey]*tracepb.InstrumentationLibrarySpans) var resources int for _, sd := range sdl { @@ -45,30 +49,30 @@ func Spans(sdl []tracesdk.ReadOnlySpan) []*tracepb.ResourceSpans { } rKey := sd.Resource().Equivalent() - k := key{ + iKey := ilsKey{ r: rKey, - is: sd.InstrumentationScope(), + il: sd.InstrumentationLibrary(), } - scopeSpan, iOk := ssm[k] + ils, iOk := ilsm[iKey] if !iOk { - // Either the resource or instrumentation scope were unknown. - scopeSpan = &tracepb.ScopeSpans{ - Scope: InstrumentationScope(sd.InstrumentationScope()), - Spans: []*tracepb.Span{}, - SchemaUrl: sd.InstrumentationScope().SchemaURL, + // Either the resource or instrumentation library were unknown. + ils = &tracepb.InstrumentationLibrarySpans{ + InstrumentationLibrary: InstrumentationLibrary(sd.InstrumentationLibrary()), + Spans: []*tracepb.Span{}, + SchemaUrl: sd.InstrumentationLibrary().SchemaURL, } } - scopeSpan.Spans = append(scopeSpan.Spans, span(sd)) - ssm[k] = scopeSpan + ils.Spans = append(ils.Spans, span(sd)) + ilsm[iKey] = ils rs, rOk := rsm[rKey] if !rOk { resources++ // The resource was unknown. rs = &tracepb.ResourceSpans{ - Resource: Resource(sd.Resource()), - ScopeSpans: []*tracepb.ScopeSpans{scopeSpan}, - SchemaUrl: sd.Resource().SchemaURL(), + Resource: Resource(sd.Resource()), + InstrumentationLibrarySpans: []*tracepb.InstrumentationLibrarySpans{ils}, + SchemaUrl: sd.Resource().SchemaURL(), } rsm[rKey] = rs continue @@ -78,9 +82,9 @@ func Spans(sdl []tracesdk.ReadOnlySpan) []*tracepb.ResourceSpans { // library lookup was unknown because if so we need to add it to the // ResourceSpans. Otherwise, the instrumentation library has already // been seen and the append we did above will be included it in the - // ScopeSpans reference. + // InstrumentationLibrarySpans reference. if !iOk { - rs.ScopeSpans = append(rs.ScopeSpans, scopeSpan) + rs.InstrumentationLibrarySpans = append(rs.InstrumentationLibrarySpans, ils) } } @@ -158,10 +162,9 @@ func links(links []tracesdk.Link) []*tracepb.Span_Link { sid := otLink.SpanContext.SpanID() sl = append(sl, &tracepb.Span_Link{ - TraceId: tid[:], - SpanId: sid[:], - Attributes: KeyValues(otLink.Attributes), - DroppedAttributesCount: uint32(otLink.DroppedAttributeCount), + TraceId: tid[:], + SpanId: sid[:], + Attributes: KeyValues(otLink.Attributes), }) } return sl @@ -173,16 +176,29 @@ func spanEvents(es []tracesdk.Event) []*tracepb.Span_Event { return nil } - events := make([]*tracepb.Span_Event, len(es)) + evCount := len(es) + if evCount > maxEventsPerSpan { + evCount = maxEventsPerSpan + } + events := make([]*tracepb.Span_Event, 0, evCount) + nEvents := 0 + // Transform message events - for i := 0; i < len(es); i++ { - events[i] = &tracepb.Span_Event{ - Name: es[i].Name, - TimeUnixNano: uint64(es[i].Time.UnixNano()), - Attributes: KeyValues(es[i].Attributes), - DroppedAttributesCount: uint32(es[i].DroppedAttributeCount), + for _, e := range es { + if nEvents >= maxEventsPerSpan { + break } + nEvents++ + events = append(events, + &tracepb.Span_Event{ + Name: e.Name, + TimeUnixNano: uint64(e.Time.UnixNano()), + Attributes: KeyValues(e.Attributes), + // TODO (rghetia) : Add Drop Counts when supported. + }, + ) } + return events } diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go index fe23f8e3766f4..d709ffa96e19b 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/client.go @@ -26,8 +26,6 @@ import ( "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/exporters/otlp/internal" "go.opentelemetry.io/otel/exporters/otlp/internal/retry" "go.opentelemetry.io/otel/exporters/otlp/otlptrace" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig" @@ -198,17 +196,9 @@ func (c *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc defer cancel() return c.requestFunc(ctx, func(iCtx context.Context) error { - resp, err := c.tsc.Export(iCtx, &coltracepb.ExportTraceServiceRequest{ + _, err := c.tsc.Export(iCtx, &coltracepb.ExportTraceServiceRequest{ ResourceSpans: protoSpans, }) - if resp != nil && resp.PartialSuccess != nil { - msg := resp.PartialSuccess.GetErrorMessage() - n := resp.PartialSuccess.GetRejectedSpans() - if n != 0 || msg != "" { - err := internal.TracePartialSuccessError(n, msg) - otel.Handle(err) - } - } // nil is converted to OK. if status.Code(err) == codes.OK { // Success. @@ -275,22 +265,11 @@ func retryable(err error) (bool, time.Duration) { // throttleDelay returns a duration to wait for if an explicit throttle time // is included in the response status. -func throttleDelay(s *status.Status) time.Duration { - for _, detail := range s.Details() { +func throttleDelay(status *status.Status) time.Duration { + for _, detail := range status.Details() { if t, ok := detail.(*errdetails.RetryInfo); ok { return t.RetryDelay.AsDuration() } } return 0 } - -// MarshalLog is the marshaling function used by the logging system to represent this Client. -func (c *client) MarshalLog() interface{} { - return struct { - Type string - Endpoint string - }{ - Type: "otlphttpgrpc", - Endpoint: c.endpoint, - } -} diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/options.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/options.go index 3d09ce590d0e7..e2e5bd696f63e 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/options.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/options.go @@ -84,7 +84,8 @@ func WithReconnectionPeriod(rp time.Duration) Option { } func compressorToCompression(compressor string) otlpconfig.Compression { - if compressor == "gzip" { + switch compressor { + case "gzip": return otlpconfig.GzipCompression } diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/client.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/client.go index 9fbe861717d44..81487f9b6f99f 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/client.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/client.go @@ -20,17 +20,18 @@ import ( "context" "fmt" "io" + "io/ioutil" "net" "net/http" "net/url" + "path" "strconv" + "strings" "sync" "time" "google.golang.org/protobuf/proto" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/exporters/otlp/internal" "go.opentelemetry.io/otel/exporters/otlp/internal/retry" "go.opentelemetry.io/otel/exporters/otlp/otlptrace" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig" @@ -42,7 +43,7 @@ const contentTypeProto = "application/x-protobuf" var gzPool = sync.Pool{ New: func() interface{} { - w := gzip.NewWriter(io.Discard) + w := gzip.NewWriter(ioutil.Discard) return w }, } @@ -78,7 +79,26 @@ var _ otlptrace.Client = (*client)(nil) // NewClient creates a new HTTP trace client. func NewClient(opts ...Option) otlptrace.Client { - cfg := otlpconfig.NewHTTPConfig(asHTTPOptions(opts)...) + cfg := otlpconfig.NewDefaultConfig() + cfg = otlpconfig.ApplyHTTPEnvConfigs(cfg) + for _, opt := range opts { + cfg = opt.applyHTTPOption(cfg) + } + + for pathPtr, defaultPath := range map[*string]string{ + &cfg.Traces.URLPath: otlpconfig.DefaultTracesPath, + } { + tmp := strings.TrimSpace(*pathPtr) + if tmp == "" { + tmp = defaultPath + } else { + tmp = path.Clean(tmp) + if !path.IsAbs(tmp) { + tmp = fmt.Sprintf("/%s", tmp) + } + } + *pathPtr = tmp + } httpClient := &http.Client{ Transport: ourTransport, @@ -101,7 +121,7 @@ func NewClient(opts ...Option) otlptrace.Client { } } -// Start does nothing in a HTTP client. +// Start does nothing in a HTTP client func (d *client) Start(ctx context.Context) error { // nothing to do select { @@ -156,49 +176,28 @@ func (d *client) UploadTraces(ctx context.Context, protoSpans []*tracepb.Resourc return err } - if resp != nil && resp.Body != nil { - defer func() { - if err := resp.Body.Close(); err != nil { - otel.Handle(err) - } - }() - } - + var rErr error switch resp.StatusCode { case http.StatusOK: // Success, do not retry. - // Read the partial success message, if any. - var respData bytes.Buffer - if _, err := io.Copy(&respData, resp.Body); err != nil { + case http.StatusTooManyRequests, + http.StatusServiceUnavailable: + // Retry-able failure. + rErr = newResponseError(resp.Header) + + // Going to retry, drain the body to reuse the connection. + if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { + _ = resp.Body.Close() return err } - - if respData.Len() != 0 { - var respProto coltracepb.ExportTraceServiceResponse - if err := proto.Unmarshal(respData.Bytes(), &respProto); err != nil { - return err - } - - if respProto.PartialSuccess != nil { - msg := respProto.PartialSuccess.GetErrorMessage() - n := respProto.PartialSuccess.GetRejectedSpans() - if n != 0 || msg != "" { - err := internal.TracePartialSuccessError(n, msg) - otel.Handle(err) - } - } - } - return nil - - case http.StatusTooManyRequests, http.StatusServiceUnavailable: - // Retry-able failures. Drain the body to reuse the connection. - if _, err := io.Copy(io.Discard, resp.Body); err != nil { - otel.Handle(err) - } - return newResponseError(resp.Header) default: - return fmt.Errorf("failed to send to %s: %s", request.URL, resp.Status) + rErr = fmt.Errorf("failed to send %s to %s: %s", d.name, request.URL, resp.Status) + } + + if err := resp.Body.Close(); err != nil { + return err } + return rErr }) } @@ -209,8 +208,6 @@ func (d *client) newRequest(body []byte) (request, error) { return request{Request: r}, err } - r.Header.Set("User-Agent", internal.GetUserAgentHeader()) - for k, v := range d.cfg.Headers { r.Header.Set(k, v) } @@ -246,23 +243,10 @@ func (d *client) newRequest(body []byte) (request, error) { return req, nil } -// MarshalLog is the marshaling function used by the logging system to represent this Client. -func (d *client) MarshalLog() interface{} { - return struct { - Type string - Endpoint string - Insecure bool - }{ - Type: "otlphttphttp", - Endpoint: d.cfg.Endpoint, - Insecure: d.cfg.Insecure, - } -} - // bodyReader returns a closure returning a new reader for buf. func bodyReader(buf []byte) func() io.ReadCloser { return func() io.ReadCloser { - return io.NopCloser(bytes.NewReader(buf)) + return ioutil.NopCloser(bytes.NewReader(buf)) } } diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/options.go b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/options.go index 4257ce3473f86..e550cfb5d518e 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/options.go +++ b/vendor/go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/options.go @@ -40,14 +40,6 @@ type Option interface { applyHTTPOption(otlpconfig.Config) otlpconfig.Config } -func asHTTPOptions(opts []Option) []otlpconfig.HTTPOption { - converted := make([]otlpconfig.HTTPOption, len(opts)) - for i, o := range opts { - converted[i] = otlpconfig.NewHTTPOption(o.applyHTTPOption) - } - return converted -} - // RetryConfig defines configuration for retrying batches in case of export // failure using an exponential backoff. type RetryConfig retry.Config @@ -63,7 +55,7 @@ func (w wrappedOption) applyHTTPOption(cfg otlpconfig.Config) otlpconfig.Config // WithEndpoint allows one to set the address of the collector // endpoint that the driver will use to send spans. If // unset, it will instead try to use -// the default endpoint (localhost:4318). Note that the endpoint +// the default endpoint (localhost:4317). Note that the endpoint // must not contain any URL path. func WithEndpoint(endpoint string) Option { return wrappedOption{otlpconfig.WithEndpoint(endpoint)} diff --git a/vendor/go.opentelemetry.io/otel/internal/metric/LICENSE b/vendor/go.opentelemetry.io/otel/internal/metric/LICENSE new file mode 100644 index 0000000000000..261eeb9e9f8b2 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/internal/metric/LICENSE @@ -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. diff --git a/vendor/go.opentelemetry.io/otel/internal/metric/global/meter.go b/vendor/go.opentelemetry.io/otel/internal/metric/global/meter.go new file mode 100644 index 0000000000000..77781ead118cf --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/internal/metric/global/meter.go @@ -0,0 +1,287 @@ +// Copyright The OpenTelemetry 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 global // import "go.opentelemetry.io/otel/internal/metric/global" + +import ( + "context" + "sync" + "sync/atomic" + "unsafe" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/internal/metric/registry" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" + "go.opentelemetry.io/otel/metric/sdkapi" +) + +// This file contains the forwarding implementation of MeterProvider used as +// the default global instance. Metric events using instruments provided by +// this implementation are no-ops until the first Meter implementation is set +// as the global provider. +// +// The implementation here uses Mutexes to maintain a list of active Meters in +// the MeterProvider and Instruments in each Meter, under the assumption that +// these interfaces are not performance-critical. +// +// We have the invariant that setDelegate() will be called before a new +// MeterProvider implementation is registered as the global provider. Mutexes +// in the MeterProvider and Meters ensure that each instrument has a delegate +// before the global provider is set. +// +// Metric uniqueness checking is implemented by calling the exported +// methods of the api/metric/registry package. + +type meterKey struct { + InstrumentationName string + InstrumentationVersion string + SchemaURL string +} + +type meterProvider struct { + delegate metric.MeterProvider + + // lock protects `delegate` and `meters`. + lock sync.Mutex + + // meters maintains a unique entry for every named Meter + // that has been registered through the global instance. + meters map[meterKey]*meterEntry +} + +type meterImpl struct { + delegate unsafe.Pointer // (*metric.MeterImpl) + + lock sync.Mutex + syncInsts []*syncImpl + asyncInsts []*asyncImpl +} + +type meterEntry struct { + unique sdkapi.MeterImpl + impl meterImpl +} + +type instrument struct { + descriptor sdkapi.Descriptor +} + +type syncImpl struct { + delegate unsafe.Pointer // (*sdkapi.SyncImpl) + + instrument +} + +type asyncImpl struct { + delegate unsafe.Pointer // (*sdkapi.AsyncImpl) + + instrument + + runner sdkapi.AsyncRunner +} + +var _ metric.MeterProvider = &meterProvider{} +var _ sdkapi.MeterImpl = &meterImpl{} +var _ sdkapi.InstrumentImpl = &syncImpl{} +var _ sdkapi.AsyncImpl = &asyncImpl{} + +func (inst *instrument) Descriptor() sdkapi.Descriptor { + return inst.descriptor +} + +// MeterProvider interface and delegation + +func newMeterProvider() *meterProvider { + return &meterProvider{ + meters: map[meterKey]*meterEntry{}, + } +} + +func (p *meterProvider) setDelegate(provider metric.MeterProvider) { + p.lock.Lock() + defer p.lock.Unlock() + + p.delegate = provider + for key, entry := range p.meters { + entry.impl.setDelegate(key, provider) + } + p.meters = nil +} + +func (p *meterProvider) Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter { + p.lock.Lock() + defer p.lock.Unlock() + + if p.delegate != nil { + return p.delegate.Meter(instrumentationName, opts...) + } + + cfg := metric.NewMeterConfig(opts...) + key := meterKey{ + InstrumentationName: instrumentationName, + InstrumentationVersion: cfg.InstrumentationVersion(), + SchemaURL: cfg.SchemaURL(), + } + entry, ok := p.meters[key] + if !ok { + entry = &meterEntry{} + // Note: This code implements its own MeterProvider + // name-uniqueness logic because there is + // synchronization required at the moment of + // delegation. We use the same instrument-uniqueness + // checking the real SDK uses here: + entry.unique = registry.NewUniqueInstrumentMeterImpl(&entry.impl) + p.meters[key] = entry + } + return metric.WrapMeterImpl(entry.unique) +} + +// Meter interface and delegation + +func (m *meterImpl) setDelegate(key meterKey, provider metric.MeterProvider) { + m.lock.Lock() + defer m.lock.Unlock() + + d := new(sdkapi.MeterImpl) + *d = provider.Meter( + key.InstrumentationName, + metric.WithInstrumentationVersion(key.InstrumentationVersion), + metric.WithSchemaURL(key.SchemaURL), + ).MeterImpl() + m.delegate = unsafe.Pointer(d) + + for _, inst := range m.syncInsts { + inst.setDelegate(*d) + } + m.syncInsts = nil + for _, obs := range m.asyncInsts { + obs.setDelegate(*d) + } + m.asyncInsts = nil +} + +func (m *meterImpl) NewSyncInstrument(desc sdkapi.Descriptor) (sdkapi.SyncImpl, error) { + m.lock.Lock() + defer m.lock.Unlock() + + if meterPtr := (*sdkapi.MeterImpl)(atomic.LoadPointer(&m.delegate)); meterPtr != nil { + return (*meterPtr).NewSyncInstrument(desc) + } + + inst := &syncImpl{ + instrument: instrument{ + descriptor: desc, + }, + } + m.syncInsts = append(m.syncInsts, inst) + return inst, nil +} + +// Synchronous delegation + +func (inst *syncImpl) setDelegate(d sdkapi.MeterImpl) { + implPtr := new(sdkapi.SyncImpl) + + var err error + *implPtr, err = d.NewSyncInstrument(inst.descriptor) + + if err != nil { + // TODO: There is no standard way to deliver this error to the user. + // See https://github.com/open-telemetry/opentelemetry-go/issues/514 + // Note that the default SDK will not generate any errors yet, this is + // only for added safety. + panic(err) + } + + atomic.StorePointer(&inst.delegate, unsafe.Pointer(implPtr)) +} + +func (inst *syncImpl) Implementation() interface{} { + if implPtr := (*sdkapi.SyncImpl)(atomic.LoadPointer(&inst.delegate)); implPtr != nil { + return (*implPtr).Implementation() + } + return inst +} + +// Async delegation + +func (m *meterImpl) NewAsyncInstrument( + desc sdkapi.Descriptor, + runner sdkapi.AsyncRunner, +) (sdkapi.AsyncImpl, error) { + + m.lock.Lock() + defer m.lock.Unlock() + + if meterPtr := (*sdkapi.MeterImpl)(atomic.LoadPointer(&m.delegate)); meterPtr != nil { + return (*meterPtr).NewAsyncInstrument(desc, runner) + } + + inst := &asyncImpl{ + instrument: instrument{ + descriptor: desc, + }, + runner: runner, + } + m.asyncInsts = append(m.asyncInsts, inst) + return inst, nil +} + +func (obs *asyncImpl) Implementation() interface{} { + if implPtr := (*sdkapi.AsyncImpl)(atomic.LoadPointer(&obs.delegate)); implPtr != nil { + return (*implPtr).Implementation() + } + return obs +} + +func (obs *asyncImpl) setDelegate(d sdkapi.MeterImpl) { + implPtr := new(sdkapi.AsyncImpl) + + var err error + *implPtr, err = d.NewAsyncInstrument(obs.descriptor, obs.runner) + + if err != nil { + // TODO: There is no standard way to deliver this error to the user. + // See https://github.com/open-telemetry/opentelemetry-go/issues/514 + // Note that the default SDK will not generate any errors yet, this is + // only for added safety. + panic(err) + } + + atomic.StorePointer(&obs.delegate, unsafe.Pointer(implPtr)) +} + +// Metric updates + +func (m *meterImpl) RecordBatch(ctx context.Context, labels []attribute.KeyValue, measurements ...sdkapi.Measurement) { + if delegatePtr := (*sdkapi.MeterImpl)(atomic.LoadPointer(&m.delegate)); delegatePtr != nil { + (*delegatePtr).RecordBatch(ctx, labels, measurements...) + } +} + +func (inst *syncImpl) RecordOne(ctx context.Context, number number.Number, labels []attribute.KeyValue) { + if instPtr := (*sdkapi.SyncImpl)(atomic.LoadPointer(&inst.delegate)); instPtr != nil { + (*instPtr).RecordOne(ctx, number, labels) + } +} + +func AtomicFieldOffsets() map[string]uintptr { + return map[string]uintptr{ + "meterProvider.delegate": unsafe.Offsetof(meterProvider{}.delegate), + "meterImpl.delegate": unsafe.Offsetof(meterImpl{}.delegate), + "syncImpl.delegate": unsafe.Offsetof(syncImpl{}.delegate), + "asyncImpl.delegate": unsafe.Offsetof(asyncImpl{}.delegate), + } +} diff --git a/vendor/go.opentelemetry.io/otel/metric/internal/global/state.go b/vendor/go.opentelemetry.io/otel/internal/metric/global/metric.go similarity index 54% rename from vendor/go.opentelemetry.io/otel/metric/internal/global/state.go rename to vendor/go.opentelemetry.io/otel/internal/metric/global/metric.go index 47c0d787d8a6a..896c6dd1c30bb 100644 --- a/vendor/go.opentelemetry.io/otel/metric/internal/global/state.go +++ b/vendor/go.opentelemetry.io/otel/internal/metric/global/metric.go @@ -4,7 +4,7 @@ // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // -// htmp://www.apache.org/licenses/LICENSE-2.0 +// 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, @@ -12,57 +12,55 @@ // See the License for the specific language governing permissions and // limitations under the License. -package global // import "go.opentelemetry.io/otel/metric/internal/global" +package global // import "go.opentelemetry.io/otel/internal/metric/global" import ( - "errors" "sync" "sync/atomic" - "go.opentelemetry.io/otel/internal/global" "go.opentelemetry.io/otel/metric" ) +type meterProviderHolder struct { + mp metric.MeterProvider +} + var ( - globalMeterProvider = defaultMeterProvider() + globalMeter = defaultMeterValue() delegateMeterOnce sync.Once ) -type meterProviderHolder struct { - mp metric.MeterProvider -} - // MeterProvider is the internal implementation for global.MeterProvider. func MeterProvider() metric.MeterProvider { - return globalMeterProvider.Load().(meterProviderHolder).mp + return globalMeter.Load().(meterProviderHolder).mp } // SetMeterProvider is the internal implementation for global.SetMeterProvider. func SetMeterProvider(mp metric.MeterProvider) { - current := MeterProvider() - if _, cOk := current.(*meterProvider); cOk { - if _, mpOk := mp.(*meterProvider); mpOk && current == mp { - // Do not assign the default delegating MeterProvider to delegate - // to itself. - global.Error( - errors.New("no delegate configured in meter provider"), - "Setting meter provider to it's current value. No delegate will be configured", - ) - return - } - } - delegateMeterOnce.Do(func() { - if def, ok := current.(*meterProvider); ok { + current := MeterProvider() + + if current == mp { + // Setting the provider to the prior default is nonsense, panic. + // Panic is acceptable because we are likely still early in the + // process lifetime. + panic("invalid MeterProvider, the global instance cannot be reinstalled") + } else if def, ok := current.(*meterProvider); ok { def.setDelegate(mp) } }) - globalMeterProvider.Store(meterProviderHolder{mp: mp}) + globalMeter.Store(meterProviderHolder{mp: mp}) } -func defaultMeterProvider() *atomic.Value { +func defaultMeterValue() *atomic.Value { v := &atomic.Value{} - v.Store(meterProviderHolder{mp: &meterProvider{}}) + v.Store(meterProviderHolder{mp: newMeterProvider()}) return v } + +// ResetForTest restores the initial global state, for testing purposes. +func ResetForTest() { + globalMeter = defaultMeterValue() + delegateMeterOnce = sync.Once{} +} diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/config.go b/vendor/go.opentelemetry.io/otel/internal/metric/registry/doc.go similarity index 50% rename from vendor/go.opentelemetry.io/otel/exporters/otlp/internal/config.go rename to vendor/go.opentelemetry.io/otel/internal/metric/registry/doc.go index b3fd45d9d31b7..2f17562f0eb54 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/config.go +++ b/vendor/go.opentelemetry.io/otel/internal/metric/registry/doc.go @@ -12,23 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package internal contains common functionality for all OTLP exporters. -package internal // import "go.opentelemetry.io/otel/exporters/otlp/internal" +/* +Package registry provides a non-standalone implementation of +MeterProvider that adds uniqueness checking for instrument descriptors +on top of other MeterProvider it wraps. -import ( - "fmt" - "path" - "strings" -) - -// CleanPath returns a path with all spaces trimmed and all redundancies removed. If urlPath is empty or cleaning it results in an empty string, defaultPath is returned instead. -func CleanPath(urlPath string, defaultPath string) string { - tmp := path.Clean(strings.TrimSpace(urlPath)) - if tmp == "." { - return defaultPath - } - if !path.IsAbs(tmp) { - tmp = fmt.Sprintf("/%s", tmp) - } - return tmp -} +This package is currently in a pre-GA phase. Backwards incompatible changes +may be introduced in subsequent minor version releases as we work to track the +evolving OpenTelemetry specification and user feedback. +*/ +package registry // import "go.opentelemetry.io/otel/internal/metric/registry" diff --git a/vendor/go.opentelemetry.io/otel/internal/metric/registry/registry.go b/vendor/go.opentelemetry.io/otel/internal/metric/registry/registry.go new file mode 100644 index 0000000000000..c929bf45c85ce --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/internal/metric/registry/registry.go @@ -0,0 +1,139 @@ +// Copyright The OpenTelemetry 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 registry // import "go.opentelemetry.io/otel/internal/metric/registry" + +import ( + "context" + "fmt" + "sync" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric/sdkapi" +) + +// UniqueInstrumentMeterImpl implements the metric.MeterImpl interface, adding +// uniqueness checking for instrument descriptors. +type UniqueInstrumentMeterImpl struct { + lock sync.Mutex + impl sdkapi.MeterImpl + state map[string]sdkapi.InstrumentImpl +} + +var _ sdkapi.MeterImpl = (*UniqueInstrumentMeterImpl)(nil) + +// ErrMetricKindMismatch is the standard error for mismatched metric +// instrument definitions. +var ErrMetricKindMismatch = fmt.Errorf( + "a metric was already registered by this name with another kind or number type") + +// NewUniqueInstrumentMeterImpl returns a wrapped metric.MeterImpl +// with the addition of instrument name uniqueness checking. +func NewUniqueInstrumentMeterImpl(impl sdkapi.MeterImpl) *UniqueInstrumentMeterImpl { + return &UniqueInstrumentMeterImpl{ + impl: impl, + state: map[string]sdkapi.InstrumentImpl{}, + } +} + +// MeterImpl gives the caller access to the underlying MeterImpl +// used by this UniqueInstrumentMeterImpl. +func (u *UniqueInstrumentMeterImpl) MeterImpl() sdkapi.MeterImpl { + return u.impl +} + +// RecordBatch implements sdkapi.MeterImpl. +func (u *UniqueInstrumentMeterImpl) RecordBatch(ctx context.Context, labels []attribute.KeyValue, ms ...sdkapi.Measurement) { + u.impl.RecordBatch(ctx, labels, ms...) +} + +// NewMetricKindMismatchError formats an error that describes a +// mismatched metric instrument definition. +func NewMetricKindMismatchError(desc sdkapi.Descriptor) error { + return fmt.Errorf("metric %s registered as %s %s: %w", + desc.Name(), + desc.NumberKind(), + desc.InstrumentKind(), + ErrMetricKindMismatch) +} + +// Compatible determines whether two sdkapi.Descriptors are considered +// the same for the purpose of uniqueness checking. +func Compatible(candidate, existing sdkapi.Descriptor) bool { + return candidate.InstrumentKind() == existing.InstrumentKind() && + candidate.NumberKind() == existing.NumberKind() +} + +// checkUniqueness returns an ErrMetricKindMismatch error if there is +// a conflict between a descriptor that was already registered and the +// `descriptor` argument. If there is an existing compatible +// registration, this returns the already-registered instrument. If +// there is no conflict and no prior registration, returns (nil, nil). +func (u *UniqueInstrumentMeterImpl) checkUniqueness(descriptor sdkapi.Descriptor) (sdkapi.InstrumentImpl, error) { + impl, ok := u.state[descriptor.Name()] + if !ok { + return nil, nil + } + + if !Compatible(descriptor, impl.Descriptor()) { + return nil, NewMetricKindMismatchError(impl.Descriptor()) + } + + return impl, nil +} + +// NewSyncInstrument implements sdkapi.MeterImpl. +func (u *UniqueInstrumentMeterImpl) NewSyncInstrument(descriptor sdkapi.Descriptor) (sdkapi.SyncImpl, error) { + u.lock.Lock() + defer u.lock.Unlock() + + impl, err := u.checkUniqueness(descriptor) + + if err != nil { + return nil, err + } else if impl != nil { + return impl.(sdkapi.SyncImpl), nil + } + + syncInst, err := u.impl.NewSyncInstrument(descriptor) + if err != nil { + return nil, err + } + u.state[descriptor.Name()] = syncInst + return syncInst, nil +} + +// NewAsyncInstrument implements sdkapi.MeterImpl. +func (u *UniqueInstrumentMeterImpl) NewAsyncInstrument( + descriptor sdkapi.Descriptor, + runner sdkapi.AsyncRunner, +) (sdkapi.AsyncImpl, error) { + u.lock.Lock() + defer u.lock.Unlock() + + impl, err := u.checkUniqueness(descriptor) + + if err != nil { + return nil, err + } else if impl != nil { + return impl.(sdkapi.AsyncImpl), nil + } + + asyncInst, err := u.impl.NewAsyncInstrument(descriptor, runner) + if err != nil { + return nil, err + } + u.state[descriptor.Name()] = asyncInst + return asyncInst, nil +} diff --git a/vendor/go.opentelemetry.io/otel/metric/config.go b/vendor/go.opentelemetry.io/otel/metric/config.go index 778ad2d748b56..3f722344fa7ce 100644 --- a/vendor/go.opentelemetry.io/otel/metric/config.go +++ b/vendor/go.opentelemetry.io/otel/metric/config.go @@ -14,38 +14,84 @@ package metric // import "go.opentelemetry.io/otel/metric" -import "go.opentelemetry.io/otel/attribute" +import ( + "go.opentelemetry.io/otel/metric/unit" +) + +// InstrumentConfig contains options for metric instrument descriptors. +type InstrumentConfig struct { + description string + unit unit.Unit +} + +// Description describes the instrument in human-readable terms. +func (cfg *InstrumentConfig) Description() string { + return cfg.description +} + +// Unit describes the measurement unit for a instrument. +func (cfg *InstrumentConfig) Unit() unit.Unit { + return cfg.unit +} + +// InstrumentOption is an interface for applying metric instrument options. +type InstrumentOption interface { + // ApplyMeter is used to set a InstrumentOption value of a + // InstrumentConfig. + applyInstrument(InstrumentConfig) InstrumentConfig +} + +// NewInstrumentConfig creates a new InstrumentConfig +// and applies all the given options. +func NewInstrumentConfig(opts ...InstrumentOption) InstrumentConfig { + var config InstrumentConfig + for _, o := range opts { + config = o.applyInstrument(config) + } + return config +} + +type instrumentOptionFunc func(InstrumentConfig) InstrumentConfig + +func (fn instrumentOptionFunc) applyInstrument(cfg InstrumentConfig) InstrumentConfig { + return fn(cfg) +} + +// WithDescription applies provided description. +func WithDescription(desc string) InstrumentOption { + return instrumentOptionFunc(func(cfg InstrumentConfig) InstrumentConfig { + cfg.description = desc + return cfg + }) +} + +// WithUnit applies provided unit. +func WithUnit(unit unit.Unit) InstrumentOption { + return instrumentOptionFunc(func(cfg InstrumentConfig) InstrumentConfig { + cfg.unit = unit + return cfg + }) +} // MeterConfig contains options for Meters. type MeterConfig struct { instrumentationVersion string schemaURL string - attrs attribute.Set - - // Ensure forward compatibility by explicitly making this not comparable. - noCmp [0]func() //nolint: unused // This is indeed used. } -// InstrumentationVersion returns the version of the library providing -// instrumentation. -func (cfg MeterConfig) InstrumentationVersion() string { +// InstrumentationVersion is the version of the library providing instrumentation. +func (cfg *MeterConfig) InstrumentationVersion() string { return cfg.instrumentationVersion } -// InstrumentationAttributes returns the attributes associated with the library -// providing instrumentation. -func (cfg MeterConfig) InstrumentationAttributes() attribute.Set { - return cfg.attrs -} - // SchemaURL is the schema_url of the library providing instrumentation. -func (cfg MeterConfig) SchemaURL() string { +func (cfg *MeterConfig) SchemaURL() string { return cfg.schemaURL } // MeterOption is an interface for applying Meter options. type MeterOption interface { - // applyMeter is used to set a MeterOption value of a MeterConfig. + // ApplyMeter is used to set a MeterOption value of a MeterConfig. applyMeter(MeterConfig) MeterConfig } @@ -73,16 +119,6 @@ func WithInstrumentationVersion(version string) MeterOption { }) } -// WithInstrumentationAttributes sets the instrumentation attributes. -// -// The passed attributes will be de-duplicated. -func WithInstrumentationAttributes(attr ...attribute.KeyValue) MeterOption { - return meterOptionFunc(func(config MeterConfig) MeterConfig { - config.attrs = attribute.NewSet(attr...) - return config - }) -} - // WithSchemaURL sets the schema URL. func WithSchemaURL(schemaURL string) MeterOption { return meterOptionFunc(func(config MeterConfig) MeterConfig { diff --git a/vendor/go.opentelemetry.io/otel/metric/doc.go b/vendor/go.opentelemetry.io/otel/metric/doc.go index bd6f43437208b..4baf0719fcc10 100644 --- a/vendor/go.opentelemetry.io/otel/metric/doc.go +++ b/vendor/go.opentelemetry.io/otel/metric/doc.go @@ -19,5 +19,49 @@ OpenTelemetry API. This package is currently in a pre-GA phase. Backwards incompatible changes may be introduced in subsequent minor version releases as we work to track the evolving OpenTelemetry specification and user feedback. + +Measurements can be made about an operation being performed or the state of a +system in general. These measurements can be crucial to the reliable operation +of code and provide valuable insights about the inner workings of a system. + +Measurements are made using instruments provided by this package. The type of +instrument used will depend on the type of measurement being made and of what +part of a system is being measured. + +Instruments are categorized as Synchronous or Asynchronous and independently +as Adding or Grouping. Synchronous instruments are called by the user with a +Context. Asynchronous instruments are called by the SDK during collection. +Adding instruments are semantically intended for capturing a sum. Grouping +instruments are intended for capturing a distribution. + +Adding instruments may be monotonic, in which case they are non-decreasing +and naturally define a rate. + +The synchronous instrument names are: + + Counter: adding, monotonic + UpDownCounter: adding + Histogram: grouping + +and the asynchronous instruments are: + + CounterObserver: adding, monotonic + UpDownCounterObserver: adding + GaugeObserver: grouping + +All instruments are provided with support for either float64 or int64 input +values. + +An instrument is created using a Meter. Additionally, a Meter is used to +record batches of synchronous measurements or asynchronous observations. A +Meter is obtained using a MeterProvider. A Meter, like a Tracer, is unique to +the instrumentation it instruments and must be named and versioned when +created with a MeterProvider with the name and version of the instrumentation +library. + +Instrumentation should be designed to accept a MeterProvider from which it can +create its own unique Meter. Alternatively, the registered global +MeterProvider from the go.opentelemetry.io/otel package can be used as a +default. */ package metric // import "go.opentelemetry.io/otel/metric" diff --git a/vendor/go.opentelemetry.io/otel/metric/global/global.go b/vendor/go.opentelemetry.io/otel/metric/global/global.go deleted file mode 100644 index cb0896d38acf4..0000000000000 --- a/vendor/go.opentelemetry.io/otel/metric/global/global.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright The OpenTelemetry 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 global // import "go.opentelemetry.io/otel/metric/global" - -import ( - "go.opentelemetry.io/otel/metric" - "go.opentelemetry.io/otel/metric/internal/global" -) - -// Meter returns a Meter from the global MeterProvider. The -// instrumentationName must be the name of the library providing -// instrumentation. This name may be the same as the instrumented code only if -// that code provides built-in instrumentation. If the instrumentationName is -// empty, then a implementation defined default name will be used instead. -// -// This is short for MeterProvider().Meter(name). -func Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter { - return MeterProvider().Meter(instrumentationName, opts...) -} - -// MeterProvider returns the registered global meter provider. -// If none is registered then a No-op MeterProvider is returned. -func MeterProvider() metric.MeterProvider { - return global.MeterProvider() -} - -// SetMeterProvider registers `mp` as the global meter provider. -func SetMeterProvider(mp metric.MeterProvider) { - global.SetMeterProvider(mp) -} diff --git a/vendor/go.opentelemetry.io/otel/metric/global/metric.go b/vendor/go.opentelemetry.io/otel/metric/global/metric.go new file mode 100644 index 0000000000000..14ba862002a2d --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/global/metric.go @@ -0,0 +1,49 @@ +// Copyright The OpenTelemetry 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 global // import "go.opentelemetry.io/otel/metric/global" + +import ( + "go.opentelemetry.io/otel/internal/metric/global" + "go.opentelemetry.io/otel/metric" +) + +// Meter creates an implementation of the Meter interface from the global +// MeterProvider. The instrumentationName must be the name of the library +// providing instrumentation. This name may be the same as the instrumented +// code only if that code provides built-in instrumentation. If the +// instrumentationName is empty, then a implementation defined default name +// will be used instead. +// +// This is short for MeterProvider().Meter(name) +func Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter { + return GetMeterProvider().Meter(instrumentationName, opts...) +} + +// GetMeterProvider returns the registered global meter provider. If +// none is registered then a default meter provider is returned that +// forwards the Meter interface to the first registered Meter. +// +// Use the meter provider to create a named meter. E.g. +// meter := global.MeterProvider().Meter("example.com/foo") +// or +// meter := global.Meter("example.com/foo") +func GetMeterProvider() metric.MeterProvider { + return global.MeterProvider() +} + +// SetMeterProvider registers `mp` as the global meter provider. +func SetMeterProvider(mp metric.MeterProvider) { + global.SetMeterProvider(mp) +} diff --git a/vendor/go.opentelemetry.io/otel/metric/instrument/asyncfloat64.go b/vendor/go.opentelemetry.io/otel/metric/instrument/asyncfloat64.go deleted file mode 100644 index 0b5d5a99c0f69..0000000000000 --- a/vendor/go.opentelemetry.io/otel/metric/instrument/asyncfloat64.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright The OpenTelemetry 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 instrument // import "go.opentelemetry.io/otel/metric/instrument" - -import ( - "context" - - "go.opentelemetry.io/otel/attribute" -) - -// Float64Observable describes a set of instruments used asynchronously to -// record float64 measurements once per collection cycle. Observations of -// these instruments are only made within a callback. -// -// Warning: methods may be added to this interface in minor releases. -type Float64Observable interface { - Asynchronous - - float64Observable() -} - -// Float64ObservableCounter is an instrument used to asynchronously record -// increasing float64 measurements once per collection cycle. Observations are -// only made within a callback for this instrument. The value observed is -// assumed the to be the cumulative sum of the count. -// -// Warning: methods may be added to this interface in minor releases. -type Float64ObservableCounter interface{ Float64Observable } - -// Float64ObservableUpDownCounter is an instrument used to asynchronously -// record float64 measurements once per collection cycle. Observations are only -// made within a callback for this instrument. The value observed is assumed -// the to be the cumulative sum of the count. -// -// Warning: methods may be added to this interface in minor releases. -type Float64ObservableUpDownCounter interface{ Float64Observable } - -// Float64ObservableGauge is an instrument used to asynchronously record -// instantaneous float64 measurements once per collection cycle. Observations -// are only made within a callback for this instrument. -// -// Warning: methods may be added to this interface in minor releases. -type Float64ObservableGauge interface{ Float64Observable } - -// Float64Observer is a recorder of float64 measurements. -// -// Warning: methods may be added to this interface in minor releases. -type Float64Observer interface { - Observe(value float64, attributes ...attribute.KeyValue) -} - -// Float64Callback is a function registered with a Meter that makes -// observations for a Float64Observerable instrument it is registered with. -// Calls to the Float64Observer record measurement values for the -// Float64Observable. -// -// The function needs to complete in a finite amount of time and the deadline -// of the passed context is expected to be honored. -// -// The function needs to make unique observations across all registered -// Float64Callbacks. Meaning, it should not report measurements with the same -// attributes as another Float64Callbacks also registered for the same -// instrument. -// -// The function needs to be concurrent safe. -type Float64Callback func(context.Context, Float64Observer) error - -// Float64ObserverConfig contains options for Asynchronous instruments that -// observe float64 values. -type Float64ObserverConfig struct { - description string - unit string - callbacks []Float64Callback -} - -// NewFloat64ObserverConfig returns a new Float64ObserverConfig with all opts -// applied. -func NewFloat64ObserverConfig(opts ...Float64ObserverOption) Float64ObserverConfig { - var config Float64ObserverConfig - for _, o := range opts { - config = o.applyFloat64Observer(config) - } - return config -} - -// Description returns the Config description. -func (c Float64ObserverConfig) Description() string { - return c.description -} - -// Unit returns the Config unit. -func (c Float64ObserverConfig) Unit() string { - return c.unit -} - -// Callbacks returns the Config callbacks. -func (c Float64ObserverConfig) Callbacks() []Float64Callback { - return c.callbacks -} - -// Float64ObserverOption applies options to float64 Observer instruments. -type Float64ObserverOption interface { - applyFloat64Observer(Float64ObserverConfig) Float64ObserverConfig -} - -type float64ObserverOptionFunc func(Float64ObserverConfig) Float64ObserverConfig - -func (fn float64ObserverOptionFunc) applyFloat64Observer(cfg Float64ObserverConfig) Float64ObserverConfig { - return fn(cfg) -} - -// WithFloat64Callback adds callback to be called for an instrument. -func WithFloat64Callback(callback Float64Callback) Float64ObserverOption { - return float64ObserverOptionFunc(func(cfg Float64ObserverConfig) Float64ObserverConfig { - cfg.callbacks = append(cfg.callbacks, callback) - return cfg - }) -} diff --git a/vendor/go.opentelemetry.io/otel/metric/instrument/asyncint64.go b/vendor/go.opentelemetry.io/otel/metric/instrument/asyncint64.go deleted file mode 100644 index 05feeacb0538f..0000000000000 --- a/vendor/go.opentelemetry.io/otel/metric/instrument/asyncint64.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright The OpenTelemetry 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 instrument // import "go.opentelemetry.io/otel/metric/instrument" - -import ( - "context" - - "go.opentelemetry.io/otel/attribute" -) - -// Int64Observable describes a set of instruments used asynchronously to record -// int64 measurements once per collection cycle. Observations of these -// instruments are only made within a callback. -// -// Warning: methods may be added to this interface in minor releases. -type Int64Observable interface { - Asynchronous - - int64Observable() -} - -// Int64ObservableCounter is an instrument used to asynchronously record -// increasing int64 measurements once per collection cycle. Observations are -// only made within a callback for this instrument. The value observed is -// assumed the to be the cumulative sum of the count. -// -// Warning: methods may be added to this interface in minor releases. -type Int64ObservableCounter interface{ Int64Observable } - -// Int64ObservableUpDownCounter is an instrument used to asynchronously record -// int64 measurements once per collection cycle. Observations are only made -// within a callback for this instrument. The value observed is assumed the to -// be the cumulative sum of the count. -// -// Warning: methods may be added to this interface in minor releases. -type Int64ObservableUpDownCounter interface{ Int64Observable } - -// Int64ObservableGauge is an instrument used to asynchronously record -// instantaneous int64 measurements once per collection cycle. Observations are -// only made within a callback for this instrument. -// -// Warning: methods may be added to this interface in minor releases. -type Int64ObservableGauge interface{ Int64Observable } - -// Int64Observer is a recorder of int64 measurements. -// -// Warning: methods may be added to this interface in minor releases. -type Int64Observer interface { - Observe(value int64, attributes ...attribute.KeyValue) -} - -// Int64Callback is a function registered with a Meter that makes -// observations for a Int64Observerable instrument it is registered with. -// Calls to the Int64Observer record measurement values for the -// Int64Observable. -// -// The function needs to complete in a finite amount of time and the deadline -// of the passed context is expected to be honored. -// -// The function needs to make unique observations across all registered -// Int64Callback. Meaning, it should not report measurements with the same -// attributes as another Int64Callbacks also registered for the same -// instrument. -// -// The function needs to be concurrent safe. -type Int64Callback func(context.Context, Int64Observer) error - -// Int64ObserverConfig contains options for Asynchronous instruments that -// observe int64 values. -type Int64ObserverConfig struct { - description string - unit string - callbacks []Int64Callback -} - -// NewInt64ObserverConfig returns a new Int64ObserverConfig with all opts -// applied. -func NewInt64ObserverConfig(opts ...Int64ObserverOption) Int64ObserverConfig { - var config Int64ObserverConfig - for _, o := range opts { - config = o.applyInt64Observer(config) - } - return config -} - -// Description returns the Config description. -func (c Int64ObserverConfig) Description() string { - return c.description -} - -// Unit returns the Config unit. -func (c Int64ObserverConfig) Unit() string { - return c.unit -} - -// Callbacks returns the Config callbacks. -func (c Int64ObserverConfig) Callbacks() []Int64Callback { - return c.callbacks -} - -// Int64ObserverOption applies options to int64 Observer instruments. -type Int64ObserverOption interface { - applyInt64Observer(Int64ObserverConfig) Int64ObserverConfig -} - -type int64ObserverOptionFunc func(Int64ObserverConfig) Int64ObserverConfig - -func (fn int64ObserverOptionFunc) applyInt64Observer(cfg Int64ObserverConfig) Int64ObserverConfig { - return fn(cfg) -} - -// WithInt64Callback adds callback to be called for an instrument. -func WithInt64Callback(callback Int64Callback) Int64ObserverOption { - return int64ObserverOptionFunc(func(cfg Int64ObserverConfig) Int64ObserverConfig { - cfg.callbacks = append(cfg.callbacks, callback) - return cfg - }) -} diff --git a/vendor/go.opentelemetry.io/otel/metric/instrument/instrument.go b/vendor/go.opentelemetry.io/otel/metric/instrument/instrument.go deleted file mode 100644 index f6dd9e890f4b7..0000000000000 --- a/vendor/go.opentelemetry.io/otel/metric/instrument/instrument.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright The OpenTelemetry 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 instrument // import "go.opentelemetry.io/otel/metric/instrument" - -// Asynchronous instruments are instruments that are updated within a Callback. -// If an instrument is observed outside of it's callback it should be an error. -// -// This interface is used as a grouping mechanism. -type Asynchronous interface { - asynchronous() -} - -// Synchronous instruments are updated in line with application code. -// -// This interface is used as a grouping mechanism. -type Synchronous interface { - synchronous() -} - -// Option applies options to all instruments. -type Option interface { - Float64ObserverOption - Int64ObserverOption - Float64Option - Int64Option -} - -type descOpt string - -func (o descOpt) applyFloat64(c Float64Config) Float64Config { - c.description = string(o) - return c -} - -func (o descOpt) applyInt64(c Int64Config) Int64Config { - c.description = string(o) - return c -} - -func (o descOpt) applyFloat64Observer(c Float64ObserverConfig) Float64ObserverConfig { - c.description = string(o) - return c -} - -func (o descOpt) applyInt64Observer(c Int64ObserverConfig) Int64ObserverConfig { - c.description = string(o) - return c -} - -// WithDescription sets the instrument description. -func WithDescription(desc string) Option { return descOpt(desc) } - -type unitOpt string - -func (o unitOpt) applyFloat64(c Float64Config) Float64Config { - c.unit = string(o) - return c -} - -func (o unitOpt) applyInt64(c Int64Config) Int64Config { - c.unit = string(o) - return c -} - -func (o unitOpt) applyFloat64Observer(c Float64ObserverConfig) Float64ObserverConfig { - c.unit = string(o) - return c -} - -func (o unitOpt) applyInt64Observer(c Int64ObserverConfig) Int64ObserverConfig { - c.unit = string(o) - return c -} - -// WithUnit sets the instrument unit. -func WithUnit(u string) Option { return unitOpt(u) } diff --git a/vendor/go.opentelemetry.io/otel/metric/instrument/syncfloat64.go b/vendor/go.opentelemetry.io/otel/metric/instrument/syncfloat64.go deleted file mode 100644 index 2cdfeb2691afa..0000000000000 --- a/vendor/go.opentelemetry.io/otel/metric/instrument/syncfloat64.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright The OpenTelemetry 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 instrument // import "go.opentelemetry.io/otel/metric/instrument" - -import ( - "context" - - "go.opentelemetry.io/otel/attribute" -) - -// Float64Counter is an instrument that records increasing float64 values. -// -// Warning: methods may be added to this interface in minor releases. -type Float64Counter interface { - // Add records a change to the counter. - Add(ctx context.Context, incr float64, attrs ...attribute.KeyValue) - - Synchronous -} - -// Float64UpDownCounter is an instrument that records increasing or decreasing -// float64 values. -// -// Warning: methods may be added to this interface in minor releases. -type Float64UpDownCounter interface { - // Add records a change to the counter. - Add(ctx context.Context, incr float64, attrs ...attribute.KeyValue) - - Synchronous -} - -// Float64Histogram is an instrument that records a distribution of float64 -// values. -// -// Warning: methods may be added to this interface in minor releases. -type Float64Histogram interface { - // Record adds an additional value to the distribution. - Record(ctx context.Context, incr float64, attrs ...attribute.KeyValue) - - Synchronous -} - -// Float64Config contains options for Asynchronous instruments that -// observe float64 values. -type Float64Config struct { - description string - unit string -} - -// Float64Config contains options for Synchronous instruments that record -// float64 values. -func NewFloat64Config(opts ...Float64Option) Float64Config { - var config Float64Config - for _, o := range opts { - config = o.applyFloat64(config) - } - return config -} - -// Description returns the Config description. -func (c Float64Config) Description() string { - return c.description -} - -// Unit returns the Config unit. -func (c Float64Config) Unit() string { - return c.unit -} - -// Float64Option applies options to synchronous float64 instruments. -type Float64Option interface { - applyFloat64(Float64Config) Float64Config -} diff --git a/vendor/go.opentelemetry.io/otel/metric/instrument/syncint64.go b/vendor/go.opentelemetry.io/otel/metric/instrument/syncint64.go deleted file mode 100644 index e212c6d695f7c..0000000000000 --- a/vendor/go.opentelemetry.io/otel/metric/instrument/syncint64.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright The OpenTelemetry 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 instrument // import "go.opentelemetry.io/otel/metric/instrument" - -import ( - "context" - - "go.opentelemetry.io/otel/attribute" -) - -// Int64Counter is an instrument that records increasing int64 values. -// -// Warning: methods may be added to this interface in minor releases. -type Int64Counter interface { - // Add records a change to the counter. - Add(ctx context.Context, incr int64, attrs ...attribute.KeyValue) - - Synchronous -} - -// Int64UpDownCounter is an instrument that records increasing or decreasing -// int64 values. -// -// Warning: methods may be added to this interface in minor releases. -type Int64UpDownCounter interface { - // Add records a change to the counter. - Add(ctx context.Context, incr int64, attrs ...attribute.KeyValue) - - Synchronous -} - -// Int64Histogram is an instrument that records a distribution of int64 -// values. -// -// Warning: methods may be added to this interface in minor releases. -type Int64Histogram interface { - // Record adds an additional value to the distribution. - Record(ctx context.Context, incr int64, attrs ...attribute.KeyValue) - - Synchronous -} - -// Int64Config contains options for Synchronous instruments that record int64 -// values. -type Int64Config struct { - description string - unit string -} - -// NewInt64Config returns a new Int64Config with all opts -// applied. -func NewInt64Config(opts ...Int64Option) Int64Config { - var config Int64Config - for _, o := range opts { - config = o.applyInt64(config) - } - return config -} - -// Description returns the Config description. -func (c Int64Config) Description() string { - return c.description -} - -// Unit returns the Config unit. -func (c Int64Config) Unit() string { - return c.unit -} - -// Int64Option applies options to synchronous int64 instruments. -type Int64Option interface { - applyInt64(Int64Config) Int64Config -} diff --git a/vendor/go.opentelemetry.io/otel/metric/internal/global/instruments.go b/vendor/go.opentelemetry.io/otel/metric/internal/global/instruments.go deleted file mode 100644 index d1480fa5f3eda..0000000000000 --- a/vendor/go.opentelemetry.io/otel/metric/internal/global/instruments.go +++ /dev/null @@ -1,355 +0,0 @@ -// Copyright The OpenTelemetry 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 global // import "go.opentelemetry.io/otel/metric/internal/global" - -import ( - "context" - "sync/atomic" - - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/metric" - "go.opentelemetry.io/otel/metric/instrument" -) - -// unwrapper unwraps to return the underlying instrument implementation. -type unwrapper interface { - Unwrap() instrument.Asynchronous -} - -type afCounter struct { - instrument.Float64Observable - - name string - opts []instrument.Float64ObserverOption - - delegate atomic.Value //instrument.Float64ObservableCounter -} - -var _ unwrapper = (*afCounter)(nil) -var _ instrument.Float64ObservableCounter = (*afCounter)(nil) - -func (i *afCounter) setDelegate(m metric.Meter) { - ctr, err := m.Float64ObservableCounter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *afCounter) Unwrap() instrument.Asynchronous { - if ctr := i.delegate.Load(); ctr != nil { - return ctr.(instrument.Float64ObservableCounter) - } - return nil -} - -type afUpDownCounter struct { - instrument.Float64Observable - - name string - opts []instrument.Float64ObserverOption - - delegate atomic.Value //instrument.Float64ObservableUpDownCounter -} - -var _ unwrapper = (*afUpDownCounter)(nil) -var _ instrument.Float64ObservableUpDownCounter = (*afUpDownCounter)(nil) - -func (i *afUpDownCounter) setDelegate(m metric.Meter) { - ctr, err := m.Float64ObservableUpDownCounter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *afUpDownCounter) Unwrap() instrument.Asynchronous { - if ctr := i.delegate.Load(); ctr != nil { - return ctr.(instrument.Float64ObservableUpDownCounter) - } - return nil -} - -type afGauge struct { - instrument.Float64Observable - - name string - opts []instrument.Float64ObserverOption - - delegate atomic.Value //instrument.Float64ObservableGauge -} - -var _ unwrapper = (*afGauge)(nil) -var _ instrument.Float64ObservableGauge = (*afGauge)(nil) - -func (i *afGauge) setDelegate(m metric.Meter) { - ctr, err := m.Float64ObservableGauge(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *afGauge) Unwrap() instrument.Asynchronous { - if ctr := i.delegate.Load(); ctr != nil { - return ctr.(instrument.Float64ObservableGauge) - } - return nil -} - -type aiCounter struct { - instrument.Int64Observable - - name string - opts []instrument.Int64ObserverOption - - delegate atomic.Value //instrument.Int64ObservableCounter -} - -var _ unwrapper = (*aiCounter)(nil) -var _ instrument.Int64ObservableCounter = (*aiCounter)(nil) - -func (i *aiCounter) setDelegate(m metric.Meter) { - ctr, err := m.Int64ObservableCounter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *aiCounter) Unwrap() instrument.Asynchronous { - if ctr := i.delegate.Load(); ctr != nil { - return ctr.(instrument.Int64ObservableCounter) - } - return nil -} - -type aiUpDownCounter struct { - instrument.Int64Observable - - name string - opts []instrument.Int64ObserverOption - - delegate atomic.Value //instrument.Int64ObservableUpDownCounter -} - -var _ unwrapper = (*aiUpDownCounter)(nil) -var _ instrument.Int64ObservableUpDownCounter = (*aiUpDownCounter)(nil) - -func (i *aiUpDownCounter) setDelegate(m metric.Meter) { - ctr, err := m.Int64ObservableUpDownCounter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *aiUpDownCounter) Unwrap() instrument.Asynchronous { - if ctr := i.delegate.Load(); ctr != nil { - return ctr.(instrument.Int64ObservableUpDownCounter) - } - return nil -} - -type aiGauge struct { - instrument.Int64Observable - - name string - opts []instrument.Int64ObserverOption - - delegate atomic.Value //instrument.Int64ObservableGauge -} - -var _ unwrapper = (*aiGauge)(nil) -var _ instrument.Int64ObservableGauge = (*aiGauge)(nil) - -func (i *aiGauge) setDelegate(m metric.Meter) { - ctr, err := m.Int64ObservableGauge(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *aiGauge) Unwrap() instrument.Asynchronous { - if ctr := i.delegate.Load(); ctr != nil { - return ctr.(instrument.Int64ObservableGauge) - } - return nil -} - -// Sync Instruments. -type sfCounter struct { - name string - opts []instrument.Float64Option - - delegate atomic.Value //instrument.Float64Counter - - instrument.Synchronous -} - -var _ instrument.Float64Counter = (*sfCounter)(nil) - -func (i *sfCounter) setDelegate(m metric.Meter) { - ctr, err := m.Float64Counter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *sfCounter) Add(ctx context.Context, incr float64, attrs ...attribute.KeyValue) { - if ctr := i.delegate.Load(); ctr != nil { - ctr.(instrument.Float64Counter).Add(ctx, incr, attrs...) - } -} - -type sfUpDownCounter struct { - name string - opts []instrument.Float64Option - - delegate atomic.Value //instrument.Float64UpDownCounter - - instrument.Synchronous -} - -var _ instrument.Float64UpDownCounter = (*sfUpDownCounter)(nil) - -func (i *sfUpDownCounter) setDelegate(m metric.Meter) { - ctr, err := m.Float64UpDownCounter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *sfUpDownCounter) Add(ctx context.Context, incr float64, attrs ...attribute.KeyValue) { - if ctr := i.delegate.Load(); ctr != nil { - ctr.(instrument.Float64UpDownCounter).Add(ctx, incr, attrs...) - } -} - -type sfHistogram struct { - name string - opts []instrument.Float64Option - - delegate atomic.Value //instrument.Float64Histogram - - instrument.Synchronous -} - -var _ instrument.Float64Histogram = (*sfHistogram)(nil) - -func (i *sfHistogram) setDelegate(m metric.Meter) { - ctr, err := m.Float64Histogram(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *sfHistogram) Record(ctx context.Context, x float64, attrs ...attribute.KeyValue) { - if ctr := i.delegate.Load(); ctr != nil { - ctr.(instrument.Float64Histogram).Record(ctx, x, attrs...) - } -} - -type siCounter struct { - name string - opts []instrument.Int64Option - - delegate atomic.Value //instrument.Int64Counter - - instrument.Synchronous -} - -var _ instrument.Int64Counter = (*siCounter)(nil) - -func (i *siCounter) setDelegate(m metric.Meter) { - ctr, err := m.Int64Counter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *siCounter) Add(ctx context.Context, x int64, attrs ...attribute.KeyValue) { - if ctr := i.delegate.Load(); ctr != nil { - ctr.(instrument.Int64Counter).Add(ctx, x, attrs...) - } -} - -type siUpDownCounter struct { - name string - opts []instrument.Int64Option - - delegate atomic.Value //instrument.Int64UpDownCounter - - instrument.Synchronous -} - -var _ instrument.Int64UpDownCounter = (*siUpDownCounter)(nil) - -func (i *siUpDownCounter) setDelegate(m metric.Meter) { - ctr, err := m.Int64UpDownCounter(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *siUpDownCounter) Add(ctx context.Context, x int64, attrs ...attribute.KeyValue) { - if ctr := i.delegate.Load(); ctr != nil { - ctr.(instrument.Int64UpDownCounter).Add(ctx, x, attrs...) - } -} - -type siHistogram struct { - name string - opts []instrument.Int64Option - - delegate atomic.Value //instrument.Int64Histogram - - instrument.Synchronous -} - -var _ instrument.Int64Histogram = (*siHistogram)(nil) - -func (i *siHistogram) setDelegate(m metric.Meter) { - ctr, err := m.Int64Histogram(i.name, i.opts...) - if err != nil { - otel.Handle(err) - return - } - i.delegate.Store(ctr) -} - -func (i *siHistogram) Record(ctx context.Context, x int64, attrs ...attribute.KeyValue) { - if ctr := i.delegate.Load(); ctr != nil { - ctr.(instrument.Int64Histogram).Record(ctx, x, attrs...) - } -} diff --git a/vendor/go.opentelemetry.io/otel/metric/internal/global/meter.go b/vendor/go.opentelemetry.io/otel/metric/internal/global/meter.go deleted file mode 100644 index 8acf632863cb4..0000000000000 --- a/vendor/go.opentelemetry.io/otel/metric/internal/global/meter.go +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright The OpenTelemetry 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 global // import "go.opentelemetry.io/otel/metric/internal/global" - -import ( - "container/list" - "sync" - "sync/atomic" - - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/metric" - "go.opentelemetry.io/otel/metric/instrument" -) - -// meterProvider is a placeholder for a configured SDK MeterProvider. -// -// All MeterProvider functionality is forwarded to a delegate once -// configured. -type meterProvider struct { - mtx sync.Mutex - meters map[il]*meter - - delegate metric.MeterProvider -} - -type il struct { - name string - version string -} - -// setDelegate configures p to delegate all MeterProvider functionality to -// provider. -// -// All Meters provided prior to this function call are switched out to be -// Meters provided by provider. All instruments and callbacks are recreated and -// delegated. -// -// It is guaranteed by the caller that this happens only once. -func (p *meterProvider) setDelegate(provider metric.MeterProvider) { - p.mtx.Lock() - defer p.mtx.Unlock() - - p.delegate = provider - - if len(p.meters) == 0 { - return - } - - for _, meter := range p.meters { - meter.setDelegate(provider) - } - - p.meters = nil -} - -// Meter implements MeterProvider. -func (p *meterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter { - p.mtx.Lock() - defer p.mtx.Unlock() - - if p.delegate != nil { - return p.delegate.Meter(name, opts...) - } - - // At this moment it is guaranteed that no sdk is installed, save the meter in the meters map. - - c := metric.NewMeterConfig(opts...) - key := il{ - name: name, - version: c.InstrumentationVersion(), - } - - if p.meters == nil { - p.meters = make(map[il]*meter) - } - - if val, ok := p.meters[key]; ok { - return val - } - - t := &meter{name: name, opts: opts} - p.meters[key] = t - return t -} - -// meter is a placeholder for a metric.Meter. -// -// All Meter functionality is forwarded to a delegate once configured. -// Otherwise, all functionality is forwarded to a NoopMeter. -type meter struct { - name string - opts []metric.MeterOption - - mtx sync.Mutex - instruments []delegatedInstrument - - registry list.List - - delegate atomic.Value // metric.Meter -} - -type delegatedInstrument interface { - setDelegate(metric.Meter) -} - -// setDelegate configures m to delegate all Meter functionality to Meters -// created by provider. -// -// All subsequent calls to the Meter methods will be passed to the delegate. -// -// It is guaranteed by the caller that this happens only once. -func (m *meter) setDelegate(provider metric.MeterProvider) { - meter := provider.Meter(m.name, m.opts...) - m.delegate.Store(meter) - - m.mtx.Lock() - defer m.mtx.Unlock() - - for _, inst := range m.instruments { - inst.setDelegate(meter) - } - - for e := m.registry.Front(); e != nil; e = e.Next() { - r := e.Value.(*registration) - r.setDelegate(meter) - m.registry.Remove(e) - } - - m.instruments = nil - m.registry.Init() -} - -func (m *meter) Int64Counter(name string, options ...instrument.Int64Option) (instrument.Int64Counter, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - return del.Int64Counter(name, options...) - } - m.mtx.Lock() - defer m.mtx.Unlock() - i := &siCounter{name: name, opts: options} - m.instruments = append(m.instruments, i) - return i, nil -} - -func (m *meter) Int64UpDownCounter(name string, options ...instrument.Int64Option) (instrument.Int64UpDownCounter, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - return del.Int64UpDownCounter(name, options...) - } - m.mtx.Lock() - defer m.mtx.Unlock() - i := &siUpDownCounter{name: name, opts: options} - m.instruments = append(m.instruments, i) - return i, nil -} - -func (m *meter) Int64Histogram(name string, options ...instrument.Int64Option) (instrument.Int64Histogram, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - return del.Int64Histogram(name, options...) - } - m.mtx.Lock() - defer m.mtx.Unlock() - i := &siHistogram{name: name, opts: options} - m.instruments = append(m.instruments, i) - return i, nil -} - -func (m *meter) Int64ObservableCounter(name string, options ...instrument.Int64ObserverOption) (instrument.Int64ObservableCounter, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - return del.Int64ObservableCounter(name, options...) - } - m.mtx.Lock() - defer m.mtx.Unlock() - i := &aiCounter{name: name, opts: options} - m.instruments = append(m.instruments, i) - return i, nil -} - -func (m *meter) Int64ObservableUpDownCounter(name string, options ...instrument.Int64ObserverOption) (instrument.Int64ObservableUpDownCounter, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - return del.Int64ObservableUpDownCounter(name, options...) - } - m.mtx.Lock() - defer m.mtx.Unlock() - i := &aiUpDownCounter{name: name, opts: options} - m.instruments = append(m.instruments, i) - return i, nil -} - -func (m *meter) Int64ObservableGauge(name string, options ...instrument.Int64ObserverOption) (instrument.Int64ObservableGauge, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - return del.Int64ObservableGauge(name, options...) - } - m.mtx.Lock() - defer m.mtx.Unlock() - i := &aiGauge{name: name, opts: options} - m.instruments = append(m.instruments, i) - return i, nil -} - -func (m *meter) Float64Counter(name string, options ...instrument.Float64Option) (instrument.Float64Counter, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - return del.Float64Counter(name, options...) - } - m.mtx.Lock() - defer m.mtx.Unlock() - i := &sfCounter{name: name, opts: options} - m.instruments = append(m.instruments, i) - return i, nil -} - -func (m *meter) Float64UpDownCounter(name string, options ...instrument.Float64Option) (instrument.Float64UpDownCounter, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - return del.Float64UpDownCounter(name, options...) - } - m.mtx.Lock() - defer m.mtx.Unlock() - i := &sfUpDownCounter{name: name, opts: options} - m.instruments = append(m.instruments, i) - return i, nil -} - -func (m *meter) Float64Histogram(name string, options ...instrument.Float64Option) (instrument.Float64Histogram, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - return del.Float64Histogram(name, options...) - } - m.mtx.Lock() - defer m.mtx.Unlock() - i := &sfHistogram{name: name, opts: options} - m.instruments = append(m.instruments, i) - return i, nil -} - -func (m *meter) Float64ObservableCounter(name string, options ...instrument.Float64ObserverOption) (instrument.Float64ObservableCounter, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - return del.Float64ObservableCounter(name, options...) - } - m.mtx.Lock() - defer m.mtx.Unlock() - i := &afCounter{name: name, opts: options} - m.instruments = append(m.instruments, i) - return i, nil -} - -func (m *meter) Float64ObservableUpDownCounter(name string, options ...instrument.Float64ObserverOption) (instrument.Float64ObservableUpDownCounter, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - return del.Float64ObservableUpDownCounter(name, options...) - } - m.mtx.Lock() - defer m.mtx.Unlock() - i := &afUpDownCounter{name: name, opts: options} - m.instruments = append(m.instruments, i) - return i, nil -} - -func (m *meter) Float64ObservableGauge(name string, options ...instrument.Float64ObserverOption) (instrument.Float64ObservableGauge, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - return del.Float64ObservableGauge(name, options...) - } - m.mtx.Lock() - defer m.mtx.Unlock() - i := &afGauge{name: name, opts: options} - m.instruments = append(m.instruments, i) - return i, nil -} - -// RegisterCallback captures the function that will be called during Collect. -func (m *meter) RegisterCallback(f metric.Callback, insts ...instrument.Asynchronous) (metric.Registration, error) { - if del, ok := m.delegate.Load().(metric.Meter); ok { - insts = unwrapInstruments(insts) - return del.RegisterCallback(f, insts...) - } - - m.mtx.Lock() - defer m.mtx.Unlock() - - reg := ®istration{instruments: insts, function: f} - e := m.registry.PushBack(reg) - reg.unreg = func() error { - m.mtx.Lock() - _ = m.registry.Remove(e) - m.mtx.Unlock() - return nil - } - return reg, nil -} - -type wrapped interface { - unwrap() instrument.Asynchronous -} - -func unwrapInstruments(instruments []instrument.Asynchronous) []instrument.Asynchronous { - out := make([]instrument.Asynchronous, 0, len(instruments)) - - for _, inst := range instruments { - if in, ok := inst.(wrapped); ok { - out = append(out, in.unwrap()) - } else { - out = append(out, inst) - } - } - - return out -} - -type registration struct { - instruments []instrument.Asynchronous - function metric.Callback - - unreg func() error - unregMu sync.Mutex -} - -func (c *registration) setDelegate(m metric.Meter) { - insts := unwrapInstruments(c.instruments) - - c.unregMu.Lock() - defer c.unregMu.Unlock() - - if c.unreg == nil { - // Unregister already called. - return - } - - reg, err := m.RegisterCallback(c.function, insts...) - if err != nil { - otel.Handle(err) - } - - c.unreg = reg.Unregister -} - -func (c *registration) Unregister() error { - c.unregMu.Lock() - defer c.unregMu.Unlock() - if c.unreg == nil { - // Unregister already called. - return nil - } - - var err error - err, c.unreg = c.unreg(), nil - return err -} diff --git a/vendor/go.opentelemetry.io/otel/metric/meter.go b/vendor/go.opentelemetry.io/otel/metric/meter.go deleted file mode 100644 index 2f69d2ae54fd7..0000000000000 --- a/vendor/go.opentelemetry.io/otel/metric/meter.go +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright The OpenTelemetry 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 metric // import "go.opentelemetry.io/otel/metric" - -import ( - "context" - - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/metric/instrument" -) - -// MeterProvider provides access to named Meter instances, for instrumenting -// an application or library. -// -// Warning: methods may be added to this interface in minor releases. -type MeterProvider interface { - // Meter creates an instance of a `Meter` interface. The name must be the - // name of the library providing instrumentation. This name may be the same - // as the instrumented code only if that code provides built-in - // instrumentation. If the name is empty, then a implementation defined - // default name will be used instead. - Meter(name string, opts ...MeterOption) Meter -} - -// Meter provides access to instrument instances for recording metrics. -// -// Warning: methods may be added to this interface in minor releases. -type Meter interface { - // Int64Counter returns a new instrument identified by name and configured - // with options. The instrument is used to synchronously record increasing - // int64 measurements during a computational operation. - Int64Counter(name string, options ...instrument.Int64Option) (instrument.Int64Counter, error) - // Int64UpDownCounter returns a new instrument identified by name and - // configured with options. The instrument is used to synchronously record - // int64 measurements during a computational operation. - Int64UpDownCounter(name string, options ...instrument.Int64Option) (instrument.Int64UpDownCounter, error) - // Int64Histogram returns a new instrument identified by name and - // configured with options. The instrument is used to synchronously record - // the distribution of int64 measurements during a computational operation. - Int64Histogram(name string, options ...instrument.Int64Option) (instrument.Int64Histogram, error) - // Int64ObservableCounter returns a new instrument identified by name and - // configured with options. The instrument is used to asynchronously record - // increasing int64 measurements once per a measurement collection cycle. - Int64ObservableCounter(name string, options ...instrument.Int64ObserverOption) (instrument.Int64ObservableCounter, error) - // Int64ObservableUpDownCounter returns a new instrument identified by name - // and configured with options. The instrument is used to asynchronously - // record int64 measurements once per a measurement collection cycle. - Int64ObservableUpDownCounter(name string, options ...instrument.Int64ObserverOption) (instrument.Int64ObservableUpDownCounter, error) - // Int64ObservableGauge returns a new instrument identified by name and - // configured with options. The instrument is used to asynchronously record - // instantaneous int64 measurements once per a measurement collection - // cycle. - Int64ObservableGauge(name string, options ...instrument.Int64ObserverOption) (instrument.Int64ObservableGauge, error) - - // Float64Counter returns a new instrument identified by name and - // configured with options. The instrument is used to synchronously record - // increasing float64 measurements during a computational operation. - Float64Counter(name string, options ...instrument.Float64Option) (instrument.Float64Counter, error) - // Float64UpDownCounter returns a new instrument identified by name and - // configured with options. The instrument is used to synchronously record - // float64 measurements during a computational operation. - Float64UpDownCounter(name string, options ...instrument.Float64Option) (instrument.Float64UpDownCounter, error) - // Float64Histogram returns a new instrument identified by name and - // configured with options. The instrument is used to synchronously record - // the distribution of float64 measurements during a computational - // operation. - Float64Histogram(name string, options ...instrument.Float64Option) (instrument.Float64Histogram, error) - // Float64ObservableCounter returns a new instrument identified by name and - // configured with options. The instrument is used to asynchronously record - // increasing float64 measurements once per a measurement collection cycle. - Float64ObservableCounter(name string, options ...instrument.Float64ObserverOption) (instrument.Float64ObservableCounter, error) - // Float64ObservableUpDownCounter returns a new instrument identified by - // name and configured with options. The instrument is used to - // asynchronously record float64 measurements once per a measurement - // collection cycle. - Float64ObservableUpDownCounter(name string, options ...instrument.Float64ObserverOption) (instrument.Float64ObservableUpDownCounter, error) - // Float64ObservableGauge returns a new instrument identified by name and - // configured with options. The instrument is used to asynchronously record - // instantaneous float64 measurements once per a measurement collection - // cycle. - Float64ObservableGauge(name string, options ...instrument.Float64ObserverOption) (instrument.Float64ObservableGauge, error) - - // RegisterCallback registers f to be called during the collection of a - // measurement cycle. - // - // If Unregister of the returned Registration is called, f needs to be - // unregistered and not called during collection. - // - // The instruments f is registered with are the only instruments that f may - // observe values for. - // - // If no instruments are passed, f should not be registered nor called - // during collection. - RegisterCallback(f Callback, instruments ...instrument.Asynchronous) (Registration, error) -} - -// Callback is a function registered with a Meter that makes observations for -// the set of instruments it is registered with. The Observer parameter is used -// to record measurment observations for these instruments. -// -// The function needs to complete in a finite amount of time and the deadline -// of the passed context is expected to be honored. -// -// The function needs to make unique observations across all registered -// Callbacks. Meaning, it should not report measurements for an instrument with -// the same attributes as another Callback will report. -// -// The function needs to be concurrent safe. -type Callback func(context.Context, Observer) error - -// Observer records measurements for multiple instruments in a Callback. -type Observer interface { - // ObserveFloat64 records the float64 value with attributes for obsrv. - ObserveFloat64(obsrv instrument.Float64Observable, value float64, attributes ...attribute.KeyValue) - // ObserveInt64 records the int64 value with attributes for obsrv. - ObserveInt64(obsrv instrument.Int64Observable, value int64, attributes ...attribute.KeyValue) -} - -// Registration is an token representing the unique registration of a callback -// for a set of instruments with a Meter. -type Registration interface { - // Unregister removes the callback registration from a Meter. - // - // This method needs to be idempotent and concurrent safe. - Unregister() error -} diff --git a/vendor/go.opentelemetry.io/otel/metric/metric.go b/vendor/go.opentelemetry.io/otel/metric/metric.go new file mode 100644 index 0000000000000..d8c5a6b3f353f --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/metric.go @@ -0,0 +1,538 @@ +// Copyright The OpenTelemetry 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 metric // import "go.opentelemetry.io/otel/metric" + +import ( + "context" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric/number" + "go.opentelemetry.io/otel/metric/sdkapi" +) + +// MeterProvider supports named Meter instances. +type MeterProvider interface { + // Meter creates an implementation of the Meter interface. + // The instrumentationName must be the name of the library providing + // instrumentation. This name may be the same as the instrumented code + // only if that code provides built-in instrumentation. If the + // instrumentationName is empty, then a implementation defined default + // name will be used instead. + Meter(instrumentationName string, opts ...MeterOption) Meter +} + +// Meter is the creator of metric instruments. +// +// An uninitialized Meter is a no-op implementation. +type Meter struct { + impl sdkapi.MeterImpl +} + +// WrapMeterImpl constructs a `Meter` implementation from a +// `MeterImpl` implementation. +func WrapMeterImpl(impl sdkapi.MeterImpl) Meter { + return Meter{ + impl: impl, + } +} + +// Measurement is used for reporting a synchronous batch of metric +// values. Instances of this type should be created by synchronous +// instruments (e.g., Int64Counter.Measurement()). +// +// Note: This is an alias because it is a first-class member of the +// API but is also part of the lower-level sdkapi interface. +type Measurement = sdkapi.Measurement + +// Observation is used for reporting an asynchronous batch of metric +// values. Instances of this type should be created by asynchronous +// instruments (e.g., Int64GaugeObserver.Observation()). +// +// Note: This is an alias because it is a first-class member of the +// API but is also part of the lower-level sdkapi interface. +type Observation = sdkapi.Observation + +// RecordBatch atomically records a batch of measurements. +func (m Meter) RecordBatch(ctx context.Context, ls []attribute.KeyValue, ms ...Measurement) { + if m.impl == nil { + return + } + m.impl.RecordBatch(ctx, ls, ms...) +} + +// NewBatchObserver creates a new BatchObserver that supports +// making batches of observations for multiple instruments. +func (m Meter) NewBatchObserver(callback BatchObserverFunc) BatchObserver { + return BatchObserver{ + meter: m, + runner: newBatchAsyncRunner(callback), + } +} + +// NewInt64Counter creates a new integer Counter instrument with the +// given name, customized with options. May return an error if the +// name is invalid (e.g., empty) or improperly registered (e.g., +// duplicate registration). +func (m Meter) NewInt64Counter(name string, options ...InstrumentOption) (Int64Counter, error) { + return wrapInt64CounterInstrument( + m.newSync(name, sdkapi.CounterInstrumentKind, number.Int64Kind, options)) +} + +// NewFloat64Counter creates a new floating point Counter with the +// given name, customized with options. May return an error if the +// name is invalid (e.g., empty) or improperly registered (e.g., +// duplicate registration). +func (m Meter) NewFloat64Counter(name string, options ...InstrumentOption) (Float64Counter, error) { + return wrapFloat64CounterInstrument( + m.newSync(name, sdkapi.CounterInstrumentKind, number.Float64Kind, options)) +} + +// NewInt64UpDownCounter creates a new integer UpDownCounter instrument with the +// given name, customized with options. May return an error if the +// name is invalid (e.g., empty) or improperly registered (e.g., +// duplicate registration). +func (m Meter) NewInt64UpDownCounter(name string, options ...InstrumentOption) (Int64UpDownCounter, error) { + return wrapInt64UpDownCounterInstrument( + m.newSync(name, sdkapi.UpDownCounterInstrumentKind, number.Int64Kind, options)) +} + +// NewFloat64UpDownCounter creates a new floating point UpDownCounter with the +// given name, customized with options. May return an error if the +// name is invalid (e.g., empty) or improperly registered (e.g., +// duplicate registration). +func (m Meter) NewFloat64UpDownCounter(name string, options ...InstrumentOption) (Float64UpDownCounter, error) { + return wrapFloat64UpDownCounterInstrument( + m.newSync(name, sdkapi.UpDownCounterInstrumentKind, number.Float64Kind, options)) +} + +// NewInt64Histogram creates a new integer Histogram instrument with the +// given name, customized with options. May return an error if the +// name is invalid (e.g., empty) or improperly registered (e.g., +// duplicate registration). +func (m Meter) NewInt64Histogram(name string, opts ...InstrumentOption) (Int64Histogram, error) { + return wrapInt64HistogramInstrument( + m.newSync(name, sdkapi.HistogramInstrumentKind, number.Int64Kind, opts)) +} + +// NewFloat64Histogram creates a new floating point Histogram with the +// given name, customized with options. May return an error if the +// name is invalid (e.g., empty) or improperly registered (e.g., +// duplicate registration). +func (m Meter) NewFloat64Histogram(name string, opts ...InstrumentOption) (Float64Histogram, error) { + return wrapFloat64HistogramInstrument( + m.newSync(name, sdkapi.HistogramInstrumentKind, number.Float64Kind, opts)) +} + +// NewInt64GaugeObserver creates a new integer GaugeObserver instrument +// with the given name, running a given callback, and customized with +// options. May return an error if the name is invalid (e.g., empty) +// or improperly registered (e.g., duplicate registration). +func (m Meter) NewInt64GaugeObserver(name string, callback Int64ObserverFunc, opts ...InstrumentOption) (Int64GaugeObserver, error) { + if callback == nil { + return wrapInt64GaugeObserverInstrument(sdkapi.NewNoopAsyncInstrument(), nil) + } + return wrapInt64GaugeObserverInstrument( + m.newAsync(name, sdkapi.GaugeObserverInstrumentKind, number.Int64Kind, opts, + newInt64AsyncRunner(callback))) +} + +// NewFloat64GaugeObserver creates a new floating point GaugeObserver with +// the given name, running a given callback, and customized with +// options. May return an error if the name is invalid (e.g., empty) +// or improperly registered (e.g., duplicate registration). +func (m Meter) NewFloat64GaugeObserver(name string, callback Float64ObserverFunc, opts ...InstrumentOption) (Float64GaugeObserver, error) { + if callback == nil { + return wrapFloat64GaugeObserverInstrument(sdkapi.NewNoopAsyncInstrument(), nil) + } + return wrapFloat64GaugeObserverInstrument( + m.newAsync(name, sdkapi.GaugeObserverInstrumentKind, number.Float64Kind, opts, + newFloat64AsyncRunner(callback))) +} + +// NewInt64CounterObserver creates a new integer CounterObserver instrument +// with the given name, running a given callback, and customized with +// options. May return an error if the name is invalid (e.g., empty) +// or improperly registered (e.g., duplicate registration). +func (m Meter) NewInt64CounterObserver(name string, callback Int64ObserverFunc, opts ...InstrumentOption) (Int64CounterObserver, error) { + if callback == nil { + return wrapInt64CounterObserverInstrument(sdkapi.NewNoopAsyncInstrument(), nil) + } + return wrapInt64CounterObserverInstrument( + m.newAsync(name, sdkapi.CounterObserverInstrumentKind, number.Int64Kind, opts, + newInt64AsyncRunner(callback))) +} + +// NewFloat64CounterObserver creates a new floating point CounterObserver with +// the given name, running a given callback, and customized with +// options. May return an error if the name is invalid (e.g., empty) +// or improperly registered (e.g., duplicate registration). +func (m Meter) NewFloat64CounterObserver(name string, callback Float64ObserverFunc, opts ...InstrumentOption) (Float64CounterObserver, error) { + if callback == nil { + return wrapFloat64CounterObserverInstrument(sdkapi.NewNoopAsyncInstrument(), nil) + } + return wrapFloat64CounterObserverInstrument( + m.newAsync(name, sdkapi.CounterObserverInstrumentKind, number.Float64Kind, opts, + newFloat64AsyncRunner(callback))) +} + +// NewInt64UpDownCounterObserver creates a new integer UpDownCounterObserver instrument +// with the given name, running a given callback, and customized with +// options. May return an error if the name is invalid (e.g., empty) +// or improperly registered (e.g., duplicate registration). +func (m Meter) NewInt64UpDownCounterObserver(name string, callback Int64ObserverFunc, opts ...InstrumentOption) (Int64UpDownCounterObserver, error) { + if callback == nil { + return wrapInt64UpDownCounterObserverInstrument(sdkapi.NewNoopAsyncInstrument(), nil) + } + return wrapInt64UpDownCounterObserverInstrument( + m.newAsync(name, sdkapi.UpDownCounterObserverInstrumentKind, number.Int64Kind, opts, + newInt64AsyncRunner(callback))) +} + +// NewFloat64UpDownCounterObserver creates a new floating point UpDownCounterObserver with +// the given name, running a given callback, and customized with +// options. May return an error if the name is invalid (e.g., empty) +// or improperly registered (e.g., duplicate registration). +func (m Meter) NewFloat64UpDownCounterObserver(name string, callback Float64ObserverFunc, opts ...InstrumentOption) (Float64UpDownCounterObserver, error) { + if callback == nil { + return wrapFloat64UpDownCounterObserverInstrument(sdkapi.NewNoopAsyncInstrument(), nil) + } + return wrapFloat64UpDownCounterObserverInstrument( + m.newAsync(name, sdkapi.UpDownCounterObserverInstrumentKind, number.Float64Kind, opts, + newFloat64AsyncRunner(callback))) +} + +// NewInt64GaugeObserver creates a new integer GaugeObserver instrument +// with the given name, running in a batch callback, and customized with +// options. May return an error if the name is invalid (e.g., empty) +// or improperly registered (e.g., duplicate registration). +func (b BatchObserver) NewInt64GaugeObserver(name string, opts ...InstrumentOption) (Int64GaugeObserver, error) { + if b.runner == nil { + return wrapInt64GaugeObserverInstrument(sdkapi.NewNoopAsyncInstrument(), nil) + } + return wrapInt64GaugeObserverInstrument( + b.meter.newAsync(name, sdkapi.GaugeObserverInstrumentKind, number.Int64Kind, opts, b.runner)) +} + +// NewFloat64GaugeObserver creates a new floating point GaugeObserver with +// the given name, running in a batch callback, and customized with +// options. May return an error if the name is invalid (e.g., empty) +// or improperly registered (e.g., duplicate registration). +func (b BatchObserver) NewFloat64GaugeObserver(name string, opts ...InstrumentOption) (Float64GaugeObserver, error) { + if b.runner == nil { + return wrapFloat64GaugeObserverInstrument(sdkapi.NewNoopAsyncInstrument(), nil) + } + return wrapFloat64GaugeObserverInstrument( + b.meter.newAsync(name, sdkapi.GaugeObserverInstrumentKind, number.Float64Kind, opts, + b.runner)) +} + +// NewInt64CounterObserver creates a new integer CounterObserver instrument +// with the given name, running in a batch callback, and customized with +// options. May return an error if the name is invalid (e.g., empty) +// or improperly registered (e.g., duplicate registration). +func (b BatchObserver) NewInt64CounterObserver(name string, opts ...InstrumentOption) (Int64CounterObserver, error) { + if b.runner == nil { + return wrapInt64CounterObserverInstrument(sdkapi.NewNoopAsyncInstrument(), nil) + } + return wrapInt64CounterObserverInstrument( + b.meter.newAsync(name, sdkapi.CounterObserverInstrumentKind, number.Int64Kind, opts, b.runner)) +} + +// NewFloat64CounterObserver creates a new floating point CounterObserver with +// the given name, running in a batch callback, and customized with +// options. May return an error if the name is invalid (e.g., empty) +// or improperly registered (e.g., duplicate registration). +func (b BatchObserver) NewFloat64CounterObserver(name string, opts ...InstrumentOption) (Float64CounterObserver, error) { + if b.runner == nil { + return wrapFloat64CounterObserverInstrument(sdkapi.NewNoopAsyncInstrument(), nil) + } + return wrapFloat64CounterObserverInstrument( + b.meter.newAsync(name, sdkapi.CounterObserverInstrumentKind, number.Float64Kind, opts, + b.runner)) +} + +// NewInt64UpDownCounterObserver creates a new integer UpDownCounterObserver instrument +// with the given name, running in a batch callback, and customized with +// options. May return an error if the name is invalid (e.g., empty) +// or improperly registered (e.g., duplicate registration). +func (b BatchObserver) NewInt64UpDownCounterObserver(name string, opts ...InstrumentOption) (Int64UpDownCounterObserver, error) { + if b.runner == nil { + return wrapInt64UpDownCounterObserverInstrument(sdkapi.NewNoopAsyncInstrument(), nil) + } + return wrapInt64UpDownCounterObserverInstrument( + b.meter.newAsync(name, sdkapi.UpDownCounterObserverInstrumentKind, number.Int64Kind, opts, b.runner)) +} + +// NewFloat64UpDownCounterObserver creates a new floating point UpDownCounterObserver with +// the given name, running in a batch callback, and customized with +// options. May return an error if the name is invalid (e.g., empty) +// or improperly registered (e.g., duplicate registration). +func (b BatchObserver) NewFloat64UpDownCounterObserver(name string, opts ...InstrumentOption) (Float64UpDownCounterObserver, error) { + if b.runner == nil { + return wrapFloat64UpDownCounterObserverInstrument(sdkapi.NewNoopAsyncInstrument(), nil) + } + return wrapFloat64UpDownCounterObserverInstrument( + b.meter.newAsync(name, sdkapi.UpDownCounterObserverInstrumentKind, number.Float64Kind, opts, + b.runner)) +} + +// MeterImpl returns the underlying MeterImpl of this Meter. +func (m Meter) MeterImpl() sdkapi.MeterImpl { + return m.impl +} + +// newAsync constructs one new asynchronous instrument. +func (m Meter) newAsync( + name string, + mkind sdkapi.InstrumentKind, + nkind number.Kind, + opts []InstrumentOption, + runner sdkapi.AsyncRunner, +) ( + sdkapi.AsyncImpl, + error, +) { + if m.impl == nil { + return sdkapi.NewNoopAsyncInstrument(), nil + } + cfg := NewInstrumentConfig(opts...) + desc := sdkapi.NewDescriptor(name, mkind, nkind, cfg.description, cfg.unit) + return m.impl.NewAsyncInstrument(desc, runner) +} + +// newSync constructs one new synchronous instrument. +func (m Meter) newSync( + name string, + metricKind sdkapi.InstrumentKind, + numberKind number.Kind, + opts []InstrumentOption, +) ( + sdkapi.SyncImpl, + error, +) { + if m.impl == nil { + return sdkapi.NewNoopSyncInstrument(), nil + } + cfg := NewInstrumentConfig(opts...) + desc := sdkapi.NewDescriptor(name, metricKind, numberKind, cfg.description, cfg.unit) + return m.impl.NewSyncInstrument(desc) +} + +// MeterMust is a wrapper for Meter interfaces that panics when any +// instrument constructor encounters an error. +type MeterMust struct { + meter Meter +} + +// BatchObserverMust is a wrapper for BatchObserver that panics when +// any instrument constructor encounters an error. +type BatchObserverMust struct { + batch BatchObserver +} + +// Must constructs a MeterMust implementation from a Meter, allowing +// the application to panic when any instrument constructor yields an +// error. +func Must(meter Meter) MeterMust { + return MeterMust{meter: meter} +} + +// NewInt64Counter calls `Meter.NewInt64Counter` and returns the +// instrument, panicking if it encounters an error. +func (mm MeterMust) NewInt64Counter(name string, cos ...InstrumentOption) Int64Counter { + if inst, err := mm.meter.NewInt64Counter(name, cos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64Counter calls `Meter.NewFloat64Counter` and returns the +// instrument, panicking if it encounters an error. +func (mm MeterMust) NewFloat64Counter(name string, cos ...InstrumentOption) Float64Counter { + if inst, err := mm.meter.NewFloat64Counter(name, cos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64UpDownCounter calls `Meter.NewInt64UpDownCounter` and returns the +// instrument, panicking if it encounters an error. +func (mm MeterMust) NewInt64UpDownCounter(name string, cos ...InstrumentOption) Int64UpDownCounter { + if inst, err := mm.meter.NewInt64UpDownCounter(name, cos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64UpDownCounter calls `Meter.NewFloat64UpDownCounter` and returns the +// instrument, panicking if it encounters an error. +func (mm MeterMust) NewFloat64UpDownCounter(name string, cos ...InstrumentOption) Float64UpDownCounter { + if inst, err := mm.meter.NewFloat64UpDownCounter(name, cos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64Histogram calls `Meter.NewInt64Histogram` and returns the +// instrument, panicking if it encounters an error. +func (mm MeterMust) NewInt64Histogram(name string, mos ...InstrumentOption) Int64Histogram { + if inst, err := mm.meter.NewInt64Histogram(name, mos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64Histogram calls `Meter.NewFloat64Histogram` and returns the +// instrument, panicking if it encounters an error. +func (mm MeterMust) NewFloat64Histogram(name string, mos ...InstrumentOption) Float64Histogram { + if inst, err := mm.meter.NewFloat64Histogram(name, mos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64GaugeObserver calls `Meter.NewInt64GaugeObserver` and +// returns the instrument, panicking if it encounters an error. +func (mm MeterMust) NewInt64GaugeObserver(name string, callback Int64ObserverFunc, oos ...InstrumentOption) Int64GaugeObserver { + if inst, err := mm.meter.NewInt64GaugeObserver(name, callback, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64GaugeObserver calls `Meter.NewFloat64GaugeObserver` and +// returns the instrument, panicking if it encounters an error. +func (mm MeterMust) NewFloat64GaugeObserver(name string, callback Float64ObserverFunc, oos ...InstrumentOption) Float64GaugeObserver { + if inst, err := mm.meter.NewFloat64GaugeObserver(name, callback, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64CounterObserver calls `Meter.NewInt64CounterObserver` and +// returns the instrument, panicking if it encounters an error. +func (mm MeterMust) NewInt64CounterObserver(name string, callback Int64ObserverFunc, oos ...InstrumentOption) Int64CounterObserver { + if inst, err := mm.meter.NewInt64CounterObserver(name, callback, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64CounterObserver calls `Meter.NewFloat64CounterObserver` and +// returns the instrument, panicking if it encounters an error. +func (mm MeterMust) NewFloat64CounterObserver(name string, callback Float64ObserverFunc, oos ...InstrumentOption) Float64CounterObserver { + if inst, err := mm.meter.NewFloat64CounterObserver(name, callback, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64UpDownCounterObserver calls `Meter.NewInt64UpDownCounterObserver` and +// returns the instrument, panicking if it encounters an error. +func (mm MeterMust) NewInt64UpDownCounterObserver(name string, callback Int64ObserverFunc, oos ...InstrumentOption) Int64UpDownCounterObserver { + if inst, err := mm.meter.NewInt64UpDownCounterObserver(name, callback, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64UpDownCounterObserver calls `Meter.NewFloat64UpDownCounterObserver` and +// returns the instrument, panicking if it encounters an error. +func (mm MeterMust) NewFloat64UpDownCounterObserver(name string, callback Float64ObserverFunc, oos ...InstrumentOption) Float64UpDownCounterObserver { + if inst, err := mm.meter.NewFloat64UpDownCounterObserver(name, callback, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewBatchObserver returns a wrapper around BatchObserver that panics +// when any instrument constructor returns an error. +func (mm MeterMust) NewBatchObserver(callback BatchObserverFunc) BatchObserverMust { + return BatchObserverMust{ + batch: mm.meter.NewBatchObserver(callback), + } +} + +// NewInt64GaugeObserver calls `BatchObserver.NewInt64GaugeObserver` and +// returns the instrument, panicking if it encounters an error. +func (bm BatchObserverMust) NewInt64GaugeObserver(name string, oos ...InstrumentOption) Int64GaugeObserver { + if inst, err := bm.batch.NewInt64GaugeObserver(name, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64GaugeObserver calls `BatchObserver.NewFloat64GaugeObserver` and +// returns the instrument, panicking if it encounters an error. +func (bm BatchObserverMust) NewFloat64GaugeObserver(name string, oos ...InstrumentOption) Float64GaugeObserver { + if inst, err := bm.batch.NewFloat64GaugeObserver(name, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64CounterObserver calls `BatchObserver.NewInt64CounterObserver` and +// returns the instrument, panicking if it encounters an error. +func (bm BatchObserverMust) NewInt64CounterObserver(name string, oos ...InstrumentOption) Int64CounterObserver { + if inst, err := bm.batch.NewInt64CounterObserver(name, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64CounterObserver calls `BatchObserver.NewFloat64CounterObserver` and +// returns the instrument, panicking if it encounters an error. +func (bm BatchObserverMust) NewFloat64CounterObserver(name string, oos ...InstrumentOption) Float64CounterObserver { + if inst, err := bm.batch.NewFloat64CounterObserver(name, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewInt64UpDownCounterObserver calls `BatchObserver.NewInt64UpDownCounterObserver` and +// returns the instrument, panicking if it encounters an error. +func (bm BatchObserverMust) NewInt64UpDownCounterObserver(name string, oos ...InstrumentOption) Int64UpDownCounterObserver { + if inst, err := bm.batch.NewInt64UpDownCounterObserver(name, oos...); err != nil { + panic(err) + } else { + return inst + } +} + +// NewFloat64UpDownCounterObserver calls `BatchObserver.NewFloat64UpDownCounterObserver` and +// returns the instrument, panicking if it encounters an error. +func (bm BatchObserverMust) NewFloat64UpDownCounterObserver(name string, oos ...InstrumentOption) Float64UpDownCounterObserver { + if inst, err := bm.batch.NewFloat64UpDownCounterObserver(name, oos...); err != nil { + panic(err) + } else { + return inst + } +} diff --git a/vendor/go.opentelemetry.io/otel/metric/metric_instrument.go b/vendor/go.opentelemetry.io/otel/metric/metric_instrument.go new file mode 100644 index 0000000000000..2da24c8f211ef --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/metric_instrument.go @@ -0,0 +1,464 @@ +// Copyright The OpenTelemetry 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 metric // import "go.opentelemetry.io/otel/metric" + +import ( + "context" + "errors" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric/number" + "go.opentelemetry.io/otel/metric/sdkapi" +) + +// ErrSDKReturnedNilImpl is returned when a new `MeterImpl` returns nil. +var ErrSDKReturnedNilImpl = errors.New("SDK returned a nil implementation") + +// Int64ObserverFunc is a type of callback that integral +// observers run. +type Int64ObserverFunc func(context.Context, Int64ObserverResult) + +// Float64ObserverFunc is a type of callback that floating point +// observers run. +type Float64ObserverFunc func(context.Context, Float64ObserverResult) + +// BatchObserverFunc is a callback argument for use with any +// Observer instrument that will be reported as a batch of +// observations. +type BatchObserverFunc func(context.Context, BatchObserverResult) + +// Int64ObserverResult is passed to an observer callback to capture +// observations for one asynchronous integer metric instrument. +type Int64ObserverResult struct { + instrument sdkapi.AsyncImpl + function func([]attribute.KeyValue, ...Observation) +} + +// Float64ObserverResult is passed to an observer callback to capture +// observations for one asynchronous floating point metric instrument. +type Float64ObserverResult struct { + instrument sdkapi.AsyncImpl + function func([]attribute.KeyValue, ...Observation) +} + +// BatchObserverResult is passed to a batch observer callback to +// capture observations for multiple asynchronous instruments. +type BatchObserverResult struct { + function func([]attribute.KeyValue, ...Observation) +} + +// Observe captures a single integer value from the associated +// instrument callback, with the given labels. +func (ir Int64ObserverResult) Observe(value int64, labels ...attribute.KeyValue) { + ir.function(labels, sdkapi.NewObservation(ir.instrument, number.NewInt64Number(value))) +} + +// Observe captures a single floating point value from the associated +// instrument callback, with the given labels. +func (fr Float64ObserverResult) Observe(value float64, labels ...attribute.KeyValue) { + fr.function(labels, sdkapi.NewObservation(fr.instrument, number.NewFloat64Number(value))) +} + +// Observe captures a multiple observations from the associated batch +// instrument callback, with the given labels. +func (br BatchObserverResult) Observe(labels []attribute.KeyValue, obs ...Observation) { + br.function(labels, obs...) +} + +var _ sdkapi.AsyncSingleRunner = (*Int64ObserverFunc)(nil) +var _ sdkapi.AsyncSingleRunner = (*Float64ObserverFunc)(nil) +var _ sdkapi.AsyncBatchRunner = (*BatchObserverFunc)(nil) + +// newInt64AsyncRunner returns a single-observer callback for integer Observer instruments. +func newInt64AsyncRunner(c Int64ObserverFunc) sdkapi.AsyncSingleRunner { + return &c +} + +// newFloat64AsyncRunner returns a single-observer callback for floating point Observer instruments. +func newFloat64AsyncRunner(c Float64ObserverFunc) sdkapi.AsyncSingleRunner { + return &c +} + +// newBatchAsyncRunner returns a batch-observer callback use with multiple Observer instruments. +func newBatchAsyncRunner(c BatchObserverFunc) sdkapi.AsyncBatchRunner { + return &c +} + +// AnyRunner implements AsyncRunner. +func (*Int64ObserverFunc) AnyRunner() {} + +// AnyRunner implements AsyncRunner. +func (*Float64ObserverFunc) AnyRunner() {} + +// AnyRunner implements AsyncRunner. +func (*BatchObserverFunc) AnyRunner() {} + +// Run implements AsyncSingleRunner. +func (i *Int64ObserverFunc) Run(ctx context.Context, impl sdkapi.AsyncImpl, function func([]attribute.KeyValue, ...Observation)) { + (*i)(ctx, Int64ObserverResult{ + instrument: impl, + function: function, + }) +} + +// Run implements AsyncSingleRunner. +func (f *Float64ObserverFunc) Run(ctx context.Context, impl sdkapi.AsyncImpl, function func([]attribute.KeyValue, ...Observation)) { + (*f)(ctx, Float64ObserverResult{ + instrument: impl, + function: function, + }) +} + +// Run implements AsyncBatchRunner. +func (b *BatchObserverFunc) Run(ctx context.Context, function func([]attribute.KeyValue, ...Observation)) { + (*b)(ctx, BatchObserverResult{ + function: function, + }) +} + +// wrapInt64GaugeObserverInstrument converts an AsyncImpl into Int64GaugeObserver. +func wrapInt64GaugeObserverInstrument(asyncInst sdkapi.AsyncImpl, err error) (Int64GaugeObserver, error) { + common, err := checkNewAsync(asyncInst, err) + return Int64GaugeObserver{asyncInstrument: common}, err +} + +// wrapFloat64GaugeObserverInstrument converts an AsyncImpl into Float64GaugeObserver. +func wrapFloat64GaugeObserverInstrument(asyncInst sdkapi.AsyncImpl, err error) (Float64GaugeObserver, error) { + common, err := checkNewAsync(asyncInst, err) + return Float64GaugeObserver{asyncInstrument: common}, err +} + +// wrapInt64CounterObserverInstrument converts an AsyncImpl into Int64CounterObserver. +func wrapInt64CounterObserverInstrument(asyncInst sdkapi.AsyncImpl, err error) (Int64CounterObserver, error) { + common, err := checkNewAsync(asyncInst, err) + return Int64CounterObserver{asyncInstrument: common}, err +} + +// wrapFloat64CounterObserverInstrument converts an AsyncImpl into Float64CounterObserver. +func wrapFloat64CounterObserverInstrument(asyncInst sdkapi.AsyncImpl, err error) (Float64CounterObserver, error) { + common, err := checkNewAsync(asyncInst, err) + return Float64CounterObserver{asyncInstrument: common}, err +} + +// wrapInt64UpDownCounterObserverInstrument converts an AsyncImpl into Int64UpDownCounterObserver. +func wrapInt64UpDownCounterObserverInstrument(asyncInst sdkapi.AsyncImpl, err error) (Int64UpDownCounterObserver, error) { + common, err := checkNewAsync(asyncInst, err) + return Int64UpDownCounterObserver{asyncInstrument: common}, err +} + +// wrapFloat64UpDownCounterObserverInstrument converts an AsyncImpl into Float64UpDownCounterObserver. +func wrapFloat64UpDownCounterObserverInstrument(asyncInst sdkapi.AsyncImpl, err error) (Float64UpDownCounterObserver, error) { + common, err := checkNewAsync(asyncInst, err) + return Float64UpDownCounterObserver{asyncInstrument: common}, err +} + +// BatchObserver represents an Observer callback that can report +// observations for multiple instruments. +type BatchObserver struct { + meter Meter + runner sdkapi.AsyncBatchRunner +} + +// Int64GaugeObserver is a metric that captures a set of int64 values at a +// point in time. +type Int64GaugeObserver struct { + asyncInstrument +} + +// Float64GaugeObserver is a metric that captures a set of float64 values +// at a point in time. +type Float64GaugeObserver struct { + asyncInstrument +} + +// Int64CounterObserver is a metric that captures a precomputed sum of +// int64 values at a point in time. +type Int64CounterObserver struct { + asyncInstrument +} + +// Float64CounterObserver is a metric that captures a precomputed sum of +// float64 values at a point in time. +type Float64CounterObserver struct { + asyncInstrument +} + +// Int64UpDownCounterObserver is a metric that captures a precomputed sum of +// int64 values at a point in time. +type Int64UpDownCounterObserver struct { + asyncInstrument +} + +// Float64UpDownCounterObserver is a metric that captures a precomputed sum of +// float64 values at a point in time. +type Float64UpDownCounterObserver struct { + asyncInstrument +} + +// Observation returns an Observation, a BatchObserverFunc +// argument, for an asynchronous integer instrument. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (i Int64GaugeObserver) Observation(v int64) Observation { + return sdkapi.NewObservation(i.instrument, number.NewInt64Number(v)) +} + +// Observation returns an Observation, a BatchObserverFunc +// argument, for an asynchronous integer instrument. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (f Float64GaugeObserver) Observation(v float64) Observation { + return sdkapi.NewObservation(f.instrument, number.NewFloat64Number(v)) +} + +// Observation returns an Observation, a BatchObserverFunc +// argument, for an asynchronous integer instrument. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (i Int64CounterObserver) Observation(v int64) Observation { + return sdkapi.NewObservation(i.instrument, number.NewInt64Number(v)) +} + +// Observation returns an Observation, a BatchObserverFunc +// argument, for an asynchronous integer instrument. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (f Float64CounterObserver) Observation(v float64) Observation { + return sdkapi.NewObservation(f.instrument, number.NewFloat64Number(v)) +} + +// Observation returns an Observation, a BatchObserverFunc +// argument, for an asynchronous integer instrument. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (i Int64UpDownCounterObserver) Observation(v int64) Observation { + return sdkapi.NewObservation(i.instrument, number.NewInt64Number(v)) +} + +// Observation returns an Observation, a BatchObserverFunc +// argument, for an asynchronous integer instrument. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (f Float64UpDownCounterObserver) Observation(v float64) Observation { + return sdkapi.NewObservation(f.instrument, number.NewFloat64Number(v)) +} + +// syncInstrument contains a SyncImpl. +type syncInstrument struct { + instrument sdkapi.SyncImpl +} + +// asyncInstrument contains a AsyncImpl. +type asyncInstrument struct { + instrument sdkapi.AsyncImpl +} + +// AsyncImpl implements AsyncImpl. +func (a asyncInstrument) AsyncImpl() sdkapi.AsyncImpl { + return a.instrument +} + +// SyncImpl returns the implementation object for synchronous instruments. +func (s syncInstrument) SyncImpl() sdkapi.SyncImpl { + return s.instrument +} + +func (s syncInstrument) float64Measurement(value float64) Measurement { + return sdkapi.NewMeasurement(s.instrument, number.NewFloat64Number(value)) +} + +func (s syncInstrument) int64Measurement(value int64) Measurement { + return sdkapi.NewMeasurement(s.instrument, number.NewInt64Number(value)) +} + +func (s syncInstrument) directRecord(ctx context.Context, number number.Number, labels []attribute.KeyValue) { + s.instrument.RecordOne(ctx, number, labels) +} + +// checkNewAsync receives an AsyncImpl and potential +// error, and returns the same types, checking for and ensuring that +// the returned interface is not nil. +func checkNewAsync(instrument sdkapi.AsyncImpl, err error) (asyncInstrument, error) { + if instrument == nil { + if err == nil { + err = ErrSDKReturnedNilImpl + } + instrument = sdkapi.NewNoopAsyncInstrument() + } + return asyncInstrument{ + instrument: instrument, + }, err +} + +// checkNewSync receives an SyncImpl and potential +// error, and returns the same types, checking for and ensuring that +// the returned interface is not nil. +func checkNewSync(instrument sdkapi.SyncImpl, err error) (syncInstrument, error) { + if instrument == nil { + if err == nil { + err = ErrSDKReturnedNilImpl + } + // Note: an alternate behavior would be to synthesize a new name + // or group all duplicately-named instruments of a certain type + // together and use a tag for the original name, e.g., + // name = 'invalid.counter.int64' + // label = 'original-name=duplicate-counter-name' + instrument = sdkapi.NewNoopSyncInstrument() + } + return syncInstrument{ + instrument: instrument, + }, err +} + +// wrapInt64CounterInstrument converts a SyncImpl into Int64Counter. +func wrapInt64CounterInstrument(syncInst sdkapi.SyncImpl, err error) (Int64Counter, error) { + common, err := checkNewSync(syncInst, err) + return Int64Counter{syncInstrument: common}, err +} + +// wrapFloat64CounterInstrument converts a SyncImpl into Float64Counter. +func wrapFloat64CounterInstrument(syncInst sdkapi.SyncImpl, err error) (Float64Counter, error) { + common, err := checkNewSync(syncInst, err) + return Float64Counter{syncInstrument: common}, err +} + +// wrapInt64UpDownCounterInstrument converts a SyncImpl into Int64UpDownCounter. +func wrapInt64UpDownCounterInstrument(syncInst sdkapi.SyncImpl, err error) (Int64UpDownCounter, error) { + common, err := checkNewSync(syncInst, err) + return Int64UpDownCounter{syncInstrument: common}, err +} + +// wrapFloat64UpDownCounterInstrument converts a SyncImpl into Float64UpDownCounter. +func wrapFloat64UpDownCounterInstrument(syncInst sdkapi.SyncImpl, err error) (Float64UpDownCounter, error) { + common, err := checkNewSync(syncInst, err) + return Float64UpDownCounter{syncInstrument: common}, err +} + +// wrapInt64HistogramInstrument converts a SyncImpl into Int64Histogram. +func wrapInt64HistogramInstrument(syncInst sdkapi.SyncImpl, err error) (Int64Histogram, error) { + common, err := checkNewSync(syncInst, err) + return Int64Histogram{syncInstrument: common}, err +} + +// wrapFloat64HistogramInstrument converts a SyncImpl into Float64Histogram. +func wrapFloat64HistogramInstrument(syncInst sdkapi.SyncImpl, err error) (Float64Histogram, error) { + common, err := checkNewSync(syncInst, err) + return Float64Histogram{syncInstrument: common}, err +} + +// Float64Counter is a metric that accumulates float64 values. +type Float64Counter struct { + syncInstrument +} + +// Int64Counter is a metric that accumulates int64 values. +type Int64Counter struct { + syncInstrument +} + +// Measurement creates a Measurement object to use with batch +// recording. +func (c Float64Counter) Measurement(value float64) Measurement { + return c.float64Measurement(value) +} + +// Measurement creates a Measurement object to use with batch +// recording. +func (c Int64Counter) Measurement(value int64) Measurement { + return c.int64Measurement(value) +} + +// Add adds the value to the counter's sum. The labels should contain +// the keys and values to be associated with this value. +func (c Float64Counter) Add(ctx context.Context, value float64, labels ...attribute.KeyValue) { + c.directRecord(ctx, number.NewFloat64Number(value), labels) +} + +// Add adds the value to the counter's sum. The labels should contain +// the keys and values to be associated with this value. +func (c Int64Counter) Add(ctx context.Context, value int64, labels ...attribute.KeyValue) { + c.directRecord(ctx, number.NewInt64Number(value), labels) +} + +// Float64UpDownCounter is a metric instrument that sums floating +// point values. +type Float64UpDownCounter struct { + syncInstrument +} + +// Int64UpDownCounter is a metric instrument that sums integer values. +type Int64UpDownCounter struct { + syncInstrument +} + +// Measurement creates a Measurement object to use with batch +// recording. +func (c Float64UpDownCounter) Measurement(value float64) Measurement { + return c.float64Measurement(value) +} + +// Measurement creates a Measurement object to use with batch +// recording. +func (c Int64UpDownCounter) Measurement(value int64) Measurement { + return c.int64Measurement(value) +} + +// Add adds the value to the counter's sum. The labels should contain +// the keys and values to be associated with this value. +func (c Float64UpDownCounter) Add(ctx context.Context, value float64, labels ...attribute.KeyValue) { + c.directRecord(ctx, number.NewFloat64Number(value), labels) +} + +// Add adds the value to the counter's sum. The labels should contain +// the keys and values to be associated with this value. +func (c Int64UpDownCounter) Add(ctx context.Context, value int64, labels ...attribute.KeyValue) { + c.directRecord(ctx, number.NewInt64Number(value), labels) +} + +// Float64Histogram is a metric that records float64 values. +type Float64Histogram struct { + syncInstrument +} + +// Int64Histogram is a metric that records int64 values. +type Int64Histogram struct { + syncInstrument +} + +// Measurement creates a Measurement object to use with batch +// recording. +func (c Float64Histogram) Measurement(value float64) Measurement { + return c.float64Measurement(value) +} + +// Measurement creates a Measurement object to use with batch +// recording. +func (c Int64Histogram) Measurement(value int64) Measurement { + return c.int64Measurement(value) +} + +// Record adds a new value to the list of Histogram's records. The +// labels should contain the keys and values to be associated with +// this value. +func (c Float64Histogram) Record(ctx context.Context, value float64, labels ...attribute.KeyValue) { + c.directRecord(ctx, number.NewFloat64Number(value), labels) +} + +// Record adds a new value to the Histogram's distribution. The +// labels should contain the keys and values to be associated with +// this value. +func (c Int64Histogram) Record(ctx context.Context, value int64, labels ...attribute.KeyValue) { + c.directRecord(ctx, number.NewInt64Number(value), labels) +} diff --git a/vendor/go.opentelemetry.io/otel/metric/noop.go b/vendor/go.opentelemetry.io/otel/metric/noop.go index f38619e39abcd..37c653f51a1e2 100644 --- a/vendor/go.opentelemetry.io/otel/metric/noop.go +++ b/vendor/go.opentelemetry.io/otel/metric/noop.go @@ -14,130 +14,17 @@ package metric // import "go.opentelemetry.io/otel/metric" -import ( - "context" - - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/metric/instrument" -) +type noopMeterProvider struct{} -// NewNoopMeterProvider creates a MeterProvider that does not record any metrics. +// NewNoopMeterProvider returns an implementation of MeterProvider that +// performs no operations. The Meter and Instrument created from the returned +// MeterProvider also perform no operations. func NewNoopMeterProvider() MeterProvider { return noopMeterProvider{} } -type noopMeterProvider struct{} - -func (noopMeterProvider) Meter(string, ...MeterOption) Meter { - return noopMeter{} -} - -// NewNoopMeter creates a Meter that does not record any metrics. -func NewNoopMeter() Meter { - return noopMeter{} -} - -type noopMeter struct{} - -func (noopMeter) Int64Counter(string, ...instrument.Int64Option) (instrument.Int64Counter, error) { - return nonrecordingSyncInt64Instrument{}, nil -} - -func (noopMeter) Int64UpDownCounter(string, ...instrument.Int64Option) (instrument.Int64UpDownCounter, error) { - return nonrecordingSyncInt64Instrument{}, nil -} - -func (noopMeter) Int64Histogram(string, ...instrument.Int64Option) (instrument.Int64Histogram, error) { - return nonrecordingSyncInt64Instrument{}, nil -} - -func (noopMeter) Int64ObservableCounter(string, ...instrument.Int64ObserverOption) (instrument.Int64ObservableCounter, error) { - return nonrecordingAsyncInt64Instrument{}, nil -} - -func (noopMeter) Int64ObservableUpDownCounter(string, ...instrument.Int64ObserverOption) (instrument.Int64ObservableUpDownCounter, error) { - return nonrecordingAsyncInt64Instrument{}, nil -} - -func (noopMeter) Int64ObservableGauge(string, ...instrument.Int64ObserverOption) (instrument.Int64ObservableGauge, error) { - return nonrecordingAsyncInt64Instrument{}, nil -} - -func (noopMeter) Float64Counter(string, ...instrument.Float64Option) (instrument.Float64Counter, error) { - return nonrecordingSyncFloat64Instrument{}, nil -} - -func (noopMeter) Float64UpDownCounter(string, ...instrument.Float64Option) (instrument.Float64UpDownCounter, error) { - return nonrecordingSyncFloat64Instrument{}, nil -} - -func (noopMeter) Float64Histogram(string, ...instrument.Float64Option) (instrument.Float64Histogram, error) { - return nonrecordingSyncFloat64Instrument{}, nil -} - -func (noopMeter) Float64ObservableCounter(string, ...instrument.Float64ObserverOption) (instrument.Float64ObservableCounter, error) { - return nonrecordingAsyncFloat64Instrument{}, nil -} - -func (noopMeter) Float64ObservableUpDownCounter(string, ...instrument.Float64ObserverOption) (instrument.Float64ObservableUpDownCounter, error) { - return nonrecordingAsyncFloat64Instrument{}, nil -} - -func (noopMeter) Float64ObservableGauge(string, ...instrument.Float64ObserverOption) (instrument.Float64ObservableGauge, error) { - return nonrecordingAsyncFloat64Instrument{}, nil -} - -// RegisterCallback creates a register callback that does not record any metrics. -func (noopMeter) RegisterCallback(Callback, ...instrument.Asynchronous) (Registration, error) { - return noopReg{}, nil -} - -type noopReg struct{} - -func (noopReg) Unregister() error { return nil } - -type nonrecordingAsyncFloat64Instrument struct { - instrument.Float64Observable -} - -var ( - _ instrument.Float64ObservableCounter = nonrecordingAsyncFloat64Instrument{} - _ instrument.Float64ObservableUpDownCounter = nonrecordingAsyncFloat64Instrument{} - _ instrument.Float64ObservableGauge = nonrecordingAsyncFloat64Instrument{} -) - -type nonrecordingAsyncInt64Instrument struct { - instrument.Int64Observable -} - -var ( - _ instrument.Int64ObservableCounter = nonrecordingAsyncInt64Instrument{} - _ instrument.Int64ObservableUpDownCounter = nonrecordingAsyncInt64Instrument{} - _ instrument.Int64ObservableGauge = nonrecordingAsyncInt64Instrument{} -) +var _ MeterProvider = noopMeterProvider{} -type nonrecordingSyncFloat64Instrument struct { - instrument.Synchronous +func (noopMeterProvider) Meter(instrumentationName string, opts ...MeterOption) Meter { + return Meter{} } - -var ( - _ instrument.Float64Counter = nonrecordingSyncFloat64Instrument{} - _ instrument.Float64UpDownCounter = nonrecordingSyncFloat64Instrument{} - _ instrument.Float64Histogram = nonrecordingSyncFloat64Instrument{} -) - -func (nonrecordingSyncFloat64Instrument) Add(context.Context, float64, ...attribute.KeyValue) {} -func (nonrecordingSyncFloat64Instrument) Record(context.Context, float64, ...attribute.KeyValue) {} - -type nonrecordingSyncInt64Instrument struct { - instrument.Synchronous -} - -var ( - _ instrument.Int64Counter = nonrecordingSyncInt64Instrument{} - _ instrument.Int64UpDownCounter = nonrecordingSyncInt64Instrument{} - _ instrument.Int64Histogram = nonrecordingSyncInt64Instrument{} -) - -func (nonrecordingSyncInt64Instrument) Add(context.Context, int64, ...attribute.KeyValue) {} -func (nonrecordingSyncInt64Instrument) Record(context.Context, int64, ...attribute.KeyValue) {} diff --git a/vendor/go.opentelemetry.io/otel/metric/number/doc.go b/vendor/go.opentelemetry.io/otel/metric/number/doc.go new file mode 100644 index 0000000000000..0649ff875e70a --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/number/doc.go @@ -0,0 +1,23 @@ +// Copyright The OpenTelemetry 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 number provides a number abstraction for instruments that +either support int64 or float64 input values. + +This package is currently in a pre-GA phase. Backwards incompatible changes +may be introduced in subsequent minor version releases as we work to track the +evolving OpenTelemetry specification and user feedback. +*/ +package number // import "go.opentelemetry.io/otel/metric/number" diff --git a/vendor/go.opentelemetry.io/otel/metric/number/kind_string.go b/vendor/go.opentelemetry.io/otel/metric/number/kind_string.go new file mode 100644 index 0000000000000..6288c7ea295f7 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/number/kind_string.go @@ -0,0 +1,24 @@ +// Code generated by "stringer -type=Kind"; DO NOT EDIT. + +package number + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[Int64Kind-0] + _ = x[Float64Kind-1] +} + +const _Kind_name = "Int64KindFloat64Kind" + +var _Kind_index = [...]uint8{0, 9, 20} + +func (i Kind) String() string { + if i < 0 || i >= Kind(len(_Kind_index)-1) { + return "Kind(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _Kind_name[_Kind_index[i]:_Kind_index[i+1]] +} diff --git a/vendor/go.opentelemetry.io/otel/metric/number/number.go b/vendor/go.opentelemetry.io/otel/metric/number/number.go new file mode 100644 index 0000000000000..3ec95e2014d7f --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/number/number.go @@ -0,0 +1,538 @@ +// Copyright The OpenTelemetry 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 number // import "go.opentelemetry.io/otel/metric/number" + +//go:generate stringer -type=Kind + +import ( + "fmt" + "math" + "sync/atomic" + + "go.opentelemetry.io/otel/internal" +) + +// Kind describes the data type of the Number. +type Kind int8 + +const ( + // Int64Kind means that the Number stores int64. + Int64Kind Kind = iota + // Float64Kind means that the Number stores float64. + Float64Kind +) + +// Zero returns a zero value for a given Kind +func (k Kind) Zero() Number { + switch k { + case Int64Kind: + return NewInt64Number(0) + case Float64Kind: + return NewFloat64Number(0.) + default: + return Number(0) + } +} + +// Minimum returns the minimum representable value +// for a given Kind +func (k Kind) Minimum() Number { + switch k { + case Int64Kind: + return NewInt64Number(math.MinInt64) + case Float64Kind: + return NewFloat64Number(-1. * math.MaxFloat64) + default: + return Number(0) + } +} + +// Maximum returns the maximum representable value +// for a given Kind +func (k Kind) Maximum() Number { + switch k { + case Int64Kind: + return NewInt64Number(math.MaxInt64) + case Float64Kind: + return NewFloat64Number(math.MaxFloat64) + default: + return Number(0) + } +} + +// Number represents either an integral or a floating point value. It +// needs to be accompanied with a source of Kind that describes +// the actual type of the value stored within Number. +type Number uint64 + +// - constructors + +// NewNumberFromRaw creates a new Number from a raw value. +func NewNumberFromRaw(r uint64) Number { + return Number(r) +} + +// NewInt64Number creates an integral Number. +func NewInt64Number(i int64) Number { + return NewNumberFromRaw(internal.Int64ToRaw(i)) +} + +// NewFloat64Number creates a floating point Number. +func NewFloat64Number(f float64) Number { + return NewNumberFromRaw(internal.Float64ToRaw(f)) +} + +// NewNumberSignChange returns a number with the same magnitude and +// the opposite sign. `kind` must describe the kind of number in `nn`. +func NewNumberSignChange(kind Kind, nn Number) Number { + switch kind { + case Int64Kind: + return NewInt64Number(-nn.AsInt64()) + case Float64Kind: + return NewFloat64Number(-nn.AsFloat64()) + } + return nn +} + +// - as x + +// AsNumber gets the Number. +func (n *Number) AsNumber() Number { + return *n +} + +// AsRaw gets the uninterpreted raw value. Might be useful for some +// atomic operations. +func (n *Number) AsRaw() uint64 { + return uint64(*n) +} + +// AsInt64 assumes that the value contains an int64 and returns it as +// such. +func (n *Number) AsInt64() int64 { + return internal.RawToInt64(n.AsRaw()) +} + +// AsFloat64 assumes that the measurement value contains a float64 and +// returns it as such. +func (n *Number) AsFloat64() float64 { + return internal.RawToFloat64(n.AsRaw()) +} + +// - as x atomic + +// AsNumberAtomic gets the Number atomically. +func (n *Number) AsNumberAtomic() Number { + return NewNumberFromRaw(n.AsRawAtomic()) +} + +// AsRawAtomic gets the uninterpreted raw value atomically. Might be +// useful for some atomic operations. +func (n *Number) AsRawAtomic() uint64 { + return atomic.LoadUint64(n.AsRawPtr()) +} + +// AsInt64Atomic assumes that the number contains an int64 and returns +// it as such atomically. +func (n *Number) AsInt64Atomic() int64 { + return atomic.LoadInt64(n.AsInt64Ptr()) +} + +// AsFloat64Atomic assumes that the measurement value contains a +// float64 and returns it as such atomically. +func (n *Number) AsFloat64Atomic() float64 { + return internal.RawToFloat64(n.AsRawAtomic()) +} + +// - as x ptr + +// AsRawPtr gets the pointer to the raw, uninterpreted raw +// value. Might be useful for some atomic operations. +func (n *Number) AsRawPtr() *uint64 { + return (*uint64)(n) +} + +// AsInt64Ptr assumes that the number contains an int64 and returns a +// pointer to it. +func (n *Number) AsInt64Ptr() *int64 { + return internal.RawPtrToInt64Ptr(n.AsRawPtr()) +} + +// AsFloat64Ptr assumes that the number contains a float64 and returns a +// pointer to it. +func (n *Number) AsFloat64Ptr() *float64 { + return internal.RawPtrToFloat64Ptr(n.AsRawPtr()) +} + +// - coerce + +// CoerceToInt64 casts the number to int64. May result in +// data/precision loss. +func (n *Number) CoerceToInt64(kind Kind) int64 { + switch kind { + case Int64Kind: + return n.AsInt64() + case Float64Kind: + return int64(n.AsFloat64()) + default: + // you get what you deserve + return 0 + } +} + +// CoerceToFloat64 casts the number to float64. May result in +// data/precision loss. +func (n *Number) CoerceToFloat64(kind Kind) float64 { + switch kind { + case Int64Kind: + return float64(n.AsInt64()) + case Float64Kind: + return n.AsFloat64() + default: + // you get what you deserve + return 0 + } +} + +// - set + +// SetNumber sets the number to the passed number. Both should be of +// the same kind. +func (n *Number) SetNumber(nn Number) { + *n.AsRawPtr() = nn.AsRaw() +} + +// SetRaw sets the number to the passed raw value. Both number and the +// raw number should represent the same kind. +func (n *Number) SetRaw(r uint64) { + *n.AsRawPtr() = r +} + +// SetInt64 assumes that the number contains an int64 and sets it to +// the passed value. +func (n *Number) SetInt64(i int64) { + *n.AsInt64Ptr() = i +} + +// SetFloat64 assumes that the number contains a float64 and sets it +// to the passed value. +func (n *Number) SetFloat64(f float64) { + *n.AsFloat64Ptr() = f +} + +// - set atomic + +// SetNumberAtomic sets the number to the passed number +// atomically. Both should be of the same kind. +func (n *Number) SetNumberAtomic(nn Number) { + atomic.StoreUint64(n.AsRawPtr(), nn.AsRaw()) +} + +// SetRawAtomic sets the number to the passed raw value +// atomically. Both number and the raw number should represent the +// same kind. +func (n *Number) SetRawAtomic(r uint64) { + atomic.StoreUint64(n.AsRawPtr(), r) +} + +// SetInt64Atomic assumes that the number contains an int64 and sets +// it to the passed value atomically. +func (n *Number) SetInt64Atomic(i int64) { + atomic.StoreInt64(n.AsInt64Ptr(), i) +} + +// SetFloat64Atomic assumes that the number contains a float64 and +// sets it to the passed value atomically. +func (n *Number) SetFloat64Atomic(f float64) { + atomic.StoreUint64(n.AsRawPtr(), internal.Float64ToRaw(f)) +} + +// - swap + +// SwapNumber sets the number to the passed number and returns the old +// number. Both this number and the passed number should be of the +// same kind. +func (n *Number) SwapNumber(nn Number) Number { + old := *n + n.SetNumber(nn) + return old +} + +// SwapRaw sets the number to the passed raw value and returns the old +// raw value. Both number and the raw number should represent the same +// kind. +func (n *Number) SwapRaw(r uint64) uint64 { + old := n.AsRaw() + n.SetRaw(r) + return old +} + +// SwapInt64 assumes that the number contains an int64, sets it to the +// passed value and returns the old int64 value. +func (n *Number) SwapInt64(i int64) int64 { + old := n.AsInt64() + n.SetInt64(i) + return old +} + +// SwapFloat64 assumes that the number contains an float64, sets it to +// the passed value and returns the old float64 value. +func (n *Number) SwapFloat64(f float64) float64 { + old := n.AsFloat64() + n.SetFloat64(f) + return old +} + +// - swap atomic + +// SwapNumberAtomic sets the number to the passed number and returns +// the old number atomically. Both this number and the passed number +// should be of the same kind. +func (n *Number) SwapNumberAtomic(nn Number) Number { + return NewNumberFromRaw(atomic.SwapUint64(n.AsRawPtr(), nn.AsRaw())) +} + +// SwapRawAtomic sets the number to the passed raw value and returns +// the old raw value atomically. Both number and the raw number should +// represent the same kind. +func (n *Number) SwapRawAtomic(r uint64) uint64 { + return atomic.SwapUint64(n.AsRawPtr(), r) +} + +// SwapInt64Atomic assumes that the number contains an int64, sets it +// to the passed value and returns the old int64 value atomically. +func (n *Number) SwapInt64Atomic(i int64) int64 { + return atomic.SwapInt64(n.AsInt64Ptr(), i) +} + +// SwapFloat64Atomic assumes that the number contains an float64, sets +// it to the passed value and returns the old float64 value +// atomically. +func (n *Number) SwapFloat64Atomic(f float64) float64 { + return internal.RawToFloat64(atomic.SwapUint64(n.AsRawPtr(), internal.Float64ToRaw(f))) +} + +// - add + +// AddNumber assumes that this and the passed number are of the passed +// kind and adds the passed number to this number. +func (n *Number) AddNumber(kind Kind, nn Number) { + switch kind { + case Int64Kind: + n.AddInt64(nn.AsInt64()) + case Float64Kind: + n.AddFloat64(nn.AsFloat64()) + } +} + +// AddRaw assumes that this number and the passed raw value are of the +// passed kind and adds the passed raw value to this number. +func (n *Number) AddRaw(kind Kind, r uint64) { + n.AddNumber(kind, NewNumberFromRaw(r)) +} + +// AddInt64 assumes that the number contains an int64 and adds the +// passed int64 to it. +func (n *Number) AddInt64(i int64) { + *n.AsInt64Ptr() += i +} + +// AddFloat64 assumes that the number contains a float64 and adds the +// passed float64 to it. +func (n *Number) AddFloat64(f float64) { + *n.AsFloat64Ptr() += f +} + +// - add atomic + +// AddNumberAtomic assumes that this and the passed number are of the +// passed kind and adds the passed number to this number atomically. +func (n *Number) AddNumberAtomic(kind Kind, nn Number) { + switch kind { + case Int64Kind: + n.AddInt64Atomic(nn.AsInt64()) + case Float64Kind: + n.AddFloat64Atomic(nn.AsFloat64()) + } +} + +// AddRawAtomic assumes that this number and the passed raw value are +// of the passed kind and adds the passed raw value to this number +// atomically. +func (n *Number) AddRawAtomic(kind Kind, r uint64) { + n.AddNumberAtomic(kind, NewNumberFromRaw(r)) +} + +// AddInt64Atomic assumes that the number contains an int64 and adds +// the passed int64 to it atomically. +func (n *Number) AddInt64Atomic(i int64) { + atomic.AddInt64(n.AsInt64Ptr(), i) +} + +// AddFloat64Atomic assumes that the number contains a float64 and +// adds the passed float64 to it atomically. +func (n *Number) AddFloat64Atomic(f float64) { + for { + o := n.AsFloat64Atomic() + if n.CompareAndSwapFloat64(o, o+f) { + break + } + } +} + +// - compare and swap (atomic only) + +// CompareAndSwapNumber does the atomic CAS operation on this +// number. This number and passed old and new numbers should be of the +// same kind. +func (n *Number) CompareAndSwapNumber(on, nn Number) bool { + return atomic.CompareAndSwapUint64(n.AsRawPtr(), on.AsRaw(), nn.AsRaw()) +} + +// CompareAndSwapRaw does the atomic CAS operation on this +// number. This number and passed old and new raw values should be of +// the same kind. +func (n *Number) CompareAndSwapRaw(or, nr uint64) bool { + return atomic.CompareAndSwapUint64(n.AsRawPtr(), or, nr) +} + +// CompareAndSwapInt64 assumes that this number contains an int64 and +// does the atomic CAS operation on it. +func (n *Number) CompareAndSwapInt64(oi, ni int64) bool { + return atomic.CompareAndSwapInt64(n.AsInt64Ptr(), oi, ni) +} + +// CompareAndSwapFloat64 assumes that this number contains a float64 and +// does the atomic CAS operation on it. +func (n *Number) CompareAndSwapFloat64(of, nf float64) bool { + return atomic.CompareAndSwapUint64(n.AsRawPtr(), internal.Float64ToRaw(of), internal.Float64ToRaw(nf)) +} + +// - compare + +// CompareNumber compares two Numbers given their kind. Both numbers +// should have the same kind. This returns: +// 0 if the numbers are equal +// -1 if the subject `n` is less than the argument `nn` +// +1 if the subject `n` is greater than the argument `nn` +func (n *Number) CompareNumber(kind Kind, nn Number) int { + switch kind { + case Int64Kind: + return n.CompareInt64(nn.AsInt64()) + case Float64Kind: + return n.CompareFloat64(nn.AsFloat64()) + default: + // you get what you deserve + return 0 + } +} + +// CompareRaw compares two numbers, where one is input as a raw +// uint64, interpreting both values as a `kind` of number. +func (n *Number) CompareRaw(kind Kind, r uint64) int { + return n.CompareNumber(kind, NewNumberFromRaw(r)) +} + +// CompareInt64 assumes that the Number contains an int64 and performs +// a comparison between the value and the other value. It returns the +// typical result of the compare function: -1 if the value is less +// than the other, 0 if both are equal, 1 if the value is greater than +// the other. +func (n *Number) CompareInt64(i int64) int { + this := n.AsInt64() + if this < i { + return -1 + } else if this > i { + return 1 + } + return 0 +} + +// CompareFloat64 assumes that the Number contains a float64 and +// performs a comparison between the value and the other value. It +// returns the typical result of the compare function: -1 if the value +// is less than the other, 0 if both are equal, 1 if the value is +// greater than the other. +// +// Do not compare NaN values. +func (n *Number) CompareFloat64(f float64) int { + this := n.AsFloat64() + if this < f { + return -1 + } else if this > f { + return 1 + } + return 0 +} + +// - relations to zero + +// IsPositive returns true if the actual value is greater than zero. +func (n *Number) IsPositive(kind Kind) bool { + return n.compareWithZero(kind) > 0 +} + +// IsNegative returns true if the actual value is less than zero. +func (n *Number) IsNegative(kind Kind) bool { + return n.compareWithZero(kind) < 0 +} + +// IsZero returns true if the actual value is equal to zero. +func (n *Number) IsZero(kind Kind) bool { + return n.compareWithZero(kind) == 0 +} + +// - misc + +// Emit returns a string representation of the raw value of the +// Number. A %d is used for integral values, %f for floating point +// values. +func (n *Number) Emit(kind Kind) string { + switch kind { + case Int64Kind: + return fmt.Sprintf("%d", n.AsInt64()) + case Float64Kind: + return fmt.Sprintf("%f", n.AsFloat64()) + default: + return "" + } +} + +// AsInterface returns the number as an interface{}, typically used +// for Kind-correct JSON conversion. +func (n *Number) AsInterface(kind Kind) interface{} { + switch kind { + case Int64Kind: + return n.AsInt64() + case Float64Kind: + return n.AsFloat64() + default: + return math.NaN() + } +} + +// - private stuff + +func (n *Number) compareWithZero(kind Kind) int { + switch kind { + case Int64Kind: + return n.CompareInt64(0) + case Float64Kind: + return n.CompareFloat64(0.) + default: + // you get what you deserve + return 0 + } +} diff --git a/vendor/go.opentelemetry.io/otel/metric/sdkapi/descriptor.go b/vendor/go.opentelemetry.io/otel/metric/sdkapi/descriptor.go new file mode 100644 index 0000000000000..14eb0532e45a9 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/sdkapi/descriptor.go @@ -0,0 +1,70 @@ +// Copyright The OpenTelemetry 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 sdkapi // import "go.opentelemetry.io/otel/metric/sdkapi" + +import ( + "go.opentelemetry.io/otel/metric/number" + "go.opentelemetry.io/otel/metric/unit" +) + +// Descriptor contains all the settings that describe an instrument, +// including its name, metric kind, number kind, and the configurable +// options. +type Descriptor struct { + name string + instrumentKind InstrumentKind + numberKind number.Kind + description string + unit unit.Unit +} + +// NewDescriptor returns a Descriptor with the given contents. +func NewDescriptor(name string, ikind InstrumentKind, nkind number.Kind, description string, unit unit.Unit) Descriptor { + return Descriptor{ + name: name, + instrumentKind: ikind, + numberKind: nkind, + description: description, + unit: unit, + } +} + +// Name returns the metric instrument's name. +func (d Descriptor) Name() string { + return d.name +} + +// InstrumentKind returns the specific kind of instrument. +func (d Descriptor) InstrumentKind() InstrumentKind { + return d.instrumentKind +} + +// Description provides a human-readable description of the metric +// instrument. +func (d Descriptor) Description() string { + return d.description +} + +// Unit describes the units of the metric instrument. Unitless +// metrics return the empty string. +func (d Descriptor) Unit() unit.Unit { + return d.unit +} + +// NumberKind returns whether this instrument is declared over int64, +// float64, or uint64 values. +func (d Descriptor) NumberKind() number.Kind { + return d.numberKind +} diff --git a/vendor/go.opentelemetry.io/otel/metric/sdkapi/instrumentkind.go b/vendor/go.opentelemetry.io/otel/metric/sdkapi/instrumentkind.go new file mode 100644 index 0000000000000..64aa5ead123cd --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/sdkapi/instrumentkind.go @@ -0,0 +1,80 @@ +// Copyright The OpenTelemetry 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. + +//go:generate stringer -type=InstrumentKind + +package sdkapi // import "go.opentelemetry.io/otel/metric/sdkapi" + +// InstrumentKind describes the kind of instrument. +type InstrumentKind int8 + +const ( + // HistogramInstrumentKind indicates a Histogram instrument. + HistogramInstrumentKind InstrumentKind = iota + // GaugeObserverInstrumentKind indicates an GaugeObserver instrument. + GaugeObserverInstrumentKind + + // CounterInstrumentKind indicates a Counter instrument. + CounterInstrumentKind + // UpDownCounterInstrumentKind indicates a UpDownCounter instrument. + UpDownCounterInstrumentKind + + // CounterObserverInstrumentKind indicates a CounterObserver instrument. + CounterObserverInstrumentKind + // UpDownCounterObserverInstrumentKind indicates a UpDownCounterObserver + // instrument. + UpDownCounterObserverInstrumentKind +) + +// Synchronous returns whether this is a synchronous kind of instrument. +func (k InstrumentKind) Synchronous() bool { + switch k { + case CounterInstrumentKind, UpDownCounterInstrumentKind, HistogramInstrumentKind: + return true + } + return false +} + +// Asynchronous returns whether this is an asynchronous kind of instrument. +func (k InstrumentKind) Asynchronous() bool { + return !k.Synchronous() +} + +// Adding returns whether this kind of instrument adds its inputs (as opposed to Grouping). +func (k InstrumentKind) Adding() bool { + switch k { + case CounterInstrumentKind, UpDownCounterInstrumentKind, CounterObserverInstrumentKind, UpDownCounterObserverInstrumentKind: + return true + } + return false +} + +// Grouping returns whether this kind of instrument groups its inputs (as opposed to Adding). +func (k InstrumentKind) Grouping() bool { + return !k.Adding() +} + +// Monotonic returns whether this kind of instrument exposes a non-decreasing sum. +func (k InstrumentKind) Monotonic() bool { + switch k { + case CounterInstrumentKind, CounterObserverInstrumentKind: + return true + } + return false +} + +// PrecomputedSum returns whether this kind of instrument receives precomputed sums. +func (k InstrumentKind) PrecomputedSum() bool { + return k.Adding() && k.Asynchronous() +} diff --git a/vendor/go.opentelemetry.io/otel/metric/sdkapi/instrumentkind_string.go b/vendor/go.opentelemetry.io/otel/metric/sdkapi/instrumentkind_string.go new file mode 100644 index 0000000000000..3a2e79d823ef7 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/sdkapi/instrumentkind_string.go @@ -0,0 +1,28 @@ +// Code generated by "stringer -type=InstrumentKind"; DO NOT EDIT. + +package sdkapi + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[HistogramInstrumentKind-0] + _ = x[GaugeObserverInstrumentKind-1] + _ = x[CounterInstrumentKind-2] + _ = x[UpDownCounterInstrumentKind-3] + _ = x[CounterObserverInstrumentKind-4] + _ = x[UpDownCounterObserverInstrumentKind-5] +} + +const _InstrumentKind_name = "HistogramInstrumentKindGaugeObserverInstrumentKindCounterInstrumentKindUpDownCounterInstrumentKindCounterObserverInstrumentKindUpDownCounterObserverInstrumentKind" + +var _InstrumentKind_index = [...]uint8{0, 23, 50, 71, 98, 127, 162} + +func (i InstrumentKind) String() string { + if i < 0 || i >= InstrumentKind(len(_InstrumentKind_index)-1) { + return "InstrumentKind(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _InstrumentKind_name[_InstrumentKind_index[i]:_InstrumentKind_index[i+1]] +} diff --git a/vendor/go.opentelemetry.io/otel/metric/sdkapi/noop.go b/vendor/go.opentelemetry.io/otel/metric/sdkapi/noop.go new file mode 100644 index 0000000000000..f22895dae6fdb --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/sdkapi/noop.go @@ -0,0 +1,66 @@ +// Copyright The OpenTelemetry 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 sdkapi // import "go.opentelemetry.io/otel/metric/sdkapi" + +import ( + "context" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric/number" +) + +type noopInstrument struct { + descriptor Descriptor +} +type noopSyncInstrument struct{ noopInstrument } +type noopAsyncInstrument struct{ noopInstrument } + +var _ SyncImpl = noopSyncInstrument{} +var _ AsyncImpl = noopAsyncInstrument{} + +// NewNoopSyncInstrument returns a No-op implementation of the +// synchronous instrument interface. +func NewNoopSyncInstrument() SyncImpl { + return noopSyncInstrument{ + noopInstrument{ + descriptor: Descriptor{ + instrumentKind: CounterInstrumentKind, + }, + }, + } +} + +// NewNoopAsyncInstrument returns a No-op implementation of the +// asynchronous instrument interface. +func NewNoopAsyncInstrument() AsyncImpl { + return noopAsyncInstrument{ + noopInstrument{ + descriptor: Descriptor{ + instrumentKind: CounterObserverInstrumentKind, + }, + }, + } +} + +func (noopInstrument) Implementation() interface{} { + return nil +} + +func (n noopInstrument) Descriptor() Descriptor { + return n.descriptor +} + +func (noopSyncInstrument) RecordOne(context.Context, number.Number, []attribute.KeyValue) { +} diff --git a/vendor/go.opentelemetry.io/otel/metric/sdkapi/sdkapi.go b/vendor/go.opentelemetry.io/otel/metric/sdkapi/sdkapi.go new file mode 100644 index 0000000000000..36836364bdceb --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/sdkapi/sdkapi.go @@ -0,0 +1,159 @@ +// Copyright The OpenTelemetry 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 sdkapi // import "go.opentelemetry.io/otel/metric/sdkapi" + +import ( + "context" + + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/metric/number" +) + +// MeterImpl is the interface an SDK must implement to supply a Meter +// implementation. +type MeterImpl interface { + // RecordBatch atomically records a batch of measurements. + RecordBatch(ctx context.Context, labels []attribute.KeyValue, measurement ...Measurement) + + // NewSyncInstrument returns a newly constructed + // synchronous instrument implementation or an error, should + // one occur. + NewSyncInstrument(descriptor Descriptor) (SyncImpl, error) + + // NewAsyncInstrument returns a newly constructed + // asynchronous instrument implementation or an error, should + // one occur. + NewAsyncInstrument( + descriptor Descriptor, + runner AsyncRunner, + ) (AsyncImpl, error) +} + +// InstrumentImpl is a common interface for synchronous and +// asynchronous instruments. +type InstrumentImpl interface { + // Implementation returns the underlying implementation of the + // instrument, which allows the implementation to gain access + // to its own representation especially from a `Measurement`. + Implementation() interface{} + + // Descriptor returns a copy of the instrument's Descriptor. + Descriptor() Descriptor +} + +// SyncImpl is the implementation-level interface to a generic +// synchronous instrument (e.g., Histogram and Counter instruments). +type SyncImpl interface { + InstrumentImpl + + // RecordOne captures a single synchronous metric event. + RecordOne(ctx context.Context, number number.Number, labels []attribute.KeyValue) +} + +// AsyncImpl is an implementation-level interface to an +// asynchronous instrument (e.g., Observer instruments). +type AsyncImpl interface { + InstrumentImpl +} + +// AsyncRunner is expected to convert into an AsyncSingleRunner or an +// AsyncBatchRunner. SDKs will encounter an error if the AsyncRunner +// does not satisfy one of these interfaces. +type AsyncRunner interface { + // AnyRunner is a non-exported method with no functional use + // other than to make this a non-empty interface. + AnyRunner() +} + +// AsyncSingleRunner is an interface implemented by single-observer +// callbacks. +type AsyncSingleRunner interface { + // Run accepts a single instrument and function for capturing + // observations of that instrument. Each call to the function + // receives one captured observation. (The function accepts + // multiple observations so the same implementation can be + // used for batch runners.) + Run(ctx context.Context, single AsyncImpl, capture func([]attribute.KeyValue, ...Observation)) + + AsyncRunner +} + +// AsyncBatchRunner is an interface implemented by batch-observer +// callbacks. +type AsyncBatchRunner interface { + // Run accepts a function for capturing observations of + // multiple instruments. + Run(ctx context.Context, capture func([]attribute.KeyValue, ...Observation)) + + AsyncRunner +} + +// NewMeasurement constructs a single observation, a binding between +// an asynchronous instrument and a number. +func NewMeasurement(instrument SyncImpl, number number.Number) Measurement { + return Measurement{ + instrument: instrument, + number: number, + } +} + +// Measurement is a low-level type used with synchronous instruments +// as a direct interface to the SDK via `RecordBatch`. +type Measurement struct { + // number needs to be aligned for 64-bit atomic operations. + number number.Number + instrument SyncImpl +} + +// SyncImpl returns the instrument that created this measurement. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (m Measurement) SyncImpl() SyncImpl { + return m.instrument +} + +// Number returns a number recorded in this measurement. +func (m Measurement) Number() number.Number { + return m.number +} + +// NewObservation constructs a single observation, a binding between +// an asynchronous instrument and a number. +func NewObservation(instrument AsyncImpl, number number.Number) Observation { + return Observation{ + instrument: instrument, + number: number, + } +} + +// Observation is a low-level type used with asynchronous instruments +// as a direct interface to the SDK via `BatchObserver`. +type Observation struct { + // number needs to be aligned for 64-bit atomic operations. + number number.Number + instrument AsyncImpl +} + +// AsyncImpl returns the instrument that created this observation. +// This returns an implementation-level object for use by the SDK, +// users should not refer to this. +func (m Observation) AsyncImpl() AsyncImpl { + return m.instrument +} + +// Number returns a number recorded in this observation. +func (m Observation) Number() number.Number { + return m.number +} diff --git a/vendor/go.opentelemetry.io/otel/metric/unit/doc.go b/vendor/go.opentelemetry.io/otel/metric/unit/doc.go new file mode 100644 index 0000000000000..f8e723593e617 --- /dev/null +++ b/vendor/go.opentelemetry.io/otel/metric/unit/doc.go @@ -0,0 +1,20 @@ +// Copyright The OpenTelemetry 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 unit provides units. +// +// This package is currently in a pre-GA phase. Backwards incompatible changes +// may be introduced in subsequent minor version releases as we work to track +// the evolving OpenTelemetry specification and user feedback. +package unit // import "go.opentelemetry.io/otel/metric/unit" diff --git a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/header.go b/vendor/go.opentelemetry.io/otel/metric/unit/unit.go similarity index 55% rename from vendor/go.opentelemetry.io/otel/exporters/otlp/internal/header.go rename to vendor/go.opentelemetry.io/otel/metric/unit/unit.go index 9aa62ed9e8e9c..4615eb16f6990 100644 --- a/vendor/go.opentelemetry.io/otel/exporters/otlp/internal/header.go +++ b/vendor/go.opentelemetry.io/otel/metric/unit/unit.go @@ -12,13 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package internal contains common functionality for all OTLP exporters. -package internal // import "go.opentelemetry.io/otel/exporters/otlp/internal" +package unit // import "go.opentelemetry.io/otel/metric/unit" -import "go.opentelemetry.io/otel" +type Unit string -// GetUserAgentHeader return an OTLP header value form "OTel OTLP Exporter Go/{{ .Version }}" -// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#user-agent -func GetUserAgentHeader() string { - return "OTel OTLP Exporter Go/" + otel.Version() -} +// Units defined by OpenTelemetry. +const ( + Dimensionless Unit = "1" + Bytes Unit = "By" + Milliseconds Unit = "ms" +) diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_config.pb.go b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_config.pb.go new file mode 100644 index 0000000000000..07f7e9b1fa355 --- /dev/null +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_config.pb.go @@ -0,0 +1,573 @@ +// Copyright 2019, OpenTelemetry 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. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.23.0 +// protoc v3.13.0 +// source: opentelemetry/proto/trace/v1/trace_config.proto + +package v1 + +import ( + proto "github.com/golang/protobuf/proto" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +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) +) + +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + +// How spans should be sampled: +// - Always off +// - Always on +// - Always follow the parent Span's decision (off if no parent). +type ConstantSampler_ConstantDecision int32 + +const ( + ConstantSampler_ALWAYS_OFF ConstantSampler_ConstantDecision = 0 + ConstantSampler_ALWAYS_ON ConstantSampler_ConstantDecision = 1 + ConstantSampler_ALWAYS_PARENT ConstantSampler_ConstantDecision = 2 +) + +// Enum value maps for ConstantSampler_ConstantDecision. +var ( + ConstantSampler_ConstantDecision_name = map[int32]string{ + 0: "ALWAYS_OFF", + 1: "ALWAYS_ON", + 2: "ALWAYS_PARENT", + } + ConstantSampler_ConstantDecision_value = map[string]int32{ + "ALWAYS_OFF": 0, + "ALWAYS_ON": 1, + "ALWAYS_PARENT": 2, + } +) + +func (x ConstantSampler_ConstantDecision) Enum() *ConstantSampler_ConstantDecision { + p := new(ConstantSampler_ConstantDecision) + *p = x + return p +} + +func (x ConstantSampler_ConstantDecision) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ConstantSampler_ConstantDecision) Descriptor() protoreflect.EnumDescriptor { + return file_opentelemetry_proto_trace_v1_trace_config_proto_enumTypes[0].Descriptor() +} + +func (ConstantSampler_ConstantDecision) Type() protoreflect.EnumType { + return &file_opentelemetry_proto_trace_v1_trace_config_proto_enumTypes[0] +} + +func (x ConstantSampler_ConstantDecision) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ConstantSampler_ConstantDecision.Descriptor instead. +func (ConstantSampler_ConstantDecision) EnumDescriptor() ([]byte, []int) { + return file_opentelemetry_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{1, 0} +} + +// Global configuration of the trace service. All fields must be specified, or +// the default (zero) values will be used for each type. +type TraceConfig struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The global default sampler used to make decisions on span sampling. + // + // Types that are assignable to Sampler: + // *TraceConfig_ConstantSampler + // *TraceConfig_TraceIdRatioBased + // *TraceConfig_RateLimitingSampler + Sampler isTraceConfig_Sampler `protobuf_oneof:"sampler"` + // The global default max number of attributes per span. + MaxNumberOfAttributes int64 `protobuf:"varint,4,opt,name=max_number_of_attributes,json=maxNumberOfAttributes,proto3" json:"max_number_of_attributes,omitempty"` + // The global default max number of annotation events per span. + MaxNumberOfTimedEvents int64 `protobuf:"varint,5,opt,name=max_number_of_timed_events,json=maxNumberOfTimedEvents,proto3" json:"max_number_of_timed_events,omitempty"` + // The global default max number of attributes per timed event. + MaxNumberOfAttributesPerTimedEvent int64 `protobuf:"varint,6,opt,name=max_number_of_attributes_per_timed_event,json=maxNumberOfAttributesPerTimedEvent,proto3" json:"max_number_of_attributes_per_timed_event,omitempty"` + // The global default max number of link entries per span. + MaxNumberOfLinks int64 `protobuf:"varint,7,opt,name=max_number_of_links,json=maxNumberOfLinks,proto3" json:"max_number_of_links,omitempty"` + // The global default max number of attributes per span. + MaxNumberOfAttributesPerLink int64 `protobuf:"varint,8,opt,name=max_number_of_attributes_per_link,json=maxNumberOfAttributesPerLink,proto3" json:"max_number_of_attributes_per_link,omitempty"` +} + +func (x *TraceConfig) Reset() { + *x = TraceConfig{} + if protoimpl.UnsafeEnabled { + mi := &file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TraceConfig) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TraceConfig) ProtoMessage() {} + +func (x *TraceConfig) ProtoReflect() protoreflect.Message { + mi := &file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TraceConfig.ProtoReflect.Descriptor instead. +func (*TraceConfig) Descriptor() ([]byte, []int) { + return file_opentelemetry_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{0} +} + +func (m *TraceConfig) GetSampler() isTraceConfig_Sampler { + if m != nil { + return m.Sampler + } + return nil +} + +func (x *TraceConfig) GetConstantSampler() *ConstantSampler { + if x, ok := x.GetSampler().(*TraceConfig_ConstantSampler); ok { + return x.ConstantSampler + } + return nil +} + +func (x *TraceConfig) GetTraceIdRatioBased() *TraceIdRatioBased { + if x, ok := x.GetSampler().(*TraceConfig_TraceIdRatioBased); ok { + return x.TraceIdRatioBased + } + return nil +} + +func (x *TraceConfig) GetRateLimitingSampler() *RateLimitingSampler { + if x, ok := x.GetSampler().(*TraceConfig_RateLimitingSampler); ok { + return x.RateLimitingSampler + } + return nil +} + +func (x *TraceConfig) GetMaxNumberOfAttributes() int64 { + if x != nil { + return x.MaxNumberOfAttributes + } + return 0 +} + +func (x *TraceConfig) GetMaxNumberOfTimedEvents() int64 { + if x != nil { + return x.MaxNumberOfTimedEvents + } + return 0 +} + +func (x *TraceConfig) GetMaxNumberOfAttributesPerTimedEvent() int64 { + if x != nil { + return x.MaxNumberOfAttributesPerTimedEvent + } + return 0 +} + +func (x *TraceConfig) GetMaxNumberOfLinks() int64 { + if x != nil { + return x.MaxNumberOfLinks + } + return 0 +} + +func (x *TraceConfig) GetMaxNumberOfAttributesPerLink() int64 { + if x != nil { + return x.MaxNumberOfAttributesPerLink + } + return 0 +} + +type isTraceConfig_Sampler interface { + isTraceConfig_Sampler() +} + +type TraceConfig_ConstantSampler struct { + ConstantSampler *ConstantSampler `protobuf:"bytes,1,opt,name=constant_sampler,json=constantSampler,proto3,oneof"` +} + +type TraceConfig_TraceIdRatioBased struct { + TraceIdRatioBased *TraceIdRatioBased `protobuf:"bytes,2,opt,name=trace_id_ratio_based,json=traceIdRatioBased,proto3,oneof"` +} + +type TraceConfig_RateLimitingSampler struct { + RateLimitingSampler *RateLimitingSampler `protobuf:"bytes,3,opt,name=rate_limiting_sampler,json=rateLimitingSampler,proto3,oneof"` +} + +func (*TraceConfig_ConstantSampler) isTraceConfig_Sampler() {} + +func (*TraceConfig_TraceIdRatioBased) isTraceConfig_Sampler() {} + +func (*TraceConfig_RateLimitingSampler) isTraceConfig_Sampler() {} + +// Sampler that always makes a constant decision on span sampling. +type ConstantSampler struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Decision ConstantSampler_ConstantDecision `protobuf:"varint,1,opt,name=decision,proto3,enum=opentelemetry.proto.trace.v1.ConstantSampler_ConstantDecision" json:"decision,omitempty"` +} + +func (x *ConstantSampler) Reset() { + *x = ConstantSampler{} + if protoimpl.UnsafeEnabled { + mi := &file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ConstantSampler) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ConstantSampler) ProtoMessage() {} + +func (x *ConstantSampler) ProtoReflect() protoreflect.Message { + mi := &file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ConstantSampler.ProtoReflect.Descriptor instead. +func (*ConstantSampler) Descriptor() ([]byte, []int) { + return file_opentelemetry_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{1} +} + +func (x *ConstantSampler) GetDecision() ConstantSampler_ConstantDecision { + if x != nil { + return x.Decision + } + return ConstantSampler_ALWAYS_OFF +} + +// Sampler that tries to uniformly sample traces with a given ratio. +// The ratio of sampling a trace is equal to that of the specified ratio. +type TraceIdRatioBased struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // The desired ratio of sampling. Must be within [0.0, 1.0]. + SamplingRatio float64 `protobuf:"fixed64,1,opt,name=samplingRatio,proto3" json:"samplingRatio,omitempty"` +} + +func (x *TraceIdRatioBased) Reset() { + *x = TraceIdRatioBased{} + if protoimpl.UnsafeEnabled { + mi := &file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TraceIdRatioBased) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TraceIdRatioBased) ProtoMessage() {} + +func (x *TraceIdRatioBased) ProtoReflect() protoreflect.Message { + mi := &file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TraceIdRatioBased.ProtoReflect.Descriptor instead. +func (*TraceIdRatioBased) Descriptor() ([]byte, []int) { + return file_opentelemetry_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{2} +} + +func (x *TraceIdRatioBased) GetSamplingRatio() float64 { + if x != nil { + return x.SamplingRatio + } + return 0 +} + +// Sampler that tries to sample with a rate per time window. +type RateLimitingSampler struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // Rate per second. + Qps int64 `protobuf:"varint,1,opt,name=qps,proto3" json:"qps,omitempty"` +} + +func (x *RateLimitingSampler) Reset() { + *x = RateLimitingSampler{} + if protoimpl.UnsafeEnabled { + mi := &file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RateLimitingSampler) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RateLimitingSampler) ProtoMessage() {} + +func (x *RateLimitingSampler) ProtoReflect() protoreflect.Message { + mi := &file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RateLimitingSampler.ProtoReflect.Descriptor instead. +func (*RateLimitingSampler) Descriptor() ([]byte, []int) { + return file_opentelemetry_proto_trace_v1_trace_config_proto_rawDescGZIP(), []int{3} +} + +func (x *RateLimitingSampler) GetQps() int64 { + if x != nil { + return x.Qps + } + return 0 +} + +var File_opentelemetry_proto_trace_v1_trace_config_proto protoreflect.FileDescriptor + +var file_opentelemetry_proto_trace_v1_trace_config_proto_rawDesc = []byte{ + 0x0a, 0x2f, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2f, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0x2f, 0x74, + 0x72, 0x61, 0x63, 0x65, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x12, 0x1c, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x22, + 0x84, 0x05, 0x0a, 0x0b, 0x54, 0x72, 0x61, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, + 0x5a, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x74, 0x5f, 0x73, 0x61, 0x6d, 0x70, + 0x6c, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2d, 0x2e, 0x6f, 0x70, 0x65, 0x6e, + 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, + 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x61, 0x6e, + 0x74, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x48, 0x00, 0x52, 0x0f, 0x63, 0x6f, 0x6e, 0x73, + 0x74, 0x61, 0x6e, 0x74, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x12, 0x62, 0x0a, 0x14, 0x74, + 0x72, 0x61, 0x63, 0x65, 0x5f, 0x69, 0x64, 0x5f, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x5f, 0x62, 0x61, + 0x73, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x2f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, + 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, + 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x54, 0x72, 0x61, 0x63, 0x65, 0x49, 0x64, + 0x52, 0x61, 0x74, 0x69, 0x6f, 0x42, 0x61, 0x73, 0x65, 0x64, 0x48, 0x00, 0x52, 0x11, 0x74, 0x72, + 0x61, 0x63, 0x65, 0x49, 0x64, 0x52, 0x61, 0x74, 0x69, 0x6f, 0x42, 0x61, 0x73, 0x65, 0x64, 0x12, + 0x67, 0x0a, 0x15, 0x72, 0x61, 0x74, 0x65, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x69, 0x6e, 0x67, + 0x5f, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x31, + 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x61, + 0x74, 0x65, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x69, 0x6e, 0x67, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, + 0x72, 0x48, 0x00, 0x52, 0x13, 0x72, 0x61, 0x74, 0x65, 0x4c, 0x69, 0x6d, 0x69, 0x74, 0x69, 0x6e, + 0x67, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x12, 0x37, 0x0a, 0x18, 0x6d, 0x61, 0x78, 0x5f, + 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x5f, 0x6f, 0x66, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, + 0x75, 0x74, 0x65, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x15, 0x6d, 0x61, 0x78, 0x4e, + 0x75, 0x6d, 0x62, 0x65, 0x72, 0x4f, 0x66, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, + 0x73, 0x12, 0x3a, 0x0a, 0x1a, 0x6d, 0x61, 0x78, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x5f, + 0x6f, 0x66, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x64, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x18, + 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x16, 0x6d, 0x61, 0x78, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, + 0x4f, 0x66, 0x54, 0x69, 0x6d, 0x65, 0x64, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x12, 0x54, 0x0a, + 0x28, 0x6d, 0x61, 0x78, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x5f, 0x6f, 0x66, 0x5f, 0x61, + 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x70, 0x65, 0x72, 0x5f, 0x74, 0x69, + 0x6d, 0x65, 0x64, 0x5f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, + 0x22, 0x6d, 0x61, 0x78, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x4f, 0x66, 0x41, 0x74, 0x74, 0x72, + 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x50, 0x65, 0x72, 0x54, 0x69, 0x6d, 0x65, 0x64, 0x45, 0x76, + 0x65, 0x6e, 0x74, 0x12, 0x2d, 0x0a, 0x13, 0x6d, 0x61, 0x78, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, + 0x72, 0x5f, 0x6f, 0x66, 0x5f, 0x6c, 0x69, 0x6e, 0x6b, 0x73, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, + 0x52, 0x10, 0x6d, 0x61, 0x78, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x4f, 0x66, 0x4c, 0x69, 0x6e, + 0x6b, 0x73, 0x12, 0x47, 0x0a, 0x21, 0x6d, 0x61, 0x78, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, + 0x5f, 0x6f, 0x66, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x70, + 0x65, 0x72, 0x5f, 0x6c, 0x69, 0x6e, 0x6b, 0x18, 0x08, 0x20, 0x01, 0x28, 0x03, 0x52, 0x1c, 0x6d, + 0x61, 0x78, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x4f, 0x66, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, + 0x75, 0x74, 0x65, 0x73, 0x50, 0x65, 0x72, 0x4c, 0x69, 0x6e, 0x6b, 0x42, 0x09, 0x0a, 0x07, 0x73, + 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x22, 0xb3, 0x01, 0x0a, 0x0f, 0x43, 0x6f, 0x6e, 0x73, 0x74, + 0x61, 0x6e, 0x74, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x12, 0x5a, 0x0a, 0x08, 0x64, 0x65, + 0x63, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x3e, 0x2e, 0x6f, + 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x73, + 0x74, 0x61, 0x6e, 0x74, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x2e, 0x43, 0x6f, 0x6e, 0x73, + 0x74, 0x61, 0x6e, 0x74, 0x44, 0x65, 0x63, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x08, 0x64, 0x65, + 0x63, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x44, 0x0a, 0x10, 0x43, 0x6f, 0x6e, 0x73, 0x74, 0x61, + 0x6e, 0x74, 0x44, 0x65, 0x63, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x0e, 0x0a, 0x0a, 0x41, 0x4c, + 0x57, 0x41, 0x59, 0x53, 0x5f, 0x4f, 0x46, 0x46, 0x10, 0x00, 0x12, 0x0d, 0x0a, 0x09, 0x41, 0x4c, + 0x57, 0x41, 0x59, 0x53, 0x5f, 0x4f, 0x4e, 0x10, 0x01, 0x12, 0x11, 0x0a, 0x0d, 0x41, 0x4c, 0x57, + 0x41, 0x59, 0x53, 0x5f, 0x50, 0x41, 0x52, 0x45, 0x4e, 0x54, 0x10, 0x02, 0x22, 0x39, 0x0a, 0x11, + 0x54, 0x72, 0x61, 0x63, 0x65, 0x49, 0x64, 0x52, 0x61, 0x74, 0x69, 0x6f, 0x42, 0x61, 0x73, 0x65, + 0x64, 0x12, 0x24, 0x0a, 0x0d, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x69, 0x6e, 0x67, 0x52, 0x61, 0x74, + 0x69, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x01, 0x52, 0x0d, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x69, + 0x6e, 0x67, 0x52, 0x61, 0x74, 0x69, 0x6f, 0x22, 0x27, 0x0a, 0x13, 0x52, 0x61, 0x74, 0x65, 0x4c, + 0x69, 0x6d, 0x69, 0x74, 0x69, 0x6e, 0x67, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x12, 0x10, + 0x0a, 0x03, 0x71, 0x70, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x71, 0x70, 0x73, + 0x42, 0x68, 0x0a, 0x1f, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, + 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, + 0x2e, 0x76, 0x31, 0x42, 0x10, 0x54, 0x72, 0x61, 0x63, 0x65, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x31, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, + 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, + 0x72, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x33, +} + +var ( + file_opentelemetry_proto_trace_v1_trace_config_proto_rawDescOnce sync.Once + file_opentelemetry_proto_trace_v1_trace_config_proto_rawDescData = file_opentelemetry_proto_trace_v1_trace_config_proto_rawDesc +) + +func file_opentelemetry_proto_trace_v1_trace_config_proto_rawDescGZIP() []byte { + file_opentelemetry_proto_trace_v1_trace_config_proto_rawDescOnce.Do(func() { + file_opentelemetry_proto_trace_v1_trace_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_opentelemetry_proto_trace_v1_trace_config_proto_rawDescData) + }) + return file_opentelemetry_proto_trace_v1_trace_config_proto_rawDescData +} + +var file_opentelemetry_proto_trace_v1_trace_config_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_opentelemetry_proto_trace_v1_trace_config_proto_goTypes = []interface{}{ + (ConstantSampler_ConstantDecision)(0), // 0: opentelemetry.proto.trace.v1.ConstantSampler.ConstantDecision + (*TraceConfig)(nil), // 1: opentelemetry.proto.trace.v1.TraceConfig + (*ConstantSampler)(nil), // 2: opentelemetry.proto.trace.v1.ConstantSampler + (*TraceIdRatioBased)(nil), // 3: opentelemetry.proto.trace.v1.TraceIdRatioBased + (*RateLimitingSampler)(nil), // 4: opentelemetry.proto.trace.v1.RateLimitingSampler +} +var file_opentelemetry_proto_trace_v1_trace_config_proto_depIdxs = []int32{ + 2, // 0: opentelemetry.proto.trace.v1.TraceConfig.constant_sampler:type_name -> opentelemetry.proto.trace.v1.ConstantSampler + 3, // 1: opentelemetry.proto.trace.v1.TraceConfig.trace_id_ratio_based:type_name -> opentelemetry.proto.trace.v1.TraceIdRatioBased + 4, // 2: opentelemetry.proto.trace.v1.TraceConfig.rate_limiting_sampler:type_name -> opentelemetry.proto.trace.v1.RateLimitingSampler + 0, // 3: opentelemetry.proto.trace.v1.ConstantSampler.decision:type_name -> opentelemetry.proto.trace.v1.ConstantSampler.ConstantDecision + 4, // [4:4] is the sub-list for method output_type + 4, // [4:4] is the sub-list for method input_type + 4, // [4:4] is the sub-list for extension type_name + 4, // [4:4] is the sub-list for extension extendee + 0, // [0:4] is the sub-list for field type_name +} + +func init() { file_opentelemetry_proto_trace_v1_trace_config_proto_init() } +func file_opentelemetry_proto_trace_v1_trace_config_proto_init() { + if File_opentelemetry_proto_trace_v1_trace_config_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TraceConfig); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ConstantSampler); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TraceIdRatioBased); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RateLimitingSampler); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes[0].OneofWrappers = []interface{}{ + (*TraceConfig_ConstantSampler)(nil), + (*TraceConfig_TraceIdRatioBased)(nil), + (*TraceConfig_RateLimitingSampler)(nil), + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_opentelemetry_proto_trace_v1_trace_config_proto_rawDesc, + NumEnums: 1, + NumMessages: 4, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_opentelemetry_proto_trace_v1_trace_config_proto_goTypes, + DependencyIndexes: file_opentelemetry_proto_trace_v1_trace_config_proto_depIdxs, + EnumInfos: file_opentelemetry_proto_trace_v1_trace_config_proto_enumTypes, + MessageInfos: file_opentelemetry_proto_trace_v1_trace_config_proto_msgTypes, + }.Build() + File_opentelemetry_proto_trace_v1_trace_config_proto = out.File + file_opentelemetry_proto_trace_v1_trace_config_proto_rawDesc = nil + file_opentelemetry_proto_trace_v1_trace_config_proto_goTypes = nil + file_opentelemetry_proto_trace_v1_trace_config_proto_depIdxs = nil +} diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.go b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.go index fc285c089e7b4..402614f1d3c5a 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.go @@ -14,13 +14,14 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.17.3 +// protoc-gen-go v1.23.0 +// protoc v3.13.0 // source: opentelemetry/proto/collector/trace/v1/trace_service.proto package v1 import ( + proto "github.com/golang/protobuf/proto" v1 "go.opentelemetry.io/proto/otlp/trace/v1" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" @@ -35,6 +36,10 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + type ExportTraceServiceRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -91,23 +96,6 @@ type ExportTraceServiceResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - - // The details of a partially successful export request. - // - // If the request is only partially accepted - // (i.e. when the server accepts only parts of the data and rejects the rest) - // the server MUST initialize the `partial_success` field and MUST - // set the `rejected_` with the number of items it rejected. - // - // Servers MAY also make use of the `partial_success` field to convey - // warnings/suggestions to senders even when the request was fully accepted. - // In such cases, the `rejected_` MUST have a value of `0` and - // the `error_message` MUST be non-empty. - // - // A `partial_success` message with an empty value (rejected_ = 0 and - // `error_message` = "") is equivalent to it not being set/present. Senders - // SHOULD interpret it the same way as in the full success case. - PartialSuccess *ExportTracePartialSuccess `protobuf:"bytes,1,opt,name=partial_success,json=partialSuccess,proto3" json:"partial_success,omitempty"` } func (x *ExportTraceServiceResponse) Reset() { @@ -142,79 +130,6 @@ func (*ExportTraceServiceResponse) Descriptor() ([]byte, []int) { return file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescGZIP(), []int{1} } -func (x *ExportTraceServiceResponse) GetPartialSuccess() *ExportTracePartialSuccess { - if x != nil { - return x.PartialSuccess - } - return nil -} - -type ExportTracePartialSuccess struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // The number of rejected spans. - // - // A `rejected_` field holding a `0` value indicates that the - // request was fully accepted. - RejectedSpans int64 `protobuf:"varint,1,opt,name=rejected_spans,json=rejectedSpans,proto3" json:"rejected_spans,omitempty"` - // A developer-facing human-readable message in English. It should be used - // either to explain why the server rejected parts of the data during a partial - // success or to convey warnings/suggestions during a full success. The message - // should offer guidance on how users can address such issues. - // - // error_message is an optional field. An error_message with an empty value - // is equivalent to it not being set. - ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` -} - -func (x *ExportTracePartialSuccess) Reset() { - *x = ExportTracePartialSuccess{} - if protoimpl.UnsafeEnabled { - mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ExportTracePartialSuccess) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ExportTracePartialSuccess) ProtoMessage() {} - -func (x *ExportTracePartialSuccess) ProtoReflect() protoreflect.Message { - mi := &file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ExportTracePartialSuccess.ProtoReflect.Descriptor instead. -func (*ExportTracePartialSuccess) Descriptor() ([]byte, []int) { - return file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescGZIP(), []int{2} -} - -func (x *ExportTracePartialSuccess) GetRejectedSpans() int64 { - if x != nil { - return x.RejectedSpans - } - return 0 -} - -func (x *ExportTracePartialSuccess) GetErrorMessage() string { - if x != nil { - return x.ErrorMessage - } - return "" -} - var File_opentelemetry_proto_collector_trace_v1_trace_service_proto protoreflect.FileDescriptor var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc = []byte{ @@ -234,42 +149,26 @@ var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc = [] 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x22, - 0x88, 0x01, 0x0a, 0x1a, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, - 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6a, - 0x0a, 0x0f, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x5f, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, - 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x41, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, - 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, - 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x50, 0x61, 0x72, 0x74, - 0x69, 0x61, 0x6c, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x52, 0x0e, 0x70, 0x61, 0x72, 0x74, - 0x69, 0x61, 0x6c, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x22, 0x67, 0x0a, 0x19, 0x45, 0x78, - 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x50, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, - 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x12, 0x25, 0x0a, 0x0e, 0x72, 0x65, 0x6a, 0x65, 0x63, - 0x74, 0x65, 0x64, 0x5f, 0x73, 0x70, 0x61, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, - 0x0d, 0x72, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x65, 0x64, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x23, - 0x0a, 0x0d, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, - 0x61, 0x67, 0x65, 0x32, 0xa2, 0x01, 0x0a, 0x0c, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x12, 0x91, 0x01, 0x0a, 0x06, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x12, - 0x41, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, - 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, - 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x1a, 0x42, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, - 0x6f, 0x72, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, - 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x9c, 0x01, 0x0a, 0x29, 0x69, 0x6f, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x74, 0x72, - 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x42, 0x11, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x31, 0x67, 0x6f, 0x2e, - 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, - 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x63, 0x6f, 0x6c, 0x6c, - 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0xaa, 0x02, - 0x26, 0x4f, 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x50, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x54, - 0x72, 0x61, 0x63, 0x65, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x1c, 0x0a, 0x1a, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, + 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x32, 0xa2, 0x01, + 0x0a, 0x0c, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x91, + 0x01, 0x0a, 0x06, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x41, 0x2e, 0x6f, 0x70, 0x65, 0x6e, + 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, + 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, + 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, + 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x42, 0x2e, 0x6f, + 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x74, 0x72, 0x61, + 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x45, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x54, 0x72, 0x61, 0x63, + 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x22, 0x00, 0x42, 0x73, 0x0a, 0x29, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, + 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6c, + 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x42, + 0x11, 0x54, 0x72, 0x61, 0x63, 0x65, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x50, 0x72, 0x6f, + 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x31, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, + 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, + 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2f, 0x74, + 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -284,23 +183,21 @@ func file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescGZIP return file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDescData } -var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes = make([]protoimpl.MessageInfo, 3) +var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_goTypes = []interface{}{ (*ExportTraceServiceRequest)(nil), // 0: opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest (*ExportTraceServiceResponse)(nil), // 1: opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - (*ExportTracePartialSuccess)(nil), // 2: opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - (*v1.ResourceSpans)(nil), // 3: opentelemetry.proto.trace.v1.ResourceSpans + (*v1.ResourceSpans)(nil), // 2: opentelemetry.proto.trace.v1.ResourceSpans } var file_opentelemetry_proto_collector_trace_v1_trace_service_proto_depIdxs = []int32{ - 3, // 0: opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resource_spans:type_name -> opentelemetry.proto.trace.v1.ResourceSpans - 2, // 1: opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse.partial_success:type_name -> opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - 0, // 2: opentelemetry.proto.collector.trace.v1.TraceService.Export:input_type -> opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest - 1, // 3: opentelemetry.proto.collector.trace.v1.TraceService.Export:output_type -> opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - 3, // [3:4] is the sub-list for method output_type - 2, // [2:3] is the sub-list for method input_type - 2, // [2:2] is the sub-list for extension type_name - 2, // [2:2] is the sub-list for extension extendee - 0, // [0:2] is the sub-list for field type_name + 2, // 0: opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resource_spans:type_name -> opentelemetry.proto.trace.v1.ResourceSpans + 0, // 1: opentelemetry.proto.collector.trace.v1.TraceService.Export:input_type -> opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest + 1, // 2: opentelemetry.proto.collector.trace.v1.TraceService.Export:output_type -> opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse + 2, // [2:3] is the sub-list for method output_type + 1, // [1:2] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name } func init() { file_opentelemetry_proto_collector_trace_v1_trace_service_proto_init() } @@ -333,18 +230,6 @@ func file_opentelemetry_proto_collector_trace_v1_trace_service_proto_init() { return nil } } - file_opentelemetry_proto_collector_trace_v1_trace_service_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ExportTracePartialSuccess); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } } type x struct{} out := protoimpl.TypeBuilder{ @@ -352,7 +237,7 @@ func file_opentelemetry_proto_collector_trace_v1_trace_service_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_opentelemetry_proto_collector_trace_v1_trace_service_proto_rawDesc, NumEnums: 0, - NumMessages: 3, + NumMessages: 2, NumExtensions: 0, NumServices: 1, }, diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.gw.go b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.gw.go index d142c2a447dc3..18dff3d03e7b8 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.gw.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service.pb.gw.go @@ -13,14 +13,15 @@ import ( "io" "net/http" - "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" - "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" - "google.golang.org/protobuf/proto" ) // Suppress "imported and not used" errors @@ -29,6 +30,7 @@ var _ io.Reader var _ status.Status var _ = runtime.String var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage var _ = metadata.Join func request_TraceService_Export_0(ctx context.Context, marshaler runtime.Marshaler, client TraceServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -77,7 +79,7 @@ func RegisterTraceServiceHandlerServer(ctx context.Context, mux *runtime.ServeMu var stream runtime.ServerTransportStream ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", runtime.WithHTTPPathPattern("/v1/trace")) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -139,7 +141,7 @@ func RegisterTraceServiceHandlerClient(ctx context.Context, mux *runtime.ServeMu ctx, cancel := context.WithCancel(req.Context()) defer cancel() inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req, "/opentelemetry.proto.collector.trace.v1.TraceService/Export", runtime.WithHTTPPathPattern("/v1/trace")) + rctx, err := runtime.AnnotateContext(ctx, mux, req) if err != nil { runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) return @@ -159,7 +161,7 @@ func RegisterTraceServiceHandlerClient(ctx context.Context, mux *runtime.ServeMu } var ( - pattern_TraceService_Export_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "trace"}, "")) + pattern_TraceService_Export_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "trace"}, "", runtime.AssumeColonVerbOpt(true))) ) var ( diff --git a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service_grpc.pb.go b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service_grpc.pb.go index c21f2cb47cf7c..4e4c24c0c875d 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service_grpc.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/collector/trace/v1/trace_service_grpc.pb.go @@ -1,8 +1,4 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.1.0 -// - protoc v3.17.3 -// source: opentelemetry/proto/collector/trace/v1/trace_service.proto package v1 @@ -15,7 +11,6 @@ import ( // 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.32.0 or later. const _ = grpc.SupportPackageIsVersion7 // TraceServiceClient is the client API for TraceService service. @@ -71,7 +66,7 @@ type UnsafeTraceServiceServer interface { } func RegisterTraceServiceServer(s grpc.ServiceRegistrar, srv TraceServiceServer) { - s.RegisterService(&TraceService_ServiceDesc, srv) + s.RegisterService(&_TraceService_serviceDesc, srv) } func _TraceService_Export_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { @@ -92,10 +87,7 @@ func _TraceService_Export_Handler(srv interface{}, ctx context.Context, dec func return interceptor(ctx, in, info, handler) } -// TraceService_ServiceDesc is the grpc.ServiceDesc for TraceService service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var TraceService_ServiceDesc = grpc.ServiceDesc{ +var _TraceService_serviceDesc = grpc.ServiceDesc{ ServiceName: "opentelemetry.proto.collector.trace.v1.TraceService", HandlerType: (*TraceServiceServer)(nil), Methods: []grpc.MethodDesc{ diff --git a/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go b/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go index 8502e607b2541..de75b592ca9a3 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/common/v1/common.pb.go @@ -14,13 +14,14 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.17.3 +// protoc-gen-go v1.23.0 +// protoc v3.13.0 // source: opentelemetry/proto/common/v1/common.proto package v1 import ( + proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -34,6 +35,10 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + // AnyValue is used to represent any type of attribute value. AnyValue may contain a // primitive value such as a string or integer or it may contain an arbitrary nested // object containing arrays, key-value lists and primitives. @@ -252,8 +257,6 @@ type KeyValueList struct { // A collection of key/value pairs of key-value pairs. The list may be empty (may // contain 0 elements). - // The keys MUST be unique (it is not allowed to have more than one - // value with the same key). Values []*KeyValue `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` } @@ -353,22 +356,21 @@ func (x *KeyValue) GetValue() *AnyValue { return nil } -// InstrumentationScope is a message representing the instrumentation scope information -// such as the fully qualified name and version. -type InstrumentationScope struct { +// StringKeyValue is a pair of key/value strings. This is the simpler (and faster) version +// of KeyValue that only supports string values. +// +// Deprecated: Do not use. +type StringKeyValue struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // An empty instrumentation scope name means the name is unknown. - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` - Attributes []*KeyValue `protobuf:"bytes,3,rep,name=attributes,proto3" json:"attributes,omitempty"` - DroppedAttributesCount uint32 `protobuf:"varint,4,opt,name=dropped_attributes_count,json=droppedAttributesCount,proto3" json:"dropped_attributes_count,omitempty"` + Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` } -func (x *InstrumentationScope) Reset() { - *x = InstrumentationScope{} +func (x *StringKeyValue) Reset() { + *x = StringKeyValue{} if protoimpl.UnsafeEnabled { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) @@ -376,13 +378,13 @@ func (x *InstrumentationScope) Reset() { } } -func (x *InstrumentationScope) String() string { +func (x *StringKeyValue) String() string { return protoimpl.X.MessageStringOf(x) } -func (*InstrumentationScope) ProtoMessage() {} +func (*StringKeyValue) ProtoMessage() {} -func (x *InstrumentationScope) ProtoReflect() protoreflect.Message { +func (x *StringKeyValue) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) @@ -394,37 +396,81 @@ func (x *InstrumentationScope) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use InstrumentationScope.ProtoReflect.Descriptor instead. -func (*InstrumentationScope) Descriptor() ([]byte, []int) { +// Deprecated: Use StringKeyValue.ProtoReflect.Descriptor instead. +func (*StringKeyValue) Descriptor() ([]byte, []int) { return file_opentelemetry_proto_common_v1_common_proto_rawDescGZIP(), []int{4} } -func (x *InstrumentationScope) GetName() string { +func (x *StringKeyValue) GetKey() string { if x != nil { - return x.Name + return x.Key } return "" } -func (x *InstrumentationScope) GetVersion() string { +func (x *StringKeyValue) GetValue() string { if x != nil { - return x.Version + return x.Value } return "" } -func (x *InstrumentationScope) GetAttributes() []*KeyValue { +// InstrumentationLibrary is a message representing the instrumentation library information +// such as the fully qualified name and version. +type InstrumentationLibrary struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // An empty instrumentation library name means the name is unknown. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version,omitempty"` +} + +func (x *InstrumentationLibrary) Reset() { + *x = InstrumentationLibrary{} + if protoimpl.UnsafeEnabled { + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *InstrumentationLibrary) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*InstrumentationLibrary) ProtoMessage() {} + +func (x *InstrumentationLibrary) ProtoReflect() protoreflect.Message { + mi := &file_opentelemetry_proto_common_v1_common_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use InstrumentationLibrary.ProtoReflect.Descriptor instead. +func (*InstrumentationLibrary) Descriptor() ([]byte, []int) { + return file_opentelemetry_proto_common_v1_common_proto_rawDescGZIP(), []int{5} +} + +func (x *InstrumentationLibrary) GetName() string { if x != nil { - return x.Attributes + return x.Name } - return nil + return "" } -func (x *InstrumentationScope) GetDroppedAttributesCount() uint32 { +func (x *InstrumentationLibrary) GetVersion() string { if x != nil { - return x.DroppedAttributesCount + return x.Version } - return 0 + return "" } var File_opentelemetry_proto_common_v1_common_proto protoreflect.FileDescriptor @@ -472,28 +518,22 @@ var file_opentelemetry_proto_common_v1_common_proto_rawDesc = []byte{ 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x41, 0x6e, 0x79, 0x56, - 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0xc7, 0x01, 0x0a, 0x14, - 0x49, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, - 0x63, 0x6f, 0x70, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, - 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, - 0x6f, 0x6e, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, - 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, - 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, - 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, - 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, - 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, - 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, - 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x42, 0x7b, 0x0a, 0x20, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, - 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, - 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x42, 0x0b, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, - 0x6e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x28, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, - 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, - 0x76, 0x31, 0xaa, 0x02, 0x1d, 0x4f, 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, - 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x3c, 0x0a, 0x0e, 0x53, + 0x74, 0x72, 0x69, 0x6e, 0x67, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x10, 0x0a, + 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, + 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, + 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x18, 0x01, 0x22, 0x46, 0x0a, 0x16, 0x49, 0x6e, 0x73, + 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4c, 0x69, 0x62, 0x72, + 0x61, 0x72, 0x79, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, + 0x6e, 0x42, 0x5b, 0x0a, 0x20, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, + 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, + 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x42, 0x0b, 0x43, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x50, 0x72, 0x6f, + 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x28, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, + 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, + 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x76, 0x31, 0x62, 0x06, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -508,13 +548,14 @@ func file_opentelemetry_proto_common_v1_common_proto_rawDescGZIP() []byte { return file_opentelemetry_proto_common_v1_common_proto_rawDescData } -var file_opentelemetry_proto_common_v1_common_proto_msgTypes = make([]protoimpl.MessageInfo, 5) +var file_opentelemetry_proto_common_v1_common_proto_msgTypes = make([]protoimpl.MessageInfo, 6) var file_opentelemetry_proto_common_v1_common_proto_goTypes = []interface{}{ - (*AnyValue)(nil), // 0: opentelemetry.proto.common.v1.AnyValue - (*ArrayValue)(nil), // 1: opentelemetry.proto.common.v1.ArrayValue - (*KeyValueList)(nil), // 2: opentelemetry.proto.common.v1.KeyValueList - (*KeyValue)(nil), // 3: opentelemetry.proto.common.v1.KeyValue - (*InstrumentationScope)(nil), // 4: opentelemetry.proto.common.v1.InstrumentationScope + (*AnyValue)(nil), // 0: opentelemetry.proto.common.v1.AnyValue + (*ArrayValue)(nil), // 1: opentelemetry.proto.common.v1.ArrayValue + (*KeyValueList)(nil), // 2: opentelemetry.proto.common.v1.KeyValueList + (*KeyValue)(nil), // 3: opentelemetry.proto.common.v1.KeyValue + (*StringKeyValue)(nil), // 4: opentelemetry.proto.common.v1.StringKeyValue + (*InstrumentationLibrary)(nil), // 5: opentelemetry.proto.common.v1.InstrumentationLibrary } var file_opentelemetry_proto_common_v1_common_proto_depIdxs = []int32{ 1, // 0: opentelemetry.proto.common.v1.AnyValue.array_value:type_name -> opentelemetry.proto.common.v1.ArrayValue @@ -522,12 +563,11 @@ var file_opentelemetry_proto_common_v1_common_proto_depIdxs = []int32{ 0, // 2: opentelemetry.proto.common.v1.ArrayValue.values:type_name -> opentelemetry.proto.common.v1.AnyValue 3, // 3: opentelemetry.proto.common.v1.KeyValueList.values:type_name -> opentelemetry.proto.common.v1.KeyValue 0, // 4: opentelemetry.proto.common.v1.KeyValue.value:type_name -> opentelemetry.proto.common.v1.AnyValue - 3, // 5: opentelemetry.proto.common.v1.InstrumentationScope.attributes:type_name -> opentelemetry.proto.common.v1.KeyValue - 6, // [6:6] is the sub-list for method output_type - 6, // [6:6] is the sub-list for method input_type - 6, // [6:6] is the sub-list for extension type_name - 6, // [6:6] is the sub-list for extension extendee - 0, // [0:6] is the sub-list for field type_name + 5, // [5:5] is the sub-list for method output_type + 5, // [5:5] is the sub-list for method input_type + 5, // [5:5] is the sub-list for extension type_name + 5, // [5:5] is the sub-list for extension extendee + 0, // [0:5] is the sub-list for field type_name } func init() { file_opentelemetry_proto_common_v1_common_proto_init() } @@ -585,7 +625,19 @@ func file_opentelemetry_proto_common_v1_common_proto_init() { } } file_opentelemetry_proto_common_v1_common_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*InstrumentationScope); i { + switch v := v.(*StringKeyValue); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_opentelemetry_proto_common_v1_common_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*InstrumentationLibrary); i { case 0: return &v.state case 1: @@ -612,7 +664,7 @@ func file_opentelemetry_proto_common_v1_common_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_opentelemetry_proto_common_v1_common_proto_rawDesc, NumEnums: 0, - NumMessages: 5, + NumMessages: 6, NumExtensions: 0, NumServices: 0, }, diff --git a/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go b/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go index bcc1060e3dd2e..ac347acb2335b 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/resource/v1/resource.pb.go @@ -14,13 +14,14 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.17.3 +// protoc-gen-go v1.23.0 +// protoc v3.13.0 // source: opentelemetry/proto/resource/v1/resource.proto package v1 import ( + proto "github.com/golang/protobuf/proto" v1 "go.opentelemetry.io/proto/otlp/common/v1" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" @@ -35,15 +36,17 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + // Resource information. type Resource struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Set of attributes that describe the resource. - // Attribute keys MUST be unique (it is not allowed to have more than one - // attribute with the same key). + // Set of labels that describe the resource. Attributes []*v1.KeyValue `protobuf:"bytes,1,rep,name=attributes,proto3" json:"attributes,omitempty"` // dropped_attributes_count is the number of dropped attributes. If the value is 0, then // no attributes were dropped. @@ -115,16 +118,14 @@ var file_opentelemetry_proto_resource_v1_resource_proto_rawDesc = []byte{ 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, - 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x42, 0x83, 0x01, - 0x0a, 0x22, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, - 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, - 0x65, 0x2e, 0x76, 0x31, 0x42, 0x0d, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, 0x72, - 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2a, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2f, 0x76, - 0x31, 0xaa, 0x02, 0x1f, 0x4f, 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, - 0x79, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, - 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x42, 0x61, 0x0a, + 0x22, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, + 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, + 0x2e, 0x76, 0x31, 0x42, 0x0d, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x50, 0x72, 0x6f, + 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2a, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, + 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, + 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2f, 0x76, 0x31, + 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( diff --git a/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go b/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go index 499a43d77bb92..abf0b4c16831b 100644 --- a/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go +++ b/vendor/go.opentelemetry.io/proto/otlp/trace/v1/trace.pb.go @@ -14,13 +14,14 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.26.0 -// protoc v3.17.3 +// protoc-gen-go v1.23.0 +// protoc v3.13.0 // source: opentelemetry/proto/trace/v1/trace.proto package v1 import ( + proto "github.com/golang/protobuf/proto" v11 "go.opentelemetry.io/proto/otlp/common/v1" v1 "go.opentelemetry.io/proto/otlp/resource/v1" protoreflect "google.golang.org/protobuf/reflect/protoreflect" @@ -36,6 +37,10 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + // SpanKind is the type of span. Can be used to specify additional relationships between spans // in addition to a parent/child relationship. type Span_SpanKind int32 @@ -227,7 +232,7 @@ func (x *TracesData) GetResourceSpans() []*ResourceSpans { return nil } -// A collection of ScopeSpans from a Resource. +// A collection of InstrumentationLibrarySpans from a Resource. type ResourceSpans struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -236,10 +241,11 @@ type ResourceSpans struct { // The resource for the spans in this message. // If this field is not set then no resource info is known. Resource *v1.Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` - // A list of ScopeSpans that originate from a resource. - ScopeSpans []*ScopeSpans `protobuf:"bytes,2,rep,name=scope_spans,json=scopeSpans,proto3" json:"scope_spans,omitempty"` + // A list of InstrumentationLibrarySpans that originate from a resource. + InstrumentationLibrarySpans []*InstrumentationLibrarySpans `protobuf:"bytes,2,rep,name=instrumentation_library_spans,json=instrumentationLibrarySpans,proto3" json:"instrumentation_library_spans,omitempty"` // This schema_url applies to the data in the "resource" field. It does not apply - // to the data in the "scope_spans" field which have their own schema_url field. + // to the data in the "instrumentation_library_spans" field which have their own + // schema_url field. SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` } @@ -282,9 +288,9 @@ func (x *ResourceSpans) GetResource() *v1.Resource { return nil } -func (x *ResourceSpans) GetScopeSpans() []*ScopeSpans { +func (x *ResourceSpans) GetInstrumentationLibrarySpans() []*InstrumentationLibrarySpans { if x != nil { - return x.ScopeSpans + return x.InstrumentationLibrarySpans } return nil } @@ -296,24 +302,24 @@ func (x *ResourceSpans) GetSchemaUrl() string { return "" } -// A collection of Spans produced by an InstrumentationScope. -type ScopeSpans struct { +// A collection of Spans produced by an InstrumentationLibrary. +type InstrumentationLibrarySpans struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // The instrumentation scope information for the spans in this message. - // Semantically when InstrumentationScope isn't set, it is equivalent with - // an empty instrumentation scope name (unknown). - Scope *v11.InstrumentationScope `protobuf:"bytes,1,opt,name=scope,proto3" json:"scope,omitempty"` - // A list of Spans that originate from an instrumentation scope. + // The instrumentation library information for the spans in this message. + // Semantically when InstrumentationLibrary isn't set, it is equivalent with + // an empty instrumentation library name (unknown). + InstrumentationLibrary *v11.InstrumentationLibrary `protobuf:"bytes,1,opt,name=instrumentation_library,json=instrumentationLibrary,proto3" json:"instrumentation_library,omitempty"` + // A list of Spans that originate from an instrumentation library. Spans []*Span `protobuf:"bytes,2,rep,name=spans,proto3" json:"spans,omitempty"` // This schema_url applies to all spans and span events in the "spans" field. SchemaUrl string `protobuf:"bytes,3,opt,name=schema_url,json=schemaUrl,proto3" json:"schema_url,omitempty"` } -func (x *ScopeSpans) Reset() { - *x = ScopeSpans{} +func (x *InstrumentationLibrarySpans) Reset() { + *x = InstrumentationLibrarySpans{} if protoimpl.UnsafeEnabled { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) @@ -321,13 +327,13 @@ func (x *ScopeSpans) Reset() { } } -func (x *ScopeSpans) String() string { +func (x *InstrumentationLibrarySpans) String() string { return protoimpl.X.MessageStringOf(x) } -func (*ScopeSpans) ProtoMessage() {} +func (*InstrumentationLibrarySpans) ProtoMessage() {} -func (x *ScopeSpans) ProtoReflect() protoreflect.Message { +func (x *InstrumentationLibrarySpans) ProtoReflect() protoreflect.Message { mi := &file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) @@ -339,33 +345,39 @@ func (x *ScopeSpans) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use ScopeSpans.ProtoReflect.Descriptor instead. -func (*ScopeSpans) Descriptor() ([]byte, []int) { +// Deprecated: Use InstrumentationLibrarySpans.ProtoReflect.Descriptor instead. +func (*InstrumentationLibrarySpans) Descriptor() ([]byte, []int) { return file_opentelemetry_proto_trace_v1_trace_proto_rawDescGZIP(), []int{2} } -func (x *ScopeSpans) GetScope() *v11.InstrumentationScope { +func (x *InstrumentationLibrarySpans) GetInstrumentationLibrary() *v11.InstrumentationLibrary { if x != nil { - return x.Scope + return x.InstrumentationLibrary } return nil } -func (x *ScopeSpans) GetSpans() []*Span { +func (x *InstrumentationLibrarySpans) GetSpans() []*Span { if x != nil { return x.Spans } return nil } -func (x *ScopeSpans) GetSchemaUrl() string { +func (x *InstrumentationLibrarySpans) GetSchemaUrl() string { if x != nil { return x.SchemaUrl } return "" } -// A Span represents a single operation performed by a single component of the system. +// Span represents a single operation within a trace. Spans can be +// nested to form a trace tree. Spans may also be linked to other spans +// from the same or different trace and form graphs. Often, a trace +// contains a root span that describes the end-to-end latency, and one +// or more subspans for its sub-operations. A trace can also contain +// multiple root spans, or none at all. Spans do not need to be +// contiguous - there may be gaps or overlaps between spans in a trace. // // The next available field id is 17. type Span struct { @@ -437,9 +449,7 @@ type Span struct { // "abc.com/score": 10.239 // // The OpenTelemetry API specification further restricts the allowed value types: - // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/common/README.md#attribute - // Attribute keys MUST be unique (it is not allowed to have more than one - // attribute with the same key). + // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/common/common.md#attributes Attributes []*v11.KeyValue `protobuf:"bytes,9,rep,name=attributes,proto3" json:"attributes,omitempty"` // dropped_attributes_count is the number of attributes that were discarded. Attributes // can be discarded because their keys are too long or because there are too many @@ -670,8 +680,6 @@ type Span_Event struct { // This field is semantically required to be set to non-empty string. Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` // attributes is a collection of attribute key/value pairs on the event. - // Attribute keys MUST be unique (it is not allowed to have more than one - // attribute with the same key). Attributes []*v11.KeyValue `protobuf:"bytes,3,rep,name=attributes,proto3" json:"attributes,omitempty"` // dropped_attributes_count is the number of dropped attributes. If the value is 0, // then no attributes were dropped. @@ -755,8 +763,6 @@ type Span_Link struct { // The trace_state associated with the link. TraceState string `protobuf:"bytes,3,opt,name=trace_state,json=traceState,proto3" json:"trace_state,omitempty"` // attributes is a collection of attribute key/value pairs on the link. - // Attribute keys MUST be unique (it is not allowed to have more than one - // attribute with the same key). Attributes []*v11.KeyValue `protobuf:"bytes,4,rep,name=attributes,proto3" json:"attributes,omitempty"` // dropped_attributes_count is the number of dropped attributes. If the value is 0, // then no attributes were dropped. @@ -849,133 +855,137 @@ var file_opentelemetry_proto_trace_v1_trace_proto_rawDesc = []byte{ 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x52, 0x0d, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, - 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x22, 0xc8, 0x01, 0x0a, 0x0d, 0x52, 0x65, 0x73, 0x6f, 0x75, + 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x22, 0xf4, 0x01, 0x0a, 0x0d, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x45, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x29, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x52, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x52, 0x08, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, - 0x49, 0x0a, 0x0b, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x5f, 0x73, 0x70, 0x61, 0x6e, 0x73, 0x18, 0x02, - 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, - 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, - 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x52, 0x0a, - 0x73, 0x63, 0x6f, 0x70, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x63, - 0x68, 0x65, 0x6d, 0x61, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, - 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x55, 0x72, 0x6c, 0x4a, 0x06, 0x08, 0xe8, 0x07, 0x10, 0xe9, - 0x07, 0x22, 0xb0, 0x01, 0x0a, 0x0a, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x53, 0x70, 0x61, 0x6e, 0x73, - 0x12, 0x49, 0x0a, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x33, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, - 0x49, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, - 0x63, 0x6f, 0x70, 0x65, 0x52, 0x05, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x38, 0x0a, 0x05, 0x73, - 0x70, 0x61, 0x6e, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x6f, 0x70, 0x65, - 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x52, 0x05, - 0x73, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, - 0x75, 0x72, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x63, 0x68, 0x65, 0x6d, - 0x61, 0x55, 0x72, 0x6c, 0x22, 0x9c, 0x0a, 0x0a, 0x04, 0x53, 0x70, 0x61, 0x6e, 0x12, 0x19, 0x0a, - 0x08, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x07, 0x74, 0x72, 0x61, 0x63, 0x65, 0x49, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x73, 0x70, 0x61, 0x6e, - 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x73, 0x70, 0x61, 0x6e, 0x49, - 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x74, 0x72, 0x61, 0x63, 0x65, 0x53, 0x74, 0x61, - 0x74, 0x65, 0x12, 0x24, 0x0a, 0x0e, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x70, 0x61, - 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x70, 0x61, 0x72, 0x65, - 0x6e, 0x74, 0x53, 0x70, 0x61, 0x6e, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, - 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x3f, 0x0a, 0x04, - 0x6b, 0x69, 0x6e, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2b, 0x2e, 0x6f, 0x70, 0x65, - 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x2e, 0x53, - 0x70, 0x61, 0x6e, 0x4b, 0x69, 0x6e, 0x64, 0x52, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0x12, 0x2f, 0x0a, - 0x14, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, - 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x07, 0x20, 0x01, 0x28, 0x06, 0x52, 0x11, 0x73, 0x74, 0x61, - 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x2b, - 0x0a, 0x12, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, - 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x08, 0x20, 0x01, 0x28, 0x06, 0x52, 0x0f, 0x65, 0x6e, 0x64, 0x54, - 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x47, 0x0a, 0x0a, 0x61, - 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, - 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, - 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, - 0x75, 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, - 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, - 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, - 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x40, - 0x0a, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x28, + 0x7d, 0x0a, 0x1d, 0x69, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x5f, 0x6c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x5f, 0x73, 0x70, 0x61, 0x6e, 0x73, + 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x39, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, + 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, + 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x49, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, 0x74, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x53, 0x70, 0x61, 0x6e, + 0x73, 0x52, 0x1b, 0x69, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x4c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x1d, + 0x0a, 0x0a, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x09, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x55, 0x72, 0x6c, 0x22, 0xe6, 0x01, + 0x0a, 0x1b, 0x49, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x4c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x53, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x6e, 0x0a, + 0x17, 0x69, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x5f, 0x6c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x35, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, - 0x61, 0x6e, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, - 0x12, 0x30, 0x0a, 0x14, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x65, 0x76, 0x65, 0x6e, - 0x74, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x12, - 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x43, 0x6f, 0x75, - 0x6e, 0x74, 0x12, 0x3d, 0x0a, 0x05, 0x6c, 0x69, 0x6e, 0x6b, 0x73, 0x18, 0x0d, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, - 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, - 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x2e, 0x4c, 0x69, 0x6e, 0x6b, 0x52, 0x05, 0x6c, 0x69, 0x6e, 0x6b, - 0x73, 0x12, 0x2e, 0x0a, 0x13, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x6c, 0x69, 0x6e, - 0x6b, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x11, - 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x4c, 0x69, 0x6e, 0x6b, 0x73, 0x43, 0x6f, 0x75, 0x6e, - 0x74, 0x12, 0x3c, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x0f, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x24, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, - 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, - 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x1a, - 0xc4, 0x01, 0x0a, 0x05, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x24, 0x0a, 0x0e, 0x74, 0x69, 0x6d, - 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x06, 0x52, 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, - 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, - 0x61, 0x6d, 0x65, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, - 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, - 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, - 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, - 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, - 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, - 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x1a, 0xde, 0x01, 0x0a, 0x04, 0x4c, 0x69, 0x6e, 0x6b, 0x12, + 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x49, + 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4c, 0x69, + 0x62, 0x72, 0x61, 0x72, 0x79, 0x52, 0x16, 0x69, 0x6e, 0x73, 0x74, 0x72, 0x75, 0x6d, 0x65, 0x6e, + 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4c, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x12, 0x38, 0x0a, + 0x05, 0x73, 0x70, 0x61, 0x6e, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x6f, + 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, + 0x52, 0x05, 0x73, 0x70, 0x61, 0x6e, 0x73, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x63, 0x68, 0x65, 0x6d, + 0x61, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x63, 0x68, + 0x65, 0x6d, 0x61, 0x55, 0x72, 0x6c, 0x22, 0x9c, 0x0a, 0x0a, 0x04, 0x53, 0x70, 0x61, 0x6e, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x74, 0x72, 0x61, 0x63, 0x65, 0x49, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x73, 0x70, 0x61, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x73, 0x70, 0x61, 0x6e, 0x49, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x74, 0x72, 0x61, 0x63, 0x65, 0x53, - 0x74, 0x61, 0x74, 0x65, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, - 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, - 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, - 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, - 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, - 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0d, 0x52, - 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, - 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0x99, 0x01, 0x0a, 0x08, 0x53, 0x70, 0x61, 0x6e, - 0x4b, 0x69, 0x6e, 0x64, 0x12, 0x19, 0x0a, 0x15, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, - 0x44, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, - 0x16, 0x0a, 0x12, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x49, 0x4e, 0x54, - 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x10, 0x01, 0x12, 0x14, 0x0a, 0x10, 0x53, 0x50, 0x41, 0x4e, 0x5f, - 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x53, 0x45, 0x52, 0x56, 0x45, 0x52, 0x10, 0x02, 0x12, 0x14, 0x0a, - 0x10, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x43, 0x4c, 0x49, 0x45, 0x4e, - 0x54, 0x10, 0x03, 0x12, 0x16, 0x0a, 0x12, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, - 0x5f, 0x50, 0x52, 0x4f, 0x44, 0x55, 0x43, 0x45, 0x52, 0x10, 0x04, 0x12, 0x16, 0x0a, 0x12, 0x53, - 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x43, 0x4f, 0x4e, 0x53, 0x55, 0x4d, 0x45, - 0x52, 0x10, 0x05, 0x22, 0xbd, 0x01, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x18, - 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x43, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, - 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, - 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x53, 0x74, 0x61, - 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x4e, 0x0a, - 0x0a, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x15, 0x0a, 0x11, 0x53, - 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x43, 0x4f, 0x44, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x45, 0x54, - 0x10, 0x00, 0x12, 0x12, 0x0a, 0x0e, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x43, 0x4f, 0x44, - 0x45, 0x5f, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x15, 0x0a, 0x11, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, - 0x5f, 0x43, 0x4f, 0x44, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x4a, 0x04, 0x08, - 0x01, 0x10, 0x02, 0x42, 0x77, 0x0a, 0x1f, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, - 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, - 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x42, 0x0a, 0x54, 0x72, 0x61, 0x63, 0x65, 0x50, 0x72, 0x6f, - 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x27, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, - 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, - 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0xaa, 0x02, 0x1c, - 0x4f, 0x70, 0x65, 0x6e, 0x54, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x50, 0x72, - 0x6f, 0x74, 0x6f, 0x2e, 0x54, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x56, 0x31, 0x62, 0x06, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x33, + 0x74, 0x61, 0x74, 0x65, 0x12, 0x24, 0x0a, 0x0e, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x73, + 0x70, 0x61, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0c, 0x70, 0x61, + 0x72, 0x65, 0x6e, 0x74, 0x53, 0x70, 0x61, 0x6e, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, + 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x3f, + 0x0a, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2b, 0x2e, 0x6f, + 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, + 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x4b, 0x69, 0x6e, 0x64, 0x52, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0x12, + 0x2f, 0x0a, 0x14, 0x73, 0x74, 0x61, 0x72, 0x74, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, + 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x07, 0x20, 0x01, 0x28, 0x06, 0x52, 0x11, 0x73, + 0x74, 0x61, 0x72, 0x74, 0x54, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, + 0x12, 0x2b, 0x0a, 0x12, 0x65, 0x6e, 0x64, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, + 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x08, 0x20, 0x01, 0x28, 0x06, 0x52, 0x0f, 0x65, 0x6e, + 0x64, 0x54, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, 0x6f, 0x12, 0x47, 0x0a, + 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x18, 0x09, 0x20, 0x03, 0x28, + 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, + 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, + 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, + 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, + 0x64, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, + 0x6e, 0x74, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, + 0x64, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, + 0x12, 0x40, 0x0a, 0x06, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x28, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, + 0x53, 0x70, 0x61, 0x6e, 0x2e, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x65, 0x76, 0x65, 0x6e, + 0x74, 0x73, 0x12, 0x30, 0x0a, 0x14, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x65, 0x76, + 0x65, 0x6e, 0x74, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0d, + 0x52, 0x12, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x43, + 0x6f, 0x75, 0x6e, 0x74, 0x12, 0x3d, 0x0a, 0x05, 0x6c, 0x69, 0x6e, 0x6b, 0x73, 0x18, 0x0d, 0x20, + 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, + 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, + 0x76, 0x31, 0x2e, 0x53, 0x70, 0x61, 0x6e, 0x2e, 0x4c, 0x69, 0x6e, 0x6b, 0x52, 0x05, 0x6c, 0x69, + 0x6e, 0x6b, 0x73, 0x12, 0x2e, 0x0a, 0x13, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x6c, + 0x69, 0x6e, 0x6b, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0d, + 0x52, 0x11, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x4c, 0x69, 0x6e, 0x6b, 0x73, 0x43, 0x6f, + 0x75, 0x6e, 0x74, 0x12, 0x3c, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x0f, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x24, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, + 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, + 0x76, 0x31, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, + 0x73, 0x1a, 0xc4, 0x01, 0x0a, 0x05, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x24, 0x0a, 0x0e, 0x74, + 0x69, 0x6d, 0x65, 0x5f, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6e, 0x61, 0x6e, 0x6f, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x06, 0x52, 0x0c, 0x74, 0x69, 0x6d, 0x65, 0x55, 0x6e, 0x69, 0x78, 0x4e, 0x61, 0x6e, + 0x6f, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, + 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, 0x6e, + 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, + 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, 0x6c, + 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, 0x38, + 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, + 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, + 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, + 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x1a, 0xde, 0x01, 0x0a, 0x04, 0x4c, 0x69, 0x6e, + 0x6b, 0x12, 0x19, 0x0a, 0x08, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x0c, 0x52, 0x07, 0x74, 0x72, 0x61, 0x63, 0x65, 0x49, 0x64, 0x12, 0x17, 0x0a, 0x07, + 0x73, 0x70, 0x61, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x73, + 0x70, 0x61, 0x6e, 0x49, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x74, 0x72, 0x61, 0x63, 0x65, 0x5f, 0x73, + 0x74, 0x61, 0x74, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x74, 0x72, 0x61, 0x63, + 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x47, 0x0a, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, + 0x75, 0x74, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x6f, 0x70, 0x65, + 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x76, 0x31, 0x2e, 0x4b, 0x65, 0x79, 0x56, 0x61, + 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, + 0x38, 0x0a, 0x18, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x74, 0x72, 0x69, + 0x62, 0x75, 0x74, 0x65, 0x73, 0x5f, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, + 0x0d, 0x52, 0x16, 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, + 0x75, 0x74, 0x65, 0x73, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x22, 0x99, 0x01, 0x0a, 0x08, 0x53, 0x70, + 0x61, 0x6e, 0x4b, 0x69, 0x6e, 0x64, 0x12, 0x19, 0x0a, 0x15, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, + 0x49, 0x4e, 0x44, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, + 0x00, 0x12, 0x16, 0x0a, 0x12, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x49, + 0x4e, 0x54, 0x45, 0x52, 0x4e, 0x41, 0x4c, 0x10, 0x01, 0x12, 0x14, 0x0a, 0x10, 0x53, 0x50, 0x41, + 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x53, 0x45, 0x52, 0x56, 0x45, 0x52, 0x10, 0x02, 0x12, + 0x14, 0x0a, 0x10, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x43, 0x4c, 0x49, + 0x45, 0x4e, 0x54, 0x10, 0x03, 0x12, 0x16, 0x0a, 0x12, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, + 0x4e, 0x44, 0x5f, 0x50, 0x52, 0x4f, 0x44, 0x55, 0x43, 0x45, 0x52, 0x10, 0x04, 0x12, 0x16, 0x0a, + 0x12, 0x53, 0x50, 0x41, 0x4e, 0x5f, 0x4b, 0x49, 0x4e, 0x44, 0x5f, 0x43, 0x4f, 0x4e, 0x53, 0x55, + 0x4d, 0x45, 0x52, 0x10, 0x05, 0x22, 0xbd, 0x01, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, + 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x43, 0x0a, 0x04, 0x63, 0x6f, + 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, + 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x74, + 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x53, + 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x22, + 0x4e, 0x0a, 0x0a, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x15, 0x0a, + 0x11, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x43, 0x4f, 0x44, 0x45, 0x5f, 0x55, 0x4e, 0x53, + 0x45, 0x54, 0x10, 0x00, 0x12, 0x12, 0x0a, 0x0e, 0x53, 0x54, 0x41, 0x54, 0x55, 0x53, 0x5f, 0x43, + 0x4f, 0x44, 0x45, 0x5f, 0x4f, 0x4b, 0x10, 0x01, 0x12, 0x15, 0x0a, 0x11, 0x53, 0x54, 0x41, 0x54, + 0x55, 0x53, 0x5f, 0x43, 0x4f, 0x44, 0x45, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x02, 0x4a, + 0x04, 0x08, 0x01, 0x10, 0x02, 0x42, 0x58, 0x0a, 0x1f, 0x69, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, + 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, + 0x74, 0x72, 0x61, 0x63, 0x65, 0x2e, 0x76, 0x31, 0x42, 0x0a, 0x54, 0x72, 0x61, 0x63, 0x65, 0x50, + 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x27, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65, 0x6e, 0x74, + 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x2f, 0x6f, 0x74, 0x6c, 0x70, 0x2f, 0x74, 0x72, 0x61, 0x63, 0x65, 0x2f, 0x76, 0x31, 0x62, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -993,25 +1003,25 @@ func file_opentelemetry_proto_trace_v1_trace_proto_rawDescGZIP() []byte { var file_opentelemetry_proto_trace_v1_trace_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_opentelemetry_proto_trace_v1_trace_proto_msgTypes = make([]protoimpl.MessageInfo, 7) var file_opentelemetry_proto_trace_v1_trace_proto_goTypes = []interface{}{ - (Span_SpanKind)(0), // 0: opentelemetry.proto.trace.v1.Span.SpanKind - (Status_StatusCode)(0), // 1: opentelemetry.proto.trace.v1.Status.StatusCode - (*TracesData)(nil), // 2: opentelemetry.proto.trace.v1.TracesData - (*ResourceSpans)(nil), // 3: opentelemetry.proto.trace.v1.ResourceSpans - (*ScopeSpans)(nil), // 4: opentelemetry.proto.trace.v1.ScopeSpans - (*Span)(nil), // 5: opentelemetry.proto.trace.v1.Span - (*Status)(nil), // 6: opentelemetry.proto.trace.v1.Status - (*Span_Event)(nil), // 7: opentelemetry.proto.trace.v1.Span.Event - (*Span_Link)(nil), // 8: opentelemetry.proto.trace.v1.Span.Link - (*v1.Resource)(nil), // 9: opentelemetry.proto.resource.v1.Resource - (*v11.InstrumentationScope)(nil), // 10: opentelemetry.proto.common.v1.InstrumentationScope - (*v11.KeyValue)(nil), // 11: opentelemetry.proto.common.v1.KeyValue + (Span_SpanKind)(0), // 0: opentelemetry.proto.trace.v1.Span.SpanKind + (Status_StatusCode)(0), // 1: opentelemetry.proto.trace.v1.Status.StatusCode + (*TracesData)(nil), // 2: opentelemetry.proto.trace.v1.TracesData + (*ResourceSpans)(nil), // 3: opentelemetry.proto.trace.v1.ResourceSpans + (*InstrumentationLibrarySpans)(nil), // 4: opentelemetry.proto.trace.v1.InstrumentationLibrarySpans + (*Span)(nil), // 5: opentelemetry.proto.trace.v1.Span + (*Status)(nil), // 6: opentelemetry.proto.trace.v1.Status + (*Span_Event)(nil), // 7: opentelemetry.proto.trace.v1.Span.Event + (*Span_Link)(nil), // 8: opentelemetry.proto.trace.v1.Span.Link + (*v1.Resource)(nil), // 9: opentelemetry.proto.resource.v1.Resource + (*v11.InstrumentationLibrary)(nil), // 10: opentelemetry.proto.common.v1.InstrumentationLibrary + (*v11.KeyValue)(nil), // 11: opentelemetry.proto.common.v1.KeyValue } var file_opentelemetry_proto_trace_v1_trace_proto_depIdxs = []int32{ 3, // 0: opentelemetry.proto.trace.v1.TracesData.resource_spans:type_name -> opentelemetry.proto.trace.v1.ResourceSpans 9, // 1: opentelemetry.proto.trace.v1.ResourceSpans.resource:type_name -> opentelemetry.proto.resource.v1.Resource - 4, // 2: opentelemetry.proto.trace.v1.ResourceSpans.scope_spans:type_name -> opentelemetry.proto.trace.v1.ScopeSpans - 10, // 3: opentelemetry.proto.trace.v1.ScopeSpans.scope:type_name -> opentelemetry.proto.common.v1.InstrumentationScope - 5, // 4: opentelemetry.proto.trace.v1.ScopeSpans.spans:type_name -> opentelemetry.proto.trace.v1.Span + 4, // 2: opentelemetry.proto.trace.v1.ResourceSpans.instrumentation_library_spans:type_name -> opentelemetry.proto.trace.v1.InstrumentationLibrarySpans + 10, // 3: opentelemetry.proto.trace.v1.InstrumentationLibrarySpans.instrumentation_library:type_name -> opentelemetry.proto.common.v1.InstrumentationLibrary + 5, // 4: opentelemetry.proto.trace.v1.InstrumentationLibrarySpans.spans:type_name -> opentelemetry.proto.trace.v1.Span 0, // 5: opentelemetry.proto.trace.v1.Span.kind:type_name -> opentelemetry.proto.trace.v1.Span.SpanKind 11, // 6: opentelemetry.proto.trace.v1.Span.attributes:type_name -> opentelemetry.proto.common.v1.KeyValue 7, // 7: opentelemetry.proto.trace.v1.Span.events:type_name -> opentelemetry.proto.trace.v1.Span.Event @@ -1058,7 +1068,7 @@ func file_opentelemetry_proto_trace_v1_trace_proto_init() { } } file_opentelemetry_proto_trace_v1_trace_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ScopeSpans); i { + switch v := v.(*InstrumentationLibrarySpans); i { case 0: return &v.state case 1: diff --git a/vendor/google.golang.org/grpc/attributes/attributes.go b/vendor/google.golang.org/grpc/attributes/attributes.go index 02f5dc5318914..ae13ddac14e02 100644 --- a/vendor/google.golang.org/grpc/attributes/attributes.go +++ b/vendor/google.golang.org/grpc/attributes/attributes.go @@ -19,7 +19,7 @@ // Package attributes defines a generic key/value store used in various gRPC // components. // -// # Experimental +// Experimental // // Notice: This package is EXPERIMENTAL and may be changed or removed in a // later release. diff --git a/vendor/google.golang.org/grpc/backoff.go b/vendor/google.golang.org/grpc/backoff.go index 29475e31c979e..542594f5cc512 100644 --- a/vendor/google.golang.org/grpc/backoff.go +++ b/vendor/google.golang.org/grpc/backoff.go @@ -48,7 +48,7 @@ type BackoffConfig struct { // here for more details: // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. diff --git a/vendor/google.golang.org/grpc/balancer/balancer.go b/vendor/google.golang.org/grpc/balancer/balancer.go index 09d61dd1b55b4..f4f9408f38529 100644 --- a/vendor/google.golang.org/grpc/balancer/balancer.go +++ b/vendor/google.golang.org/grpc/balancer/balancer.go @@ -110,11 +110,6 @@ type SubConn interface { UpdateAddresses([]resolver.Address) // Connect starts the connecting for this SubConn. Connect() - // GetOrBuildProducer returns a reference to the existing Producer for this - // ProducerBuilder in this SubConn, or, if one does not currently exist, - // creates a new one and returns it. Returns a close function which must - // be called when the Producer is no longer needed. - GetOrBuildProducer(ProducerBuilder) (p Producer, close func()) } // NewSubConnOptions contains options to create new SubConn. @@ -279,14 +274,6 @@ type PickResult struct { // type, Done may not be called. May be nil if the balancer does not wish // to be notified when the RPC completes. Done func(DoneInfo) - - // Metadata provides a way for LB policies to inject arbitrary per-call - // metadata. Any metadata returned here will be merged with existing - // metadata added by the client application. - // - // LB policies with child policies are responsible for propagating metadata - // injected by their children to the ClientConn, as part of Pick(). - Metatada metadata.MD } // TransientFailureError returns e. It exists for backward compatibility and @@ -384,21 +371,3 @@ type ClientConnState struct { // ErrBadResolverState may be returned by UpdateClientConnState to indicate a // problem with the provided name resolver data. var ErrBadResolverState = errors.New("bad resolver state") - -// A ProducerBuilder is a simple constructor for a Producer. It is used by the -// SubConn to create producers when needed. -type ProducerBuilder interface { - // Build creates a Producer. The first parameter is always a - // grpc.ClientConnInterface (a type to allow creating RPCs/streams on the - // associated SubConn), but is declared as interface{} to avoid a - // dependency cycle. Should also return a close function that will be - // called when all references to the Producer have been given up. - Build(grpcClientConnInterface interface{}) (p Producer, close func()) -} - -// A Producer is a type shared among potentially many consumers. It is -// associated with a SubConn, and an implementation will typically contain -// other methods to provide additional functionality, e.g. configuration or -// subscription registration. -type Producer interface { -} diff --git a/vendor/google.golang.org/grpc/balancer/base/balancer.go b/vendor/google.golang.org/grpc/balancer/base/balancer.go index 3929c26d31e1c..e8dfc828aaacb 100644 --- a/vendor/google.golang.org/grpc/balancer/base/balancer.go +++ b/vendor/google.golang.org/grpc/balancer/base/balancer.go @@ -157,8 +157,8 @@ func (b *baseBalancer) mergeErrors() error { // regeneratePicker takes a snapshot of the balancer, and generates a picker // from it. The picker is -// - errPicker if the balancer is in TransientFailure, -// - built by the pickerBuilder with all READY SubConns otherwise. +// - errPicker if the balancer is in TransientFailure, +// - built by the pickerBuilder with all READY SubConns otherwise. func (b *baseBalancer) regeneratePicker() { if b.state == connectivity.TransientFailure { b.picker = NewErrPicker(b.mergeErrors()) diff --git a/vendor/google.golang.org/grpc/balancer/conn_state_evaluator.go b/vendor/google.golang.org/grpc/balancer/conn_state_evaluator.go index c33413581091e..a87b6809af386 100644 --- a/vendor/google.golang.org/grpc/balancer/conn_state_evaluator.go +++ b/vendor/google.golang.org/grpc/balancer/conn_state_evaluator.go @@ -34,10 +34,10 @@ type ConnectivityStateEvaluator struct { // RecordTransition records state change happening in subConn and based on that // it evaluates what aggregated state should be. // -// - If at least one SubConn in Ready, the aggregated state is Ready; -// - Else if at least one SubConn in Connecting, the aggregated state is Connecting; -// - Else if at least one SubConn is Idle, the aggregated state is Idle; -// - Else if at least one SubConn is TransientFailure (or there are no SubConns), the aggregated state is Transient Failure. +// - If at least one SubConn in Ready, the aggregated state is Ready; +// - Else if at least one SubConn in Connecting, the aggregated state is Connecting; +// - Else if at least one SubConn is Idle, the aggregated state is Idle; +// - Else if at least one SubConn is TransientFailure (or there are no SubConns), the aggregated state is Transient Failure. // // Shutdown is not considered. func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState connectivity.State) connectivity.State { @@ -55,11 +55,7 @@ func (cse *ConnectivityStateEvaluator) RecordTransition(oldState, newState conne cse.numIdle += updateVal } } - return cse.CurrentState() -} -// CurrentState returns the current aggregate conn state by evaluating the counters -func (cse *ConnectivityStateEvaluator) CurrentState() connectivity.State { // Evaluate. if cse.numReady > 0 { return connectivity.Ready diff --git a/vendor/google.golang.org/grpc/balancer/grpclb/grpc_lb_v1/load_balancer.pb.go b/vendor/google.golang.org/grpc/balancer/grpclb/grpc_lb_v1/load_balancer.pb.go index 1205aff23f792..c393d7ffd3b2e 100644 --- a/vendor/google.golang.org/grpc/balancer/grpclb/grpc_lb_v1/load_balancer.pb.go +++ b/vendor/google.golang.org/grpc/balancer/grpclb/grpc_lb_v1/load_balancer.pb.go @@ -19,13 +19,14 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 +// protoc-gen-go v1.25.0 // protoc v3.14.0 // source: grpc/lb/v1/load_balancer.proto package grpc_lb_v1 import ( + proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" durationpb "google.golang.org/protobuf/types/known/durationpb" @@ -41,13 +42,16 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + type LoadBalanceRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to LoadBalanceRequestType: - // // *LoadBalanceRequest_InitialRequest // *LoadBalanceRequest_ClientStats LoadBalanceRequestType isLoadBalanceRequest_LoadBalanceRequestType `protobuf_oneof:"load_balance_request_type"` @@ -336,7 +340,6 @@ type LoadBalanceResponse struct { unknownFields protoimpl.UnknownFields // Types that are assignable to LoadBalanceResponseType: - // // *LoadBalanceResponse_InitialResponse // *LoadBalanceResponse_ServerList // *LoadBalanceResponse_FallbackResponse diff --git a/vendor/google.golang.org/grpc/balancer/grpclb/grpclb.go b/vendor/google.golang.org/grpc/balancer/grpclb/grpclb.go index 6d698229a342a..6c3402e36c605 100644 --- a/vendor/google.golang.org/grpc/balancer/grpclb/grpclb.go +++ b/vendor/google.golang.org/grpc/balancer/grpclb/grpclb.go @@ -19,8 +19,7 @@ // Package grpclb defines a grpclb balancer. // // To install grpclb balancer, import this package as: -// -// import _ "google.golang.org/grpc/balancer/grpclb" +// import _ "google.golang.org/grpc/balancer/grpclb" package grpclb import ( @@ -136,8 +135,8 @@ func (b *lbBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) bal lb := &lbBalancer{ cc: newLBCacheClientConn(cc), - dialTarget: opt.Target.Endpoint(), - target: opt.Target.Endpoint(), + dialTarget: opt.Target.Endpoint, + target: opt.Target.Endpoint, opt: opt, fallbackTimeout: b.fallbackTimeout, doneCh: make(chan struct{}), @@ -230,9 +229,8 @@ type lbBalancer struct { // regeneratePicker takes a snapshot of the balancer, and generates a picker from // it. The picker -// - always returns ErrTransientFailure if the balancer is in TransientFailure, -// - does two layer roundrobin pick otherwise. -// +// - always returns ErrTransientFailure if the balancer is in TransientFailure, +// - does two layer roundrobin pick otherwise. // Caller must hold lb.mu. func (lb *lbBalancer) regeneratePicker(resetDrop bool) { if lb.state == connectivity.TransientFailure { @@ -292,14 +290,14 @@ func (lb *lbBalancer) regeneratePicker(resetDrop bool) { // fallback and grpclb). lb.scState contains states for all SubConns, including // those in cache (SubConns are cached for 10 seconds after remove). // -// The aggregated state is: -// - If at least one SubConn in Ready, the aggregated state is Ready; -// - Else if at least one SubConn in Connecting or IDLE, the aggregated state is Connecting; -// - It's OK to consider IDLE as Connecting. SubConns never stay in IDLE, -// they start to connect immediately. But there's a race between the overall -// state is reported, and when the new SubConn state arrives. And SubConns -// never go back to IDLE. -// - Else the aggregated state is TransientFailure. +// The aggregated state is: +// - If at least one SubConn in Ready, the aggregated state is Ready; +// - Else if at least one SubConn in Connecting or IDLE, the aggregated state is Connecting; +// - It's OK to consider IDLE as Connecting. SubConns never stay in IDLE, +// they start to connect immediately. But there's a race between the overall +// state is reported, and when the new SubConn state arrives. And SubConns +// never go back to IDLE. +// - Else the aggregated state is TransientFailure. func (lb *lbBalancer) aggregateSubConnStates() connectivity.State { var numConnecting uint64 diff --git a/vendor/google.golang.org/grpc/balancer/grpclb/grpclb_remote_balancer.go b/vendor/google.golang.org/grpc/balancer/grpclb/grpclb_remote_balancer.go index e56006d7131a8..dab1959418e12 100644 --- a/vendor/google.golang.org/grpc/balancer/grpclb/grpclb_remote_balancer.go +++ b/vendor/google.golang.org/grpc/balancer/grpclb/grpclb_remote_balancer.go @@ -332,7 +332,7 @@ func (ccw *remoteBalancerCCWrapper) callRemoteBalancer(ctx context.Context) (bac lbClient := &loadBalancerClient{cc: ccw.cc} stream, err := lbClient.BalanceLoad(ctx, grpc.WaitForReady(true)) if err != nil { - return true, fmt.Errorf("grpclb: failed to perform RPC to the remote balancer: %v", err) + return true, fmt.Errorf("grpclb: failed to perform RPC to the remote balancer %v", err) } ccw.lb.mu.Lock() ccw.lb.remoteBalancerConnected = true diff --git a/vendor/google.golang.org/grpc/balancer_conn_wrappers.go b/vendor/google.golang.org/grpc/balancer_conn_wrappers.go index 0359956d36fa3..b1c23eaae0db2 100644 --- a/vendor/google.golang.org/grpc/balancer_conn_wrappers.go +++ b/vendor/google.golang.org/grpc/balancer_conn_wrappers.go @@ -19,20 +19,17 @@ package grpc import ( - "context" "fmt" "strings" "sync" "google.golang.org/grpc/balancer" - "google.golang.org/grpc/codes" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/internal/balancer/gracefulswitch" "google.golang.org/grpc/internal/buffer" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/resolver" - "google.golang.org/grpc/status" ) // ccBalancerWrapper sits between the ClientConn and the Balancer. @@ -308,7 +305,7 @@ func (ccb *ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer channelz.Warningf(logger, ccb.cc.channelzID, "acBalancerWrapper: NewSubConn: failed to newAddrConn: %v", err) return nil, err } - acbw := &acBalancerWrapper{ac: ac, producers: make(map[balancer.ProducerBuilder]*refCountedProducer)} + acbw := &acBalancerWrapper{ac: ac} acbw.ac.mu.Lock() ac.acbw = acbw acbw.ac.mu.Unlock() @@ -362,9 +359,8 @@ func (ccb *ccBalancerWrapper) Target() string { // acBalancerWrapper is a wrapper on top of ac for balancers. // It implements balancer.SubConn interface. type acBalancerWrapper struct { - mu sync.Mutex - ac *addrConn - producers map[balancer.ProducerBuilder]*refCountedProducer + mu sync.Mutex + ac *addrConn } func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { @@ -418,64 +414,3 @@ func (acbw *acBalancerWrapper) getAddrConn() *addrConn { defer acbw.mu.Unlock() return acbw.ac } - -var errSubConnNotReady = status.Error(codes.Unavailable, "SubConn not currently connected") - -// NewStream begins a streaming RPC on the addrConn. If the addrConn is not -// ready, returns errSubConnNotReady. -func (acbw *acBalancerWrapper) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) { - transport := acbw.ac.getReadyTransport() - if transport == nil { - return nil, errSubConnNotReady - } - return newNonRetryClientStream(ctx, desc, method, transport, acbw.ac, opts...) -} - -// Invoke performs a unary RPC. If the addrConn is not ready, returns -// errSubConnNotReady. -func (acbw *acBalancerWrapper) Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...CallOption) error { - cs, err := acbw.NewStream(ctx, unaryStreamDesc, method, opts...) - if err != nil { - return err - } - if err := cs.SendMsg(args); err != nil { - return err - } - return cs.RecvMsg(reply) -} - -type refCountedProducer struct { - producer balancer.Producer - refs int // number of current refs to the producer - close func() // underlying producer's close function -} - -func (acbw *acBalancerWrapper) GetOrBuildProducer(pb balancer.ProducerBuilder) (balancer.Producer, func()) { - acbw.mu.Lock() - defer acbw.mu.Unlock() - - // Look up existing producer from this builder. - pData := acbw.producers[pb] - if pData == nil { - // Not found; create a new one and add it to the producers map. - p, close := pb.Build(acbw) - pData = &refCountedProducer{producer: p, close: close} - acbw.producers[pb] = pData - } - // Account for this new reference. - pData.refs++ - - // Return a cleanup function wrapped in a OnceFunc to remove this reference - // and delete the refCountedProducer from the map if the total reference - // count goes to zero. - unref := func() { - acbw.mu.Lock() - pData.refs-- - if pData.refs == 0 { - defer pData.close() // Run outside the acbw mutex - delete(acbw.producers, pb) - } - acbw.mu.Unlock() - } - return pData.producer, grpcsync.OnceFunc(unref) -} diff --git a/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go b/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go index 66d141fce707b..ed75290cdf347 100644 --- a/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go +++ b/vendor/google.golang.org/grpc/binarylog/grpc_binarylog_v1/binarylog.pb.go @@ -18,13 +18,14 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 +// protoc-gen-go v1.25.0 // protoc v3.14.0 // source: grpc/binlog/v1/binarylog.proto package grpc_binarylog_v1 import ( + proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" durationpb "google.golang.org/protobuf/types/known/durationpb" @@ -40,6 +41,10 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + // Enumerates the type of event // Note the terminology is different from the RPC semantics // definition, but the same meaning is expressed here. @@ -256,7 +261,6 @@ type GrpcLogEntry struct { // according to the type of the log entry. // // Types that are assignable to Payload: - // // *GrpcLogEntry_ClientHeader // *GrpcLogEntry_ServerHeader // *GrpcLogEntry_Message @@ -690,12 +694,12 @@ func (x *Message) GetData() []byte { // Header keys added by gRPC are omitted. To be more specific, // implementations will not log the following entries, and this is // not to be treated as a truncation: -// - entries handled by grpc that are not user visible, such as those -// that begin with 'grpc-' (with exception of grpc-trace-bin) -// or keys like 'lb-token' -// - transport specific entries, including but not limited to: -// ':path', ':authority', 'content-encoding', 'user-agent', 'te', etc -// - entries added for call credentials +// - entries handled by grpc that are not user visible, such as those +// that begin with 'grpc-' (with exception of grpc-trace-bin) +// or keys like 'lb-token' +// - transport specific entries, including but not limited to: +// ':path', ':authority', 'content-encoding', 'user-agent', 'te', etc +// - entries added for call credentials // // Implementations must always log grpc-trace-bin if it is present. // Practically speaking it will only be visible on server side because diff --git a/vendor/google.golang.org/grpc/channelz/channelz.go b/vendor/google.golang.org/grpc/channelz/channelz.go index 32b7fa5794e18..a220c47c59a50 100644 --- a/vendor/google.golang.org/grpc/channelz/channelz.go +++ b/vendor/google.golang.org/grpc/channelz/channelz.go @@ -23,7 +23,7 @@ // https://github.com/grpc/proposal/blob/master/A14-channelz.md, is provided by // the `internal/channelz` package. // -// # Experimental +// Experimental // // Notice: All APIs in this package are experimental and may be removed in a // later release. diff --git a/vendor/google.golang.org/grpc/clientconn.go b/vendor/google.golang.org/grpc/clientconn.go index d607d4e9e243e..779b03bca1c31 100644 --- a/vendor/google.golang.org/grpc/clientconn.go +++ b/vendor/google.golang.org/grpc/clientconn.go @@ -256,7 +256,7 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * if err != nil { return nil, err } - cc.authority, err = determineAuthority(cc.parsedTarget.Endpoint(), cc.target, cc.dopts) + cc.authority, err = determineAuthority(cc.parsedTarget.Endpoint, cc.target, cc.dopts) if err != nil { return nil, err } @@ -503,7 +503,7 @@ type ClientConn struct { // WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or // ctx expires. A true value is returned in former case and false in latter. // -// # Experimental +// Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. @@ -522,7 +522,7 @@ func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connec // GetState returns the connectivity.State of ClientConn. // -// # Experimental +// Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a later // release. @@ -534,7 +534,7 @@ func (cc *ClientConn) GetState() connectivity.State { // the channel is idle. Does not wait for the connection attempts to begin // before returning. // -// # Experimental +// Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a later // release. @@ -761,7 +761,7 @@ func (cc *ClientConn) channelzMetric() *channelz.ChannelInternalMetric { // Target returns the target string of the ClientConn. // -// # Experimental +// Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. @@ -788,16 +788,10 @@ func (cc *ClientConn) incrCallsFailed() { func (ac *addrConn) connect() error { ac.mu.Lock() if ac.state == connectivity.Shutdown { - if logger.V(2) { - logger.Infof("connect called on shutdown addrConn; ignoring.") - } ac.mu.Unlock() return errConnClosing } if ac.state != connectivity.Idle { - if logger.V(2) { - logger.Infof("connect called on addrConn in non-idle state (%v); ignoring.", ac.state) - } ac.mu.Unlock() return nil } @@ -837,9 +831,9 @@ func equalAddresses(a, b []resolver.Address) bool { // // If ac is Ready, it checks whether current connected address of ac is in the // new addrs list. -// - If true, it updates ac.addrs and returns true. The ac will keep using -// the existing connection. -// - If false, it does nothing and returns false. +// - If true, it updates ac.addrs and returns true. The ac will keep using +// the existing connection. +// - If false, it does nothing and returns false. func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool { ac.mu.Lock() defer ac.mu.Unlock() @@ -934,7 +928,7 @@ func (cc *ClientConn) healthCheckConfig() *healthCheckConfig { return cc.sc.healthCheckConfig } -func (cc *ClientConn) getTransport(ctx context.Context, failfast bool, method string) (transport.ClientTransport, balancer.PickResult, error) { +func (cc *ClientConn) getTransport(ctx context.Context, failfast bool, method string) (transport.ClientTransport, func(balancer.DoneInfo), error) { return cc.blockingpicker.pick(ctx, failfast, balancer.PickInfo{ Ctx: ctx, FullMethodName: method, @@ -1004,7 +998,7 @@ func (cc *ClientConn) resolveNow(o resolver.ResolveNowOptions) { // However, if a previously unavailable network becomes available, this may be // used to trigger an immediate reconnect. // -// # Experimental +// Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. @@ -1234,79 +1228,111 @@ func (ac *addrConn) tryAllAddrs(addrs []resolver.Address, connectDeadline time.T // address was not successfully connected, or updates ac appropriately with the // new transport. func (ac *addrConn) createTransport(addr resolver.Address, copts transport.ConnectOptions, connectDeadline time.Time) error { + // TODO: Delete prefaceReceived and move the logic to wait for it into the + // transport. + prefaceReceived := grpcsync.NewEvent() + connClosed := grpcsync.NewEvent() + addr.ServerName = ac.cc.getServerName(addr) hctx, hcancel := context.WithCancel(ac.ctx) + hcStarted := false // protected by ac.mu - onClose := func(r transport.GoAwayReason) { + onClose := func() { ac.mu.Lock() defer ac.mu.Unlock() - // adjust params based on GoAwayReason - ac.adjustParams(r) - if ac.state == connectivity.Shutdown { - // Already shut down. tearDown() already cleared the transport and - // canceled hctx via ac.ctx, and we expected this connection to be - // closed, so do nothing here. - return - } - hcancel() - if ac.transport == nil { - // We're still connecting to this address, which could error. Do - // not update the connectivity state or resolve; these will happen - // at the end of the tryAllAddrs connection loop in the event of an - // error. + defer connClosed.Fire() + defer hcancel() + if !hcStarted || hctx.Err() != nil { + // We didn't start the health check or set the state to READY, so + // no need to do anything else here. + // + // OR, we have already cancelled the health check context, meaning + // we have already called onClose once for this transport. In this + // case it would be dangerous to clear the transport and update the + // state, since there may be a new transport in this addrConn. return } ac.transport = nil - // Refresh the name resolver on any connection loss. + // Refresh the name resolver ac.cc.resolveNow(resolver.ResolveNowOptions{}) - // Always go idle and wait for the LB policy to initiate a new - // connection attempt. - ac.updateConnectivityState(connectivity.Idle, nil) + if ac.state != connectivity.Shutdown { + ac.updateConnectivityState(connectivity.Idle, nil) + } + } + + onGoAway := func(r transport.GoAwayReason) { + ac.mu.Lock() + ac.adjustParams(r) + ac.mu.Unlock() + onClose() } connectCtx, cancel := context.WithDeadline(ac.ctx, connectDeadline) defer cancel() copts.ChannelzParentID = ac.channelzID - newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, addr, copts, onClose) + newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, addr, copts, func() { prefaceReceived.Fire() }, onGoAway, onClose) if err != nil { - if logger.V(2) { - logger.Infof("Creating new client transport to %q: %v", addr, err) - } // newTr is either nil, or closed. hcancel() channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %s. Err: %v", addr, err) return err } - ac.mu.Lock() - defer ac.mu.Unlock() - if ac.state == connectivity.Shutdown { - // This can happen if the subConn was removed while in `Connecting` - // state. tearDown() would have set the state to `Shutdown`, but - // would not have closed the transport since ac.transport would not - // have been set at that point. - // - // We run this in a goroutine because newTr.Close() calls onClose() - // inline, which requires locking ac.mu. - // + select { + case <-connectCtx.Done(): + // We didn't get the preface in time. // The error we pass to Close() is immaterial since there are no open // streams at this point, so no trailers with error details will be sent // out. We just need to pass a non-nil error. - go newTr.Close(transport.ErrConnClosing) + newTr.Close(transport.ErrConnClosing) + if connectCtx.Err() == context.DeadlineExceeded { + err := errors.New("failed to receive server preface within timeout") + channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %s: %v", addr, err) + return err + } return nil - } - if hctx.Err() != nil { - // onClose was already called for this connection, but the connection - // was successfully established first. Consider it a success and set - // the new state to Idle. - ac.updateConnectivityState(connectivity.Idle, nil) + case <-prefaceReceived.Done(): + // We got the preface - huzzah! things are good. + ac.mu.Lock() + defer ac.mu.Unlock() + if connClosed.HasFired() { + // onClose called first; go idle but do nothing else. + if ac.state != connectivity.Shutdown { + ac.updateConnectivityState(connectivity.Idle, nil) + } + return nil + } + if ac.state == connectivity.Shutdown { + // This can happen if the subConn was removed while in `Connecting` + // state. tearDown() would have set the state to `Shutdown`, but + // would not have closed the transport since ac.transport would not + // been set at that point. + // + // We run this in a goroutine because newTr.Close() calls onClose() + // inline, which requires locking ac.mu. + // + // The error we pass to Close() is immaterial since there are no open + // streams at this point, so no trailers with error details will be sent + // out. We just need to pass a non-nil error. + go newTr.Close(transport.ErrConnClosing) + return nil + } + ac.curAddr = addr + ac.transport = newTr + hcStarted = true + ac.startHealthCheck(hctx) // Will set state to READY if appropriate. return nil + case <-connClosed.Done(): + // The transport has already closed. If we received the preface, too, + // this is not an error. + select { + case <-prefaceReceived.Done(): + return nil + default: + return errors.New("connection closed before server preface received") + } } - ac.curAddr = addr - ac.transport = newTr - ac.startHealthCheck(hctx) // Will set state to READY if appropriate. - return nil } // startHealthCheck starts the health checking stream (RPC) to watch the health @@ -1376,7 +1402,7 @@ func (ac *addrConn) startHealthCheck(ctx context.Context) { if status.Code(err) == codes.Unimplemented { channelz.Error(logger, ac.channelzID, "Subchannel health check is unimplemented at server side, thus health check is disabled") } else { - channelz.Errorf(logger, ac.channelzID, "Health checking failed: %v", err) + channelz.Errorf(logger, ac.channelzID, "HealthCheckFunc exits with unexpected error %v", err) } } }() @@ -1557,7 +1583,7 @@ func (cc *ClientConn) parseTargetAndFindResolver() (resolver.Builder, error) { channelz.Infof(logger, cc.channelzID, "dial target %q parse failed: %v", cc.target, err) } else { channelz.Infof(logger, cc.channelzID, "parsed dial target is: %+v", parsedTarget) - rb = cc.getResolver(parsedTarget.URL.Scheme) + rb = cc.getResolver(parsedTarget.Scheme) if rb != nil { cc.parsedTarget = parsedTarget return rb, nil @@ -1578,26 +1604,39 @@ func (cc *ClientConn) parseTargetAndFindResolver() (resolver.Builder, error) { return nil, err } channelz.Infof(logger, cc.channelzID, "parsed dial target is: %+v", parsedTarget) - rb = cc.getResolver(parsedTarget.URL.Scheme) + rb = cc.getResolver(parsedTarget.Scheme) if rb == nil { - return nil, fmt.Errorf("could not get resolver for default scheme: %q", parsedTarget.URL.Scheme) + return nil, fmt.Errorf("could not get resolver for default scheme: %q", parsedTarget.Scheme) } cc.parsedTarget = parsedTarget return rb, nil } // parseTarget uses RFC 3986 semantics to parse the given target into a -// resolver.Target struct containing scheme, authority and url. Query +// resolver.Target struct containing scheme, authority and endpoint. Query // params are stripped from the endpoint. func parseTarget(target string) (resolver.Target, error) { u, err := url.Parse(target) if err != nil { return resolver.Target{}, err } - + // For targets of the form "[scheme]://[authority]/endpoint, the endpoint + // value returned from url.Parse() contains a leading "/". Although this is + // in accordance with RFC 3986, we do not want to break existing resolver + // implementations which expect the endpoint without the leading "/". So, we + // end up stripping the leading "/" here. But this will result in an + // incorrect parsing for something like "unix:///path/to/socket". Since we + // own the "unix" resolver, we can workaround in the unix resolver by using + // the `URL` field instead of the `Endpoint` field. + endpoint := u.Path + if endpoint == "" { + endpoint = u.Opaque + } + endpoint = strings.TrimPrefix(endpoint, "/") return resolver.Target{ Scheme: u.Scheme, Authority: u.Host, + Endpoint: endpoint, URL: *u, }, nil } diff --git a/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/altscontext.pb.go b/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/altscontext.pb.go index 1a40e17e8d3f3..703b48da753b1 100644 --- a/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/altscontext.pb.go +++ b/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/altscontext.pb.go @@ -17,13 +17,14 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 +// protoc-gen-go v1.25.0 // protoc v3.14.0 // source: grpc/gcp/altscontext.proto package grpc_gcp import ( + proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -37,6 +38,10 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + type AltsContext struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache diff --git a/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/handshaker.pb.go b/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/handshaker.pb.go index 50eefa53830ed..40570e9bf2de4 100644 --- a/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/handshaker.pb.go +++ b/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/handshaker.pb.go @@ -17,13 +17,14 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 +// protoc-gen-go v1.25.0 // protoc v3.14.0 // source: grpc/gcp/handshaker.proto package grpc_gcp import ( + proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -37,6 +38,10 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + type HandshakeProtocol int32 const ( @@ -211,7 +216,6 @@ type Identity struct { unknownFields protoimpl.UnknownFields // Types that are assignable to IdentityOneof: - // // *Identity_ServiceAccount // *Identity_Hostname IdentityOneof isIdentity_IdentityOneof `protobuf_oneof:"identity_oneof"` @@ -660,7 +664,6 @@ type HandshakerReq struct { unknownFields protoimpl.UnknownFields // Types that are assignable to ReqOneof: - // // *HandshakerReq_ClientStart // *HandshakerReq_ServerStart // *HandshakerReq_Next diff --git a/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/transport_security_common.pb.go b/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/transport_security_common.pb.go index b07412f18585f..4fc3c79d6a399 100644 --- a/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/transport_security_common.pb.go +++ b/vendor/google.golang.org/grpc/credentials/alts/internal/proto/grpc_gcp/transport_security_common.pb.go @@ -17,13 +17,14 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 +// protoc-gen-go v1.25.0 // protoc v3.14.0 // source: grpc/gcp/transport_security_common.proto package grpc_gcp import ( + proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -37,6 +38,10 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + // The security level of the created channel. The list is sorted in increasing // level of security. This order must always be maintained. type SecurityLevel int32 diff --git a/vendor/google.golang.org/grpc/credentials/credentials.go b/vendor/google.golang.org/grpc/credentials/credentials.go index 5feac3aa0e415..96ff1877e7549 100644 --- a/vendor/google.golang.org/grpc/credentials/credentials.go +++ b/vendor/google.golang.org/grpc/credentials/credentials.go @@ -36,16 +36,16 @@ import ( // PerRPCCredentials defines the common interface for the credentials which need to // attach security information to every RPC (e.g., oauth2). type PerRPCCredentials interface { - // GetRequestMetadata gets the current request metadata, refreshing tokens - // if required. This should be called by the transport layer on each - // request, and the data should be populated in headers or other - // context. If a status code is returned, it will be used as the status for - // the RPC (restricted to an allowable set of codes as defined by gRFC - // A54). uri is the URI of the entry point for the request. When supported - // by the underlying implementation, ctx can be used for timeout and - // cancellation. Additionally, RequestInfo data will be available via ctx - // to this call. TODO(zhaoq): Define the set of the qualified keys instead - // of leaving it as an arbitrary string. + // GetRequestMetadata gets the current request metadata, refreshing + // tokens if required. This should be called by the transport layer on + // each request, and the data should be populated in headers or other + // context. If a status code is returned, it will be used as the status + // for the RPC. uri is the URI of the entry point for the request. + // When supported by the underlying implementation, ctx can be used for + // timeout and cancellation. Additionally, RequestInfo data will be + // available via ctx to this call. + // TODO(zhaoq): Define the set of the qualified keys instead of leaving + // it as an arbitrary string. GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) // RequireTransportSecurity indicates whether the credentials requires // transport security. diff --git a/vendor/google.golang.org/grpc/credentials/google/xds.go b/vendor/google.golang.org/grpc/credentials/google/xds.go index 2c5c8b9eee136..e32edc0421c3e 100644 --- a/vendor/google.golang.org/grpc/credentials/google/xds.go +++ b/vendor/google.golang.org/grpc/credentials/google/xds.go @@ -40,7 +40,6 @@ const cfeClusterAuthorityName = "traffic-director-c2p.xds.googleapis.com" // "xdstp://traffic-director-c2p.xds.googleapis.com/envoy.config.cluster.v3.Cluster/google_cfe_", // use TLS // - otherwise, use ALTS -// // - else, do TLS // // On the server, ServerHandshake always does TLS. diff --git a/vendor/google.golang.org/grpc/credentials/oauth/oauth.go b/vendor/google.golang.org/grpc/credentials/oauth/oauth.go index d475cbc0894c0..c748fd21ce2b8 100644 --- a/vendor/google.golang.org/grpc/credentials/oauth/oauth.go +++ b/vendor/google.golang.org/grpc/credentials/oauth/oauth.go @@ -22,8 +22,8 @@ package oauth import ( "context" "fmt" + "io/ioutil" "net/url" - "os" "sync" "golang.org/x/oauth2" @@ -73,7 +73,7 @@ type jwtAccess struct { // NewJWTAccessFromFile creates PerRPCCredentials from the given keyFile. func NewJWTAccessFromFile(keyFile string) (credentials.PerRPCCredentials, error) { - jsonKey, err := os.ReadFile(keyFile) + jsonKey, err := ioutil.ReadFile(keyFile) if err != nil { return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err) } @@ -121,8 +121,6 @@ type oauthAccess struct { } // NewOauthAccess constructs the PerRPCCredentials using a given token. -// -// Deprecated: use oauth.TokenSource instead. func NewOauthAccess(token *oauth2.Token) credentials.PerRPCCredentials { return oauthAccess{token: *token} } @@ -192,7 +190,7 @@ func NewServiceAccountFromKey(jsonKey []byte, scope ...string) (credentials.PerR // NewServiceAccountFromFile constructs the PerRPCCredentials using the JSON key file // of a Google Developers service account. func NewServiceAccountFromFile(keyFile string, scope ...string) (credentials.PerRPCCredentials, error) { - jsonKey, err := os.ReadFile(keyFile) + jsonKey, err := ioutil.ReadFile(keyFile) if err != nil { return nil, fmt.Errorf("credentials: failed to read the service account key file: %v", err) } diff --git a/vendor/google.golang.org/grpc/credentials/tls.go b/vendor/google.golang.org/grpc/credentials/tls.go index 877b7cd21af72..784822d0560ad 100644 --- a/vendor/google.golang.org/grpc/credentials/tls.go +++ b/vendor/google.golang.org/grpc/credentials/tls.go @@ -23,9 +23,9 @@ import ( "crypto/tls" "crypto/x509" "fmt" + "io/ioutil" "net" "net/url" - "os" credinternal "google.golang.org/grpc/internal/credentials" ) @@ -166,7 +166,7 @@ func NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) Transpor // it will override the virtual host name of authority (e.g. :authority header // field) in requests. func NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) { - b, err := os.ReadFile(certFile) + b, err := ioutil.ReadFile(certFile) if err != nil { return nil, err } @@ -195,7 +195,7 @@ func NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error // TLSChannelzSecurityValue defines the struct that TLS protocol should return // from GetSecurityValue(), containing security info like cipher and certificate used. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. diff --git a/vendor/google.golang.org/grpc/dialoptions.go b/vendor/google.golang.org/grpc/dialoptions.go index 4866da101c607..9372dc322e803 100644 --- a/vendor/google.golang.org/grpc/dialoptions.go +++ b/vendor/google.golang.org/grpc/dialoptions.go @@ -44,7 +44,6 @@ func init() { extraDialOptions = nil } internal.WithBinaryLogger = withBinaryLogger - internal.JoinDialOptions = newJoinDialOption } // dialOptions configure a Dial call. dialOptions are set by the DialOption @@ -112,28 +111,13 @@ func newFuncDialOption(f func(*dialOptions)) *funcDialOption { } } -type joinDialOption struct { - opts []DialOption -} - -func (jdo *joinDialOption) apply(do *dialOptions) { - for _, opt := range jdo.opts { - opt.apply(do) - } -} - -func newJoinDialOption(opts ...DialOption) DialOption { - return &joinDialOption{opts: opts} -} - // WithWriteBufferSize determines how much data can be batched before doing a // write on the wire. The corresponding memory allocation for this buffer will // be twice the size to keep syscalls low. The default value for this buffer is // 32KB. // -// Zero or negative values will disable the write buffer such that each write -// will be on underlying connection. Note: A Send call may not directly -// translate to a write. +// Zero will disable the write buffer such that each write will be on underlying +// connection. Note: A Send call may not directly translate to a write. func WithWriteBufferSize(s int) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.WriteBufferSize = s @@ -143,9 +127,8 @@ func WithWriteBufferSize(s int) DialOption { // WithReadBufferSize lets you set the size of read buffer, this determines how // much data can be read at most for each read syscall. // -// The default value for this buffer is 32KB. Zero or negative values will -// disable read buffer for a connection so data framer can access the -// underlying conn directly. +// The default value for this buffer is 32KB. Zero will disable read buffer for +// a connection so data framer can access the underlying conn directly. func WithReadBufferSize(s int) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.ReadBufferSize = s diff --git a/vendor/google.golang.org/grpc/encoding/encoding.go b/vendor/google.golang.org/grpc/encoding/encoding.go index 07a5861352a6f..18e530fc90242 100644 --- a/vendor/google.golang.org/grpc/encoding/encoding.go +++ b/vendor/google.golang.org/grpc/encoding/encoding.go @@ -19,7 +19,7 @@ // Package encoding defines the interface for the compressor and codec, and // functions to register and retrieve compressors and codecs. // -// # Experimental +// Experimental // // Notice: This package is EXPERIMENTAL and may be changed or removed in a // later release. @@ -28,8 +28,6 @@ package encoding import ( "io" "strings" - - "google.golang.org/grpc/internal/grpcutil" ) // Identity specifies the optional encoding for uncompressed streams. @@ -75,9 +73,6 @@ var registeredCompressor = make(map[string]Compressor) // registered with the same name, the one registered last will take effect. func RegisterCompressor(c Compressor) { registeredCompressor[c.Name()] = c - if !grpcutil.IsCompressorNameRegistered(c.Name()) { - grpcutil.RegisteredCompressorNames = append(grpcutil.RegisteredCompressorNames, c.Name()) - } } // GetCompressor returns Compressor for the given compressor name. diff --git a/vendor/google.golang.org/grpc/encoding/gzip/gzip.go b/vendor/google.golang.org/grpc/encoding/gzip/gzip.go index a3bb173c24ac7..ce2f15ed288f8 100644 --- a/vendor/google.golang.org/grpc/encoding/gzip/gzip.go +++ b/vendor/google.golang.org/grpc/encoding/gzip/gzip.go @@ -19,7 +19,7 @@ // Package gzip implements and registers the gzip compressor // during the initialization. // -// # Experimental +// Experimental // // Notice: This package is EXPERIMENTAL and may be changed or removed in a // later release. @@ -30,6 +30,7 @@ import ( "encoding/binary" "fmt" "io" + "io/ioutil" "sync" "google.golang.org/grpc/encoding" @@ -41,7 +42,7 @@ const Name = "gzip" func init() { c := &compressor{} c.poolCompressor.New = func() interface{} { - return &writer{Writer: gzip.NewWriter(io.Discard), pool: &c.poolCompressor} + return &writer{Writer: gzip.NewWriter(ioutil.Discard), pool: &c.poolCompressor} } encoding.RegisterCompressor(c) } @@ -62,7 +63,7 @@ func SetLevel(level int) error { } c := encoding.GetCompressor(Name).(*compressor) c.poolCompressor.New = func() interface{} { - w, err := gzip.NewWriterLevel(io.Discard, level) + w, err := gzip.NewWriterLevel(ioutil.Discard, level) if err != nil { panic(err) } diff --git a/vendor/google.golang.org/grpc/grpclog/loggerv2.go b/vendor/google.golang.org/grpc/grpclog/loggerv2.go index 5de66e40d365b..7c1f664090344 100644 --- a/vendor/google.golang.org/grpc/grpclog/loggerv2.go +++ b/vendor/google.golang.org/grpc/grpclog/loggerv2.go @@ -22,6 +22,7 @@ import ( "encoding/json" "fmt" "io" + "io/ioutil" "log" "os" "strconv" @@ -139,9 +140,9 @@ func newLoggerV2WithConfig(infoW, warningW, errorW io.Writer, c loggerV2Config) // newLoggerV2 creates a loggerV2 to be used as default logger. // All logs are written to stderr. func newLoggerV2() LoggerV2 { - errorW := io.Discard - warningW := io.Discard - infoW := io.Discard + errorW := ioutil.Discard + warningW := ioutil.Discard + infoW := ioutil.Discard logLevel := os.Getenv("GRPC_GO_LOG_SEVERITY_LEVEL") switch logLevel { @@ -241,7 +242,7 @@ func (g *loggerT) V(l int) bool { // DepthLoggerV2, the below functions will be called with the appropriate stack // depth set for trivial functions the logger may ignore. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. diff --git a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go index 8e29a62f164f5..a66024d23e301 100644 --- a/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go +++ b/vendor/google.golang.org/grpc/health/grpc_health_v1/health.pb.go @@ -17,13 +17,14 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.28.1 +// protoc-gen-go v1.25.0 // protoc v3.14.0 // source: grpc/health/v1/health.proto package grpc_health_v1 import ( + proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" @@ -37,6 +38,10 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +// This is a compile-time assertion that a sufficiently up-to-date version +// of the legacy proto package is being used. +const _ = proto.ProtoPackageIsVersion4 + type HealthCheckResponse_ServingStatus int32 const ( diff --git a/vendor/google.golang.org/grpc/internal/binarylog/env_config.go b/vendor/google.golang.org/grpc/internal/binarylog/env_config.go index f9e80e27ab688..c5579e65065f6 100644 --- a/vendor/google.golang.org/grpc/internal/binarylog/env_config.go +++ b/vendor/google.golang.org/grpc/internal/binarylog/env_config.go @@ -30,15 +30,15 @@ import ( // to build a new logger and assign it to binarylog.Logger. // // Example filter config strings: -// - "" Nothing will be logged -// - "*" All headers and messages will be fully logged. -// - "*{h}" Only headers will be logged. -// - "*{m:256}" Only the first 256 bytes of each message will be logged. -// - "Foo/*" Logs every method in service Foo -// - "Foo/*,-Foo/Bar" Logs every method in service Foo except method /Foo/Bar -// - "Foo/*,Foo/Bar{m:256}" Logs the first 256 bytes of each message in method -// /Foo/Bar, logs all headers and messages in every other method in service -// Foo. +// - "" Nothing will be logged +// - "*" All headers and messages will be fully logged. +// - "*{h}" Only headers will be logged. +// - "*{m:256}" Only the first 256 bytes of each message will be logged. +// - "Foo/*" Logs every method in service Foo +// - "Foo/*,-Foo/Bar" Logs every method in service Foo except method /Foo/Bar +// - "Foo/*,Foo/Bar{m:256}" Logs the first 256 bytes of each message in method +// /Foo/Bar, logs all headers and messages in every other method in service +// Foo. // // If two configs exist for one certain method or service, the one specified // later overrides the previous config. diff --git a/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go b/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go index d71e441778f4e..179f4a26d135b 100644 --- a/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go +++ b/vendor/google.golang.org/grpc/internal/binarylog/method_logger.go @@ -26,7 +26,7 @@ import ( "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes" - binlogpb "google.golang.org/grpc/binarylog/grpc_binarylog_v1" + pb "google.golang.org/grpc/binarylog/grpc_binarylog_v1" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) @@ -79,7 +79,7 @@ func NewTruncatingMethodLogger(h, m uint64) *TruncatingMethodLogger { // Build is an internal only method for building the proto message out of the // input event. It's made public to enable other library to reuse as much logic // in TruncatingMethodLogger as possible. -func (ml *TruncatingMethodLogger) Build(c LogEntryConfig) *binlogpb.GrpcLogEntry { +func (ml *TruncatingMethodLogger) Build(c LogEntryConfig) *pb.GrpcLogEntry { m := c.toProto() timestamp, _ := ptypes.TimestampProto(time.Now()) m.Timestamp = timestamp @@ -87,11 +87,11 @@ func (ml *TruncatingMethodLogger) Build(c LogEntryConfig) *binlogpb.GrpcLogEntry m.SequenceIdWithinCall = ml.idWithinCallGen.next() switch pay := m.Payload.(type) { - case *binlogpb.GrpcLogEntry_ClientHeader: + case *pb.GrpcLogEntry_ClientHeader: m.PayloadTruncated = ml.truncateMetadata(pay.ClientHeader.GetMetadata()) - case *binlogpb.GrpcLogEntry_ServerHeader: + case *pb.GrpcLogEntry_ServerHeader: m.PayloadTruncated = ml.truncateMetadata(pay.ServerHeader.GetMetadata()) - case *binlogpb.GrpcLogEntry_Message: + case *pb.GrpcLogEntry_Message: m.PayloadTruncated = ml.truncateMessage(pay.Message) } return m @@ -102,7 +102,7 @@ func (ml *TruncatingMethodLogger) Log(c LogEntryConfig) { ml.sink.Write(ml.Build(c)) } -func (ml *TruncatingMethodLogger) truncateMetadata(mdPb *binlogpb.Metadata) (truncated bool) { +func (ml *TruncatingMethodLogger) truncateMetadata(mdPb *pb.Metadata) (truncated bool) { if ml.headerMaxLen == maxUInt { return false } @@ -121,7 +121,7 @@ func (ml *TruncatingMethodLogger) truncateMetadata(mdPb *binlogpb.Metadata) (tru // but not counted towards the size limit. continue } - currentEntryLen := uint64(len(entry.GetKey())) + uint64(len(entry.GetValue())) + currentEntryLen := uint64(len(entry.Value)) if currentEntryLen > bytesLimit { break } @@ -132,7 +132,7 @@ func (ml *TruncatingMethodLogger) truncateMetadata(mdPb *binlogpb.Metadata) (tru return truncated } -func (ml *TruncatingMethodLogger) truncateMessage(msgPb *binlogpb.Message) (truncated bool) { +func (ml *TruncatingMethodLogger) truncateMessage(msgPb *pb.Message) (truncated bool) { if ml.messageMaxLen == maxUInt { return false } @@ -145,7 +145,7 @@ func (ml *TruncatingMethodLogger) truncateMessage(msgPb *binlogpb.Message) (trun // LogEntryConfig represents the configuration for binary log entry. type LogEntryConfig interface { - toProto() *binlogpb.GrpcLogEntry + toProto() *pb.GrpcLogEntry } // ClientHeader configs the binary log entry to be a ClientHeader entry. @@ -159,10 +159,10 @@ type ClientHeader struct { PeerAddr net.Addr } -func (c *ClientHeader) toProto() *binlogpb.GrpcLogEntry { +func (c *ClientHeader) toProto() *pb.GrpcLogEntry { // This function doesn't need to set all the fields (e.g. seq ID). The Log // function will set the fields when necessary. - clientHeader := &binlogpb.ClientHeader{ + clientHeader := &pb.ClientHeader{ Metadata: mdToMetadataProto(c.Header), MethodName: c.MethodName, Authority: c.Authority, @@ -170,16 +170,16 @@ func (c *ClientHeader) toProto() *binlogpb.GrpcLogEntry { if c.Timeout > 0 { clientHeader.Timeout = ptypes.DurationProto(c.Timeout) } - ret := &binlogpb.GrpcLogEntry{ - Type: binlogpb.GrpcLogEntry_EVENT_TYPE_CLIENT_HEADER, - Payload: &binlogpb.GrpcLogEntry_ClientHeader{ + ret := &pb.GrpcLogEntry{ + Type: pb.GrpcLogEntry_EVENT_TYPE_CLIENT_HEADER, + Payload: &pb.GrpcLogEntry_ClientHeader{ ClientHeader: clientHeader, }, } if c.OnClientSide { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT + ret.Logger = pb.GrpcLogEntry_LOGGER_CLIENT } else { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER + ret.Logger = pb.GrpcLogEntry_LOGGER_SERVER } if c.PeerAddr != nil { ret.Peer = addrToProto(c.PeerAddr) @@ -195,19 +195,19 @@ type ServerHeader struct { PeerAddr net.Addr } -func (c *ServerHeader) toProto() *binlogpb.GrpcLogEntry { - ret := &binlogpb.GrpcLogEntry{ - Type: binlogpb.GrpcLogEntry_EVENT_TYPE_SERVER_HEADER, - Payload: &binlogpb.GrpcLogEntry_ServerHeader{ - ServerHeader: &binlogpb.ServerHeader{ +func (c *ServerHeader) toProto() *pb.GrpcLogEntry { + ret := &pb.GrpcLogEntry{ + Type: pb.GrpcLogEntry_EVENT_TYPE_SERVER_HEADER, + Payload: &pb.GrpcLogEntry_ServerHeader{ + ServerHeader: &pb.ServerHeader{ Metadata: mdToMetadataProto(c.Header), }, }, } if c.OnClientSide { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT + ret.Logger = pb.GrpcLogEntry_LOGGER_CLIENT } else { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER + ret.Logger = pb.GrpcLogEntry_LOGGER_SERVER } if c.PeerAddr != nil { ret.Peer = addrToProto(c.PeerAddr) @@ -223,7 +223,7 @@ type ClientMessage struct { Message interface{} } -func (c *ClientMessage) toProto() *binlogpb.GrpcLogEntry { +func (c *ClientMessage) toProto() *pb.GrpcLogEntry { var ( data []byte err error @@ -238,19 +238,19 @@ func (c *ClientMessage) toProto() *binlogpb.GrpcLogEntry { } else { grpclogLogger.Infof("binarylogging: message to log is neither proto.message nor []byte") } - ret := &binlogpb.GrpcLogEntry{ - Type: binlogpb.GrpcLogEntry_EVENT_TYPE_CLIENT_MESSAGE, - Payload: &binlogpb.GrpcLogEntry_Message{ - Message: &binlogpb.Message{ + ret := &pb.GrpcLogEntry{ + Type: pb.GrpcLogEntry_EVENT_TYPE_CLIENT_MESSAGE, + Payload: &pb.GrpcLogEntry_Message{ + Message: &pb.Message{ Length: uint32(len(data)), Data: data, }, }, } if c.OnClientSide { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT + ret.Logger = pb.GrpcLogEntry_LOGGER_CLIENT } else { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER + ret.Logger = pb.GrpcLogEntry_LOGGER_SERVER } return ret } @@ -263,7 +263,7 @@ type ServerMessage struct { Message interface{} } -func (c *ServerMessage) toProto() *binlogpb.GrpcLogEntry { +func (c *ServerMessage) toProto() *pb.GrpcLogEntry { var ( data []byte err error @@ -278,19 +278,19 @@ func (c *ServerMessage) toProto() *binlogpb.GrpcLogEntry { } else { grpclogLogger.Infof("binarylogging: message to log is neither proto.message nor []byte") } - ret := &binlogpb.GrpcLogEntry{ - Type: binlogpb.GrpcLogEntry_EVENT_TYPE_SERVER_MESSAGE, - Payload: &binlogpb.GrpcLogEntry_Message{ - Message: &binlogpb.Message{ + ret := &pb.GrpcLogEntry{ + Type: pb.GrpcLogEntry_EVENT_TYPE_SERVER_MESSAGE, + Payload: &pb.GrpcLogEntry_Message{ + Message: &pb.Message{ Length: uint32(len(data)), Data: data, }, }, } if c.OnClientSide { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT + ret.Logger = pb.GrpcLogEntry_LOGGER_CLIENT } else { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER + ret.Logger = pb.GrpcLogEntry_LOGGER_SERVER } return ret } @@ -300,15 +300,15 @@ type ClientHalfClose struct { OnClientSide bool } -func (c *ClientHalfClose) toProto() *binlogpb.GrpcLogEntry { - ret := &binlogpb.GrpcLogEntry{ - Type: binlogpb.GrpcLogEntry_EVENT_TYPE_CLIENT_HALF_CLOSE, +func (c *ClientHalfClose) toProto() *pb.GrpcLogEntry { + ret := &pb.GrpcLogEntry{ + Type: pb.GrpcLogEntry_EVENT_TYPE_CLIENT_HALF_CLOSE, Payload: nil, // No payload here. } if c.OnClientSide { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT + ret.Logger = pb.GrpcLogEntry_LOGGER_CLIENT } else { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER + ret.Logger = pb.GrpcLogEntry_LOGGER_SERVER } return ret } @@ -324,7 +324,7 @@ type ServerTrailer struct { PeerAddr net.Addr } -func (c *ServerTrailer) toProto() *binlogpb.GrpcLogEntry { +func (c *ServerTrailer) toProto() *pb.GrpcLogEntry { st, ok := status.FromError(c.Err) if !ok { grpclogLogger.Info("binarylogging: error in trailer is not a status error") @@ -340,10 +340,10 @@ func (c *ServerTrailer) toProto() *binlogpb.GrpcLogEntry { grpclogLogger.Infof("binarylogging: failed to marshal status proto: %v", err) } } - ret := &binlogpb.GrpcLogEntry{ - Type: binlogpb.GrpcLogEntry_EVENT_TYPE_SERVER_TRAILER, - Payload: &binlogpb.GrpcLogEntry_Trailer{ - Trailer: &binlogpb.Trailer{ + ret := &pb.GrpcLogEntry{ + Type: pb.GrpcLogEntry_EVENT_TYPE_SERVER_TRAILER, + Payload: &pb.GrpcLogEntry_Trailer{ + Trailer: &pb.Trailer{ Metadata: mdToMetadataProto(c.Trailer), StatusCode: uint32(st.Code()), StatusMessage: st.Message(), @@ -352,9 +352,9 @@ func (c *ServerTrailer) toProto() *binlogpb.GrpcLogEntry { }, } if c.OnClientSide { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT + ret.Logger = pb.GrpcLogEntry_LOGGER_CLIENT } else { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER + ret.Logger = pb.GrpcLogEntry_LOGGER_SERVER } if c.PeerAddr != nil { ret.Peer = addrToProto(c.PeerAddr) @@ -367,15 +367,15 @@ type Cancel struct { OnClientSide bool } -func (c *Cancel) toProto() *binlogpb.GrpcLogEntry { - ret := &binlogpb.GrpcLogEntry{ - Type: binlogpb.GrpcLogEntry_EVENT_TYPE_CANCEL, +func (c *Cancel) toProto() *pb.GrpcLogEntry { + ret := &pb.GrpcLogEntry{ + Type: pb.GrpcLogEntry_EVENT_TYPE_CANCEL, Payload: nil, } if c.OnClientSide { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_CLIENT + ret.Logger = pb.GrpcLogEntry_LOGGER_CLIENT } else { - ret.Logger = binlogpb.GrpcLogEntry_LOGGER_SERVER + ret.Logger = pb.GrpcLogEntry_LOGGER_SERVER } return ret } @@ -392,15 +392,15 @@ func metadataKeyOmit(key string) bool { return strings.HasPrefix(key, "grpc-") } -func mdToMetadataProto(md metadata.MD) *binlogpb.Metadata { - ret := &binlogpb.Metadata{} +func mdToMetadataProto(md metadata.MD) *pb.Metadata { + ret := &pb.Metadata{} for k, vv := range md { if metadataKeyOmit(k) { continue } for _, v := range vv { ret.Entry = append(ret.Entry, - &binlogpb.MetadataEntry{ + &pb.MetadataEntry{ Key: k, Value: []byte(v), }, @@ -410,26 +410,26 @@ func mdToMetadataProto(md metadata.MD) *binlogpb.Metadata { return ret } -func addrToProto(addr net.Addr) *binlogpb.Address { - ret := &binlogpb.Address{} +func addrToProto(addr net.Addr) *pb.Address { + ret := &pb.Address{} switch a := addr.(type) { case *net.TCPAddr: if a.IP.To4() != nil { - ret.Type = binlogpb.Address_TYPE_IPV4 + ret.Type = pb.Address_TYPE_IPV4 } else if a.IP.To16() != nil { - ret.Type = binlogpb.Address_TYPE_IPV6 + ret.Type = pb.Address_TYPE_IPV6 } else { - ret.Type = binlogpb.Address_TYPE_UNKNOWN + ret.Type = pb.Address_TYPE_UNKNOWN // Do not set address and port fields. break } ret.Address = a.IP.String() ret.IpPort = uint32(a.Port) case *net.UnixAddr: - ret.Type = binlogpb.Address_TYPE_UNIX + ret.Type = pb.Address_TYPE_UNIX ret.Address = a.String() default: - ret.Type = binlogpb.Address_TYPE_UNKNOWN + ret.Type = pb.Address_TYPE_UNKNOWN } return ret } diff --git a/vendor/google.golang.org/grpc/internal/binarylog/sink.go b/vendor/google.golang.org/grpc/internal/binarylog/sink.go index 264de387c2a5e..c2fdd58b31982 100644 --- a/vendor/google.golang.org/grpc/internal/binarylog/sink.go +++ b/vendor/google.golang.org/grpc/internal/binarylog/sink.go @@ -26,7 +26,7 @@ import ( "time" "github.com/golang/protobuf/proto" - binlogpb "google.golang.org/grpc/binarylog/grpc_binarylog_v1" + pb "google.golang.org/grpc/binarylog/grpc_binarylog_v1" ) var ( @@ -42,15 +42,15 @@ type Sink interface { // Write will be called to write the log entry into the sink. // // It should be thread-safe so it can be called in parallel. - Write(*binlogpb.GrpcLogEntry) error + Write(*pb.GrpcLogEntry) error // Close will be called when the Sink is replaced by a new Sink. Close() error } type noopSink struct{} -func (ns *noopSink) Write(*binlogpb.GrpcLogEntry) error { return nil } -func (ns *noopSink) Close() error { return nil } +func (ns *noopSink) Write(*pb.GrpcLogEntry) error { return nil } +func (ns *noopSink) Close() error { return nil } // newWriterSink creates a binary log sink with the given writer. // @@ -66,7 +66,7 @@ type writerSink struct { out io.Writer } -func (ws *writerSink) Write(e *binlogpb.GrpcLogEntry) error { +func (ws *writerSink) Write(e *pb.GrpcLogEntry) error { b, err := proto.Marshal(e) if err != nil { grpclogLogger.Errorf("binary logging: failed to marshal proto message: %v", err) @@ -96,7 +96,7 @@ type bufferedSink struct { done chan struct{} } -func (fs *bufferedSink) Write(e *binlogpb.GrpcLogEntry) error { +func (fs *bufferedSink) Write(e *pb.GrpcLogEntry) error { fs.mu.Lock() defer fs.mu.Unlock() if !fs.flusherStarted { diff --git a/vendor/google.golang.org/grpc/internal/channelz/types.go b/vendor/google.golang.org/grpc/internal/channelz/types.go index 7b2f350e2e645..ad0ce4dabf06c 100644 --- a/vendor/google.golang.org/grpc/internal/channelz/types.go +++ b/vendor/google.golang.org/grpc/internal/channelz/types.go @@ -273,10 +273,10 @@ func (c *channel) deleteSelfFromMap() (delete bool) { // deleteSelfIfReady tries to delete the channel itself from the channelz database. // The delete process includes two steps: -// 1. delete the channel from the entry relation tree, i.e. delete the channel reference from its -// parent's child list. -// 2. delete the channel from the map, i.e. delete the channel entirely from channelz. Lookup by id -// will return entry not found error. +// 1. delete the channel from the entry relation tree, i.e. delete the channel reference from its +// parent's child list. +// 2. delete the channel from the map, i.e. delete the channel entirely from channelz. Lookup by id +// will return entry not found error. func (c *channel) deleteSelfIfReady() { if !c.deleteSelfFromTree() { return @@ -381,10 +381,10 @@ func (sc *subChannel) deleteSelfFromMap() (delete bool) { // deleteSelfIfReady tries to delete the subchannel itself from the channelz database. // The delete process includes two steps: -// 1. delete the subchannel from the entry relation tree, i.e. delete the subchannel reference from -// its parent's child list. -// 2. delete the subchannel from the map, i.e. delete the subchannel entirely from channelz. Lookup -// by id will return entry not found error. +// 1. delete the subchannel from the entry relation tree, i.e. delete the subchannel reference from +// its parent's child list. +// 2. delete the subchannel from the map, i.e. delete the subchannel entirely from channelz. Lookup +// by id will return entry not found error. func (sc *subChannel) deleteSelfIfReady() { if !sc.deleteSelfFromTree() { return diff --git a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go index 5ba9d94d49c2e..6f02725431109 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/envconfig.go @@ -21,42 +21,15 @@ package envconfig import ( "os" - "strconv" "strings" ) +const ( + prefix = "GRPC_GO_" + txtErrIgnoreStr = prefix + "IGNORE_TXT_ERRORS" +) + var ( // TXTErrIgnore is set if TXT errors should be ignored ("GRPC_GO_IGNORE_TXT_ERRORS" is not "false"). - TXTErrIgnore = boolFromEnv("GRPC_GO_IGNORE_TXT_ERRORS", true) - // AdvertiseCompressors is set if registered compressor should be advertised - // ("GRPC_GO_ADVERTISE_COMPRESSORS" is not "false"). - AdvertiseCompressors = boolFromEnv("GRPC_GO_ADVERTISE_COMPRESSORS", true) - // RingHashCap indicates the maximum ring size which defaults to 4096 - // entries but may be overridden by setting the environment variable - // "GRPC_RING_HASH_CAP". This does not override the default bounds - // checking which NACKs configs specifying ring sizes > 8*1024*1024 (~8M). - RingHashCap = uint64FromEnv("GRPC_RING_HASH_CAP", 4096, 1, 8*1024*1024) + TXTErrIgnore = !strings.EqualFold(os.Getenv(txtErrIgnoreStr), "false") ) - -func boolFromEnv(envVar string, def bool) bool { - if def { - // The default is true; return true unless the variable is "false". - return !strings.EqualFold(os.Getenv(envVar), "false") - } - // The default is false; return false unless the variable is "true". - return strings.EqualFold(os.Getenv(envVar), "true") -} - -func uint64FromEnv(envVar string, def, min, max uint64) uint64 { - v, err := strconv.ParseUint(os.Getenv(envVar), 10, 64) - if err != nil { - return def - } - if v < min { - return min - } - if v > max { - return max - } - return v -} diff --git a/vendor/google.golang.org/grpc/internal/envconfig/xds.go b/vendor/google.golang.org/grpc/internal/envconfig/xds.go index 04136882c7bcb..af09711a3e88d 100644 --- a/vendor/google.golang.org/grpc/internal/envconfig/xds.go +++ b/vendor/google.golang.org/grpc/internal/envconfig/xds.go @@ -20,6 +20,7 @@ package envconfig import ( "os" + "strings" ) const ( @@ -35,6 +36,16 @@ const ( // // When both bootstrap FileName and FileContent are set, FileName is used. XDSBootstrapFileContentEnv = "GRPC_XDS_BOOTSTRAP_CONFIG" + + ringHashSupportEnv = "GRPC_XDS_EXPERIMENTAL_ENABLE_RING_HASH" + clientSideSecuritySupportEnv = "GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT" + aggregateAndDNSSupportEnv = "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER" + rbacSupportEnv = "GRPC_XDS_EXPERIMENTAL_RBAC" + outlierDetectionSupportEnv = "GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION" + federationEnv = "GRPC_EXPERIMENTAL_XDS_FEDERATION" + rlsInXDSEnv = "GRPC_EXPERIMENTAL_XDS_RLS_LB" + + c2pResolverTestOnlyTrafficDirectorURIEnv = "GRPC_TEST_ONLY_GOOGLE_C2P_RESOLVER_TRAFFIC_DIRECTOR_URI" ) var ( @@ -53,40 +64,38 @@ var ( // XDSRingHash indicates whether ring hash support is enabled, which can be // disabled by setting the environment variable // "GRPC_XDS_EXPERIMENTAL_ENABLE_RING_HASH" to "false". - XDSRingHash = boolFromEnv("GRPC_XDS_EXPERIMENTAL_ENABLE_RING_HASH", true) + XDSRingHash = !strings.EqualFold(os.Getenv(ringHashSupportEnv), "false") // XDSClientSideSecurity is used to control processing of security // configuration on the client-side. // // Note that there is no env var protection for the server-side because we // have a brand new API on the server-side and users explicitly need to use // the new API to get security integration on the server. - XDSClientSideSecurity = boolFromEnv("GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT", true) + XDSClientSideSecurity = !strings.EqualFold(os.Getenv(clientSideSecuritySupportEnv), "false") // XDSAggregateAndDNS indicates whether processing of aggregated cluster // and DNS cluster is enabled, which can be enabled by setting the // environment variable // "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER" to // "true". - XDSAggregateAndDNS = boolFromEnv("GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER", true) + XDSAggregateAndDNS = !strings.EqualFold(os.Getenv(aggregateAndDNSSupportEnv), "false") // XDSRBAC indicates whether xDS configured RBAC HTTP Filter is enabled, // which can be disabled by setting the environment variable // "GRPC_XDS_EXPERIMENTAL_RBAC" to "false". - XDSRBAC = boolFromEnv("GRPC_XDS_EXPERIMENTAL_RBAC", true) + XDSRBAC = !strings.EqualFold(os.Getenv(rbacSupportEnv), "false") // XDSOutlierDetection indicates whether outlier detection support is // enabled, which can be disabled by setting the environment variable // "GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION" to "false". - XDSOutlierDetection = boolFromEnv("GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION", true) - // XDSFederation indicates whether federation support is enabled, which can - // be enabled by setting the environment variable - // "GRPC_EXPERIMENTAL_XDS_FEDERATION" to "true". - XDSFederation = boolFromEnv("GRPC_EXPERIMENTAL_XDS_FEDERATION", false) + XDSOutlierDetection = !strings.EqualFold(os.Getenv(outlierDetectionSupportEnv), "false") + // XDSFederation indicates whether federation support is enabled. + XDSFederation = strings.EqualFold(os.Getenv(federationEnv), "true") // XDSRLS indicates whether processing of Cluster Specifier plugins and // support for the RLS CLuster Specifier is enabled, which can be enabled by // setting the environment variable "GRPC_EXPERIMENTAL_XDS_RLS_LB" to // "true". - XDSRLS = boolFromEnv("GRPC_EXPERIMENTAL_XDS_RLS_LB", false) + XDSRLS = strings.EqualFold(os.Getenv(rlsInXDSEnv), "true") // C2PResolverTestOnlyTrafficDirectorURI is the TD URI for testing. - C2PResolverTestOnlyTrafficDirectorURI = os.Getenv("GRPC_TEST_ONLY_GOOGLE_C2P_RESOLVER_TRAFFIC_DIRECTOR_URI") + C2PResolverTestOnlyTrafficDirectorURI = os.Getenv(c2pResolverTestOnlyTrafficDirectorURIEnv) ) diff --git a/vendor/google.golang.org/grpc/internal/googlecloud/manufacturer_linux.go b/vendor/google.golang.org/grpc/internal/googlecloud/manufacturer_linux.go index 6e455fb0a8226..e53b8ffc837f7 100644 --- a/vendor/google.golang.org/grpc/internal/googlecloud/manufacturer_linux.go +++ b/vendor/google.golang.org/grpc/internal/googlecloud/manufacturer_linux.go @@ -18,10 +18,10 @@ package googlecloud -import "os" +import "io/ioutil" const linuxProductNameFile = "/sys/class/dmi/id/product_name" func manufacturer() ([]byte, error) { - return os.ReadFile(linuxProductNameFile) + return ioutil.ReadFile(linuxProductNameFile) } diff --git a/vendor/google.golang.org/grpc/internal/grpclog/grpclog.go b/vendor/google.golang.org/grpc/internal/grpclog/grpclog.go index b68e26a364935..30a3b4258fc00 100644 --- a/vendor/google.golang.org/grpc/internal/grpclog/grpclog.go +++ b/vendor/google.golang.org/grpc/internal/grpclog/grpclog.go @@ -110,7 +110,7 @@ type LoggerV2 interface { // This is a copy of the DepthLoggerV2 defined in the external grpclog package. // It is defined here to avoid a circular dependency. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. diff --git a/vendor/google.golang.org/grpc/internal/grpcsync/oncefunc.go b/vendor/google.golang.org/grpc/internal/grpcsync/oncefunc.go deleted file mode 100644 index 6635f7bca96da..0000000000000 --- a/vendor/google.golang.org/grpc/internal/grpcsync/oncefunc.go +++ /dev/null @@ -1,32 +0,0 @@ -/* - * - * Copyright 2022 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 grpcsync - -import ( - "sync" -) - -// OnceFunc returns a function wrapping f which ensures f is only executed -// once even if the returned function is executed multiple times. -func OnceFunc(f func()) func() { - var once sync.Once - return func() { - once.Do(f) - } -} diff --git a/vendor/google.golang.org/grpc/internal/grpcutil/compressor.go b/vendor/google.golang.org/grpc/internal/grpcutil/compressor.go deleted file mode 100644 index 9f4090967980b..0000000000000 --- a/vendor/google.golang.org/grpc/internal/grpcutil/compressor.go +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * Copyright 2022 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 grpcutil - -import ( - "strings" - - "google.golang.org/grpc/internal/envconfig" -) - -// RegisteredCompressorNames holds names of the registered compressors. -var RegisteredCompressorNames []string - -// IsCompressorNameRegistered returns true when name is available in registry. -func IsCompressorNameRegistered(name string) bool { - for _, compressor := range RegisteredCompressorNames { - if compressor == name { - return true - } - } - return false -} - -// RegisteredCompressors returns a string of registered compressor names -// separated by comma. -func RegisteredCompressors() string { - if !envconfig.AdvertiseCompressors { - return "" - } - return strings.Join(RegisteredCompressorNames, ",") -} diff --git a/vendor/google.golang.org/grpc/internal/grpcutil/method.go b/vendor/google.golang.org/grpc/internal/grpcutil/method.go index ec62b4775e5b4..e9c4af64830c5 100644 --- a/vendor/google.golang.org/grpc/internal/grpcutil/method.go +++ b/vendor/google.golang.org/grpc/internal/grpcutil/method.go @@ -25,6 +25,7 @@ import ( // ParseMethod splits service and method from the input. It expects format // "/service/method". +// func ParseMethod(methodName string) (service, method string, _ error) { if !strings.HasPrefix(methodName, "/") { return "", "", errors.New("invalid method name: should start with /") diff --git a/vendor/google.golang.org/grpc/internal/internal.go b/vendor/google.golang.org/grpc/internal/internal.go index 0a76d9de6e027..fd0ee3dcaf1ef 100644 --- a/vendor/google.golang.org/grpc/internal/internal.go +++ b/vendor/google.golang.org/grpc/internal/internal.go @@ -77,9 +77,6 @@ var ( // ClearGlobalDialOptions clears the array of extra DialOption. This // method is useful in testing and benchmarking. ClearGlobalDialOptions func() - // JoinDialOptions combines the dial options passed as arguments into a - // single dial option. - JoinDialOptions interface{} // func(...grpc.DialOption) grpc.DialOption // JoinServerOptions combines the server options passed as arguments into a // single server option. JoinServerOptions interface{} // func(...grpc.ServerOption) grpc.ServerOption diff --git a/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go b/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go index 09a667f33cb09..75301c514913c 100644 --- a/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go +++ b/vendor/google.golang.org/grpc/internal/resolver/dns/dns_resolver.go @@ -116,7 +116,7 @@ type dnsBuilder struct{} // Build creates and starts a DNS resolver that watches the name resolution of the target. func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) { - host, port, err := parseTarget(target.Endpoint(), defaultPort) + host, port, err := parseTarget(target.Endpoint, defaultPort) if err != nil { return nil, err } @@ -140,10 +140,10 @@ func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts disableServiceConfig: opts.DisableServiceConfig, } - if target.URL.Host == "" { + if target.Authority == "" { d.resolver = defaultResolver } else { - d.resolver, err = customAuthorityResolver(target.URL.Host) + d.resolver, err = customAuthorityResolver(target.Authority) if err != nil { return nil, err } diff --git a/vendor/google.golang.org/grpc/internal/resolver/passthrough/passthrough.go b/vendor/google.golang.org/grpc/internal/resolver/passthrough/passthrough.go index afac56572ad55..520d9229e1ed7 100644 --- a/vendor/google.golang.org/grpc/internal/resolver/passthrough/passthrough.go +++ b/vendor/google.golang.org/grpc/internal/resolver/passthrough/passthrough.go @@ -20,20 +20,13 @@ // name without scheme back to gRPC as resolved address. package passthrough -import ( - "errors" - - "google.golang.org/grpc/resolver" -) +import "google.golang.org/grpc/resolver" const scheme = "passthrough" type passthroughBuilder struct{} func (*passthroughBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) { - if target.Endpoint() == "" && opts.Dialer == nil { - return nil, errors.New("passthrough: received empty target in Build()") - } r := &passthroughResolver{ target: target, cc: cc, @@ -52,7 +45,7 @@ type passthroughResolver struct { } func (r *passthroughResolver) start() { - r.cc.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: r.target.Endpoint()}}}) + r.cc.UpdateState(resolver.State{Addresses: []resolver.Address{{Addr: r.target.Endpoint}}}) } func (*passthroughResolver) ResolveNow(o resolver.ResolveNowOptions) {} diff --git a/vendor/google.golang.org/grpc/internal/resolver/unix/unix.go b/vendor/google.golang.org/grpc/internal/resolver/unix/unix.go index 1609116877383..7f1a702cacbef 100644 --- a/vendor/google.golang.org/grpc/internal/resolver/unix/unix.go +++ b/vendor/google.golang.org/grpc/internal/resolver/unix/unix.go @@ -34,8 +34,8 @@ type builder struct { } func (b *builder) Build(target resolver.Target, cc resolver.ClientConn, _ resolver.BuildOptions) (resolver.Resolver, error) { - if target.URL.Host != "" { - return nil, fmt.Errorf("invalid (non-empty) authority: %v", target.URL.Host) + if target.Authority != "" { + return nil, fmt.Errorf("invalid (non-empty) authority: %v", target.Authority) } // gRPC was parsing the dial target manually before PR #4817, and we diff --git a/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go b/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go index 51e733e495a36..badbdbf597f3f 100644 --- a/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go +++ b/vendor/google.golang.org/grpc/internal/serviceconfig/serviceconfig.go @@ -67,10 +67,10 @@ func (bc *BalancerConfig) MarshalJSON() ([]byte, error) { // ServiceConfig contains a list of loadBalancingConfigs, each with a name and // config. This method iterates through that list in order, and stops at the // first policy that is supported. -// - If the config for the first supported policy is invalid, the whole service -// config is invalid. -// - If the list doesn't contain any supported policy, the whole service config -// is invalid. +// - If the config for the first supported policy is invalid, the whole service +// config is invalid. +// - If the list doesn't contain any supported policy, the whole service config +// is invalid. func (bc *BalancerConfig) UnmarshalJSON(b []byte) error { var ir intermediateBalancerConfig err := json.Unmarshal(b, &ir) diff --git a/vendor/google.golang.org/grpc/internal/status/status.go b/vendor/google.golang.org/grpc/internal/status/status.go index b0ead4f54f82f..e5c6513edd138 100644 --- a/vendor/google.golang.org/grpc/internal/status/status.go +++ b/vendor/google.golang.org/grpc/internal/status/status.go @@ -164,13 +164,3 @@ func (e *Error) Is(target error) bool { } return proto.Equal(e.s.s, tse.s.s) } - -// IsRestrictedControlPlaneCode returns whether the status includes a code -// restricted for control plane usage as defined by gRFC A54. -func IsRestrictedControlPlaneCode(s *Status) bool { - switch s.Code() { - case codes.InvalidArgument, codes.NotFound, codes.AlreadyExists, codes.FailedPrecondition, codes.Aborted, codes.OutOfRange, codes.DataLoss: - return true - } - return false -} diff --git a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go index 9097385e1a6a5..409769f48fdcc 100644 --- a/vendor/google.golang.org/grpc/internal/transport/controlbuf.go +++ b/vendor/google.golang.org/grpc/internal/transport/controlbuf.go @@ -191,7 +191,7 @@ type goAway struct { code http2.ErrCode debugData []byte headsUp bool - closeConn error // if set, loopyWriter will exit, resulting in conn closure + closeConn bool } func (*goAway) isTransportResponseFrame() bool { return false } @@ -209,14 +209,6 @@ type outFlowControlSizeRequest struct { func (*outFlowControlSizeRequest) isTransportResponseFrame() bool { return false } -// closeConnection is an instruction to tell the loopy writer to flush the -// framer and exit, which will cause the transport's connection to be closed -// (by the client or server). The transport itself will close after the reader -// encounters the EOF caused by the connection closure. -type closeConnection struct{} - -func (closeConnection) isTransportResponseFrame() bool { return false } - type outStreamState int const ( @@ -416,7 +408,7 @@ func (c *controlBuffer) get(block bool) (interface{}, error) { select { case <-c.ch: case <-c.done: - return nil, errors.New("transport closed by client") + return nil, ErrConnClosing } } } @@ -527,9 +519,18 @@ const minBatchSize = 1000 // As an optimization, to increase the batch size for each flush, loopy yields the processor, once // if the batch size is too low to give stream goroutines a chance to fill it up. func (l *loopyWriter) run() (err error) { - // Always flush the writer before exiting in case there are pending frames - // to be sent. - defer l.framer.writer.Flush() + defer func() { + if err == ErrConnClosing { + // Don't log ErrConnClosing as error since it happens + // 1. When the connection is closed by some other known issue. + // 2. User closed the connection. + // 3. A graceful close of connection. + if logger.V(logLevel) { + logger.Infof("transport: loopyWriter.run returning. %v", err) + } + err = nil + } + }() for { it, err := l.cbuf.get(true) if err != nil { @@ -573,6 +574,7 @@ func (l *loopyWriter) run() (err error) { } l.framer.writer.Flush() break hasdata + } } } @@ -653,19 +655,18 @@ func (l *loopyWriter) headerHandler(h *headerFrame) error { itl: &itemList{}, wq: h.wq, } - return l.originateStream(str, h) + str.itl.enqueue(h) + return l.originateStream(str) } -func (l *loopyWriter) originateStream(str *outStream, hdr *headerFrame) error { - // l.draining is set when handling GoAway. In which case, we want to avoid - // creating new streams. - if l.draining { - // TODO: provide a better error with the reason we are in draining. - hdr.onOrphaned(errStreamDrain) - return nil - } +func (l *loopyWriter) originateStream(str *outStream) error { + hdr := str.itl.dequeue().(*headerFrame) if err := hdr.initStream(str.id); err != nil { - return err + if err == ErrConnClosing { + return err + } + // Other errors(errStreamDrain) need not close transport. + return nil } if err := l.writeHeader(str.id, hdr.endStream, hdr.hf, hdr.onWrite); err != nil { return err @@ -762,8 +763,8 @@ func (l *loopyWriter) cleanupStreamHandler(c *cleanupStream) error { return err } } - if l.draining && len(l.estdStreams) == 0 { - return errors.New("finished processing active streams while in draining mode") + if l.side == clientSide && l.draining && len(l.estdStreams) == 0 { + return ErrConnClosing } return nil } @@ -798,7 +799,7 @@ func (l *loopyWriter) incomingGoAwayHandler(*incomingGoAway) error { if l.side == clientSide { l.draining = true if len(l.estdStreams) == 0 { - return errors.New("received GOAWAY with no active streams") + return ErrConnClosing } } return nil @@ -816,13 +817,6 @@ func (l *loopyWriter) goAwayHandler(g *goAway) error { return nil } -func (l *loopyWriter) closeConnectionHandler() error { - // Exit loopyWriter entirely by returning an error here. This will lead to - // the transport closing the connection, and, ultimately, transport - // closure. - return ErrConnClosing -} - func (l *loopyWriter) handle(i interface{}) error { switch i := i.(type) { case *incomingWindowUpdate: @@ -851,8 +845,6 @@ func (l *loopyWriter) handle(i interface{}) error { return l.goAwayHandler(i) case *outFlowControlSizeRequest: return l.outFlowControlSizeRequestHandler(i) - case closeConnection: - return l.closeConnectionHandler() default: return fmt.Errorf("transport: unknown control message type %T", i) } diff --git a/vendor/google.golang.org/grpc/internal/transport/defaults.go b/vendor/google.golang.org/grpc/internal/transport/defaults.go index bc8ee07474968..9fa306b2e07a2 100644 --- a/vendor/google.golang.org/grpc/internal/transport/defaults.go +++ b/vendor/google.golang.org/grpc/internal/transport/defaults.go @@ -47,9 +47,3 @@ const ( defaultClientMaxHeaderListSize = uint32(16 << 20) defaultServerMaxHeaderListSize = uint32(16 << 20) ) - -// MaxStreamID is the upper bound for the stream ID before the current -// transport gracefully closes and new transport is created for subsequent RPCs. -// This is set to 75% of 2^31-1. Streams are identified with an unsigned 31-bit -// integer. It's exported so that tests can override it. -var MaxStreamID = uint32(math.MaxInt32 * 3 / 4) diff --git a/vendor/google.golang.org/grpc/internal/transport/handler_server.go b/vendor/google.golang.org/grpc/internal/transport/handler_server.go index e6626bf96e7c5..090120925bb46 100644 --- a/vendor/google.golang.org/grpc/internal/transport/handler_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/handler_server.go @@ -46,32 +46,24 @@ import ( "google.golang.org/grpc/status" ) -// NewServerHandlerTransport returns a ServerTransport handling gRPC from -// inside an http.Handler, or writes an HTTP error to w and returns an error. -// It requires that the http Server supports HTTP/2. +// NewServerHandlerTransport returns a ServerTransport handling gRPC +// from inside an http.Handler. It requires that the http Server +// supports HTTP/2. func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request, stats []stats.Handler) (ServerTransport, error) { if r.ProtoMajor != 2 { - msg := "gRPC requires HTTP/2" - http.Error(w, msg, http.StatusBadRequest) - return nil, errors.New(msg) + return nil, errors.New("gRPC requires HTTP/2") } if r.Method != "POST" { - msg := fmt.Sprintf("invalid gRPC request method %q", r.Method) - http.Error(w, msg, http.StatusBadRequest) - return nil, errors.New(msg) + return nil, errors.New("invalid gRPC request method") } contentType := r.Header.Get("Content-Type") // TODO: do we assume contentType is lowercase? we did before contentSubtype, validContentType := grpcutil.ContentSubtype(contentType) if !validContentType { - msg := fmt.Sprintf("invalid gRPC request content-type %q", contentType) - http.Error(w, msg, http.StatusUnsupportedMediaType) - return nil, errors.New(msg) + return nil, errors.New("invalid gRPC request content-type") } if _, ok := w.(http.Flusher); !ok { - msg := "gRPC requires a ResponseWriter supporting http.Flusher" - http.Error(w, msg, http.StatusInternalServerError) - return nil, errors.New(msg) + return nil, errors.New("gRPC requires a ResponseWriter supporting http.Flusher") } st := &serverHandlerTransport{ @@ -87,9 +79,7 @@ func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request, stats []s if v := r.Header.Get("grpc-timeout"); v != "" { to, err := decodeTimeout(v) if err != nil { - msg := fmt.Sprintf("malformed grpc-timeout: %v", err) - http.Error(w, msg, http.StatusBadRequest) - return nil, status.Error(codes.Internal, msg) + return nil, status.Errorf(codes.Internal, "malformed time-out: %v", err) } st.timeoutSet = true st.timeout = to @@ -107,9 +97,7 @@ func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request, stats []s for _, v := range vv { v, err := decodeMetadataHeader(k, v) if err != nil { - msg := fmt.Sprintf("malformed binary metadata %q in header %q: %v", v, k, err) - http.Error(w, msg, http.StatusBadRequest) - return nil, status.Error(codes.Internal, msg) + return nil, status.Errorf(codes.Internal, "malformed binary metadata: %v", err) } metakv = append(metakv, k, v) } @@ -153,15 +141,12 @@ type serverHandlerTransport struct { stats []stats.Handler } -func (ht *serverHandlerTransport) Close(err error) { - ht.closeOnce.Do(func() { - if logger.V(logLevel) { - logger.Infof("Closing serverHandlerTransport: %v", err) - } - close(ht.closedCh) - }) +func (ht *serverHandlerTransport) Close() { + ht.closeOnce.Do(ht.closeCloseChanOnce) } +func (ht *serverHandlerTransport) closeCloseChanOnce() { close(ht.closedCh) } + func (ht *serverHandlerTransport) RemoteAddr() net.Addr { return strAddr(ht.req.RemoteAddr) } // strAddr is a net.Addr backed by either a TCP "ip:port" string, or @@ -251,7 +236,7 @@ func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) erro }) } } - ht.Close(errors.New("finished writing status")) + ht.Close() return err } @@ -361,7 +346,7 @@ func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), trace case <-ht.req.Context().Done(): } cancel() - ht.Close(errors.New("request is done processing")) + ht.Close() }() req := ht.req @@ -457,10 +442,10 @@ func (ht *serverHandlerTransport) Drain() { // mapRecvMsgError returns the non-nil err into the appropriate // error value as expected by callers of *grpc.parser.recvMsg. // In particular, in can only be: -// - io.EOF -// - io.ErrUnexpectedEOF -// - of type transport.ConnectionError -// - an error from the status package +// * io.EOF +// * io.ErrUnexpectedEOF +// * of type transport.ConnectionError +// * an error from the status package func mapRecvMsgError(err error) error { if err == io.EOF || err == io.ErrUnexpectedEOF { return err diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_client.go b/vendor/google.golang.org/grpc/internal/transport/http2_client.go index 79ee8aea0a21a..5c2f35b24e75b 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_client.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_client.go @@ -38,10 +38,8 @@ import ( "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal/channelz" icredentials "google.golang.org/grpc/internal/credentials" - "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/grpcutil" imetadata "google.golang.org/grpc/internal/metadata" - istatus "google.golang.org/grpc/internal/status" "google.golang.org/grpc/internal/syscall" "google.golang.org/grpc/internal/transport/networktype" "google.golang.org/grpc/keepalive" @@ -59,15 +57,11 @@ var clientConnectionCounter uint64 // http2Client implements the ClientTransport interface with HTTP2. type http2Client struct { - lastRead int64 // Keep this field 64-bit aligned. Accessed atomically. - ctx context.Context - cancel context.CancelFunc - ctxDone <-chan struct{} // Cache the ctx.Done() chan. - userAgent string - // address contains the resolver returned address for this transport. - // If the `ServerName` field is set, it takes precedence over `CallHdr.Host` - // passed to `NewStream`, when determining the :authority header. - address resolver.Address + lastRead int64 // Keep this field 64-bit aligned. Accessed atomically. + ctx context.Context + cancel context.CancelFunc + ctxDone <-chan struct{} // Cache the ctx.Done() chan. + userAgent string md metadata.MD conn net.Conn // underlying communication channel loopy *loopyWriter @@ -105,13 +99,16 @@ type http2Client struct { maxSendHeaderListSize *uint32 bdpEst *bdpEstimator + // onPrefaceReceipt is a callback that client transport calls upon + // receiving server preface to signal that a succefull HTTP2 + // connection was established. + onPrefaceReceipt func() maxConcurrentStreams uint32 streamQuota int64 streamsQuotaAvailable chan struct{} waitingStreams uint32 nextID uint32 - registeredCompressors string // Do not access controlBuf with mu held. mu sync.Mutex // guard the following variables @@ -140,7 +137,8 @@ type http2Client struct { channelzID *channelz.Identifier czData *channelzData - onClose func(GoAwayReason) + onGoAway func(GoAwayReason) + onClose func() bufferPool *bufferPool @@ -196,7 +194,7 @@ func isTemporary(err error) bool { // newHTTP2Client constructs a connected ClientTransport to addr based on HTTP2 // and starts to receive messages on it. Non-nil error returns if construction // fails. -func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts ConnectOptions, onClose func(GoAwayReason)) (_ *http2Client, err error) { +func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts ConnectOptions, onPrefaceReceipt func(), onGoAway func(GoAwayReason), onClose func()) (_ *http2Client, err error) { scheme := "http" ctx, cancel := context.WithCancel(ctx) defer func() { @@ -216,40 +214,14 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts if opts.FailOnNonTempDialError { return nil, connectionErrorf(isTemporary(err), err, "transport: error while dialing: %v", err) } - return nil, connectionErrorf(true, err, "transport: Error while dialing: %v", err) + return nil, connectionErrorf(true, err, "transport: Error while dialing %v", err) } - // Any further errors will close the underlying connection defer func(conn net.Conn) { if err != nil { conn.Close() } }(conn) - - // The following defer and goroutine monitor the connectCtx for cancelation - // and deadline. On context expiration, the connection is hard closed and - // this function will naturally fail as a result. Otherwise, the defer - // waits for the goroutine to exit to prevent the context from being - // monitored (and to prevent the connection from ever being closed) after - // returning from this function. - ctxMonitorDone := grpcsync.NewEvent() - newClientCtx, newClientDone := context.WithCancel(connectCtx) - defer func() { - newClientDone() // Awaken the goroutine below if connectCtx hasn't expired. - <-ctxMonitorDone.Done() // Wait for the goroutine below to exit. - }() - go func(conn net.Conn) { - defer ctxMonitorDone.Fire() // Signal this goroutine has exited. - <-newClientCtx.Done() // Block until connectCtx expires or the defer above executes. - if err := connectCtx.Err(); err != nil { - // connectCtx expired before exiting the function. Hard close the connection. - if logger.V(logLevel) { - logger.Infof("newClientTransport: aborting due to connectCtx: %v", err) - } - conn.Close() - } - }(conn) - kp := opts.KeepaliveParams // Validate keepalive parameters. if kp.Time == 0 { @@ -281,7 +253,15 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts } } if transportCreds != nil { - conn, authInfo, err = transportCreds.ClientHandshake(connectCtx, addr.ServerName, conn) + rawConn := conn + // Pull the deadline from the connectCtx, which will be used for + // timeouts in the authentication protocol handshake. Can ignore the + // boolean as the deadline will return the zero value, which will make + // the conn not timeout on I/O operations. + deadline, _ := connectCtx.Deadline() + rawConn.SetDeadline(deadline) + conn, authInfo, err = transportCreds.ClientHandshake(connectCtx, addr.ServerName, rawConn) + rawConn.SetDeadline(time.Time{}) if err != nil { return nil, connectionErrorf(isTemporary(err), err, "transport: authentication handshake failed: %v", err) } @@ -319,8 +299,6 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts ctxDone: ctx.Done(), // Cache Done chan. cancel: cancel, userAgent: opts.UserAgent, - registeredCompressors: grpcutil.RegisteredCompressors(), - address: addr, conn: conn, remoteAddr: conn.RemoteAddr(), localAddr: conn.LocalAddr(), @@ -337,14 +315,16 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts kp: kp, statsHandlers: opts.StatsHandlers, initialWindowSize: initialWindowSize, + onPrefaceReceipt: onPrefaceReceipt, nextID: 1, maxConcurrentStreams: defaultMaxStreamsClient, streamQuota: defaultMaxStreamsClient, streamsQuotaAvailable: make(chan struct{}, 1), czData: new(channelzData), + onGoAway: onGoAway, + onClose: onClose, keepaliveEnabled: keepaliveEnabled, bufferPool: newBufferPool(), - onClose: onClose, } // Add peer information to the http2client context. t.ctx = peer.NewContext(t.ctx, t.getPeer()) @@ -383,32 +363,21 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts t.kpDormancyCond = sync.NewCond(&t.mu) go t.keepalive() } - - // Start the reader goroutine for incoming messages. Each transport has a - // dedicated goroutine which reads HTTP2 frames from the network. Then it - // dispatches the frame to the corresponding stream entity. When the - // server preface is received, readerErrCh is closed. If an error occurs - // first, an error is pushed to the channel. This must be checked before - // returning from this function. - readerErrCh := make(chan error, 1) - go t.reader(readerErrCh) - defer func() { - if err == nil { - err = <-readerErrCh - } - if err != nil { - t.Close(err) - } - }() + // Start the reader goroutine for incoming message. Each transport has + // a dedicated goroutine which reads HTTP2 frame from network. Then it + // dispatches the frame to the corresponding stream entity. + go t.reader() // Send connection preface to server. n, err := t.conn.Write(clientPreface) if err != nil { err = connectionErrorf(true, err, "transport: failed to write client preface: %v", err) + t.Close(err) return nil, err } if n != len(clientPreface) { err = connectionErrorf(true, nil, "transport: preface mismatch, wrote %d bytes; want %d", n, len(clientPreface)) + t.Close(err) return nil, err } var ss []http2.Setting @@ -428,12 +397,14 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts err = t.framer.fr.WriteSettings(ss...) if err != nil { err = connectionErrorf(true, err, "transport: failed to write initial settings frame: %v", err) + t.Close(err) return nil, err } // Adjust the connection flow control window if needed. if delta := uint32(icwz - defaultWindowSize); delta > 0 { if err := t.framer.fr.WriteWindowUpdate(0, delta); err != nil { err = connectionErrorf(true, err, "transport: failed to write window update: %v", err) + t.Close(err) return nil, err } } @@ -446,8 +417,10 @@ func newHTTP2Client(connectCtx, ctx context.Context, addr resolver.Address, opts go func() { t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst) err := t.loopy.run() - if logger.V(logLevel) { - logger.Infof("transport: loopyWriter exited. Closing connection. Err: %v", err) + if err != nil { + if logger.V(logLevel) { + logger.Errorf("transport: loopyWriter.run returning. Err: %v", err) + } } // Do not close the transport. Let reader goroutine handle it since // there might be data in the buffers. @@ -534,22 +507,9 @@ func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-previous-rpc-attempts", Value: strconv.Itoa(callHdr.PreviousAttempts)}) } - registeredCompressors := t.registeredCompressors if callHdr.SendCompress != "" { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: callHdr.SendCompress}) - // Include the outgoing compressor name when compressor is not registered - // via encoding.RegisterCompressor. This is possible when client uses - // WithCompressor dial option. - if !grpcutil.IsCompressorNameRegistered(callHdr.SendCompress) { - if registeredCompressors != "" { - registeredCompressors += "," - } - registeredCompressors += callHdr.SendCompress - } - } - - if registeredCompressors != "" { - headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-accept-encoding", Value: registeredCompressors}) + headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-accept-encoding", Value: callHdr.SendCompress}) } if dl, ok := ctx.Deadline(); ok { // Send out timeout regardless its value. The server can detect timeout context by itself. @@ -629,11 +589,7 @@ func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[s for _, c := range t.perRPCCreds { data, err := c.GetRequestMetadata(ctx, audience) if err != nil { - if st, ok := status.FromError(err); ok { - // Restrict the code to the list allowed by gRFC A54. - if istatus.IsRestrictedControlPlaneCode(st) { - err = status.Errorf(codes.Internal, "transport: received per-RPC creds error with illegal status: %v", err) - } + if _, ok := status.FromError(err); ok { return nil, err } @@ -662,14 +618,7 @@ func (t *http2Client) getCallAuthData(ctx context.Context, audience string, call } data, err := callCreds.GetRequestMetadata(ctx, audience) if err != nil { - if st, ok := status.FromError(err); ok { - // Restrict the code to the list allowed by gRFC A54. - if istatus.IsRestrictedControlPlaneCode(st) { - err = status.Errorf(codes.Internal, "transport: received per-RPC creds error with illegal status: %v", err) - } - return nil, err - } - return nil, status.Errorf(codes.Internal, "transport: per-RPC creds failed due to error: %v", err) + return nil, status.Errorf(codes.Internal, "transport: %v", err) } callAuthData = make(map[string]string, len(data)) for k, v := range data { @@ -685,13 +634,13 @@ func (t *http2Client) getCallAuthData(ctx context.Context, audience string, call // NewStream errors result in transparent retry, as they mean nothing went onto // the wire. However, there are two notable exceptions: // -// 1. If the stream headers violate the max header list size allowed by the -// server. It's possible this could succeed on another transport, even if -// it's unlikely, but do not transparently retry. -// 2. If the credentials errored when requesting their headers. In this case, -// it's possible a retry can fix the problem, but indefinitely transparently -// retrying is not appropriate as it is likely the credentials, if they can -// eventually succeed, would need I/O to do so. +// 1. If the stream headers violate the max header list size allowed by the +// server. It's possible this could succeed on another transport, even if +// it's unlikely, but do not transparently retry. +// 2. If the credentials errored when requesting their headers. In this case, +// it's possible a retry can fix the problem, but indefinitely transparently +// retrying is not appropriate as it is likely the credentials, if they can +// eventually succeed, would need I/O to do so. type NewStreamError struct { Err error @@ -706,18 +655,6 @@ func (e NewStreamError) Error() string { // streams. All non-nil errors returned will be *NewStreamError. func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, error) { ctx = peer.NewContext(ctx, t.getPeer()) - - // ServerName field of the resolver returned address takes precedence over - // Host field of CallHdr to determine the :authority header. This is because, - // the ServerName field takes precedence for server authentication during - // TLS handshake, and the :authority header should match the value used - // for server authentication. - if t.address.ServerName != "" { - newCallHdr := *callHdr - newCallHdr.Host = t.address.ServerName - callHdr = &newCallHdr - } - headerFields, err := t.createHeaderFields(ctx, callHdr) if err != nil { return nil, &NewStreamError{Err: err, AllowTransparentRetry: false} @@ -742,12 +679,15 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, endStream: false, initStream: func(id uint32) error { t.mu.Lock() - // TODO: handle transport closure in loopy instead and remove this - // initStream is never called when transport is draining. - if t.state == closing { + if state := t.state; state != reachable { t.mu.Unlock() - cleanup(ErrConnClosing) - return ErrConnClosing + // Do a quick cleanup. + err := error(errStreamDrain) + if state == closing { + err = ErrConnClosing + } + cleanup(err) + return err } if channelz.IsOn() { atomic.AddInt64(&t.czData.streamsStarted, 1) @@ -765,7 +705,6 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, } firstTry := true var ch chan struct{} - transportDrainRequired := false checkForStreamQuota := func(it interface{}) bool { if t.streamQuota <= 0 { // Can go negative if server decreases it. if firstTry { @@ -781,11 +720,6 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, h := it.(*headerFrame) h.streamID = t.nextID t.nextID += 2 - - // Drain client transport if nextID > MaxStreamID which signals gRPC that - // the connection is closed and a new one must be created for subsequent RPCs. - transportDrainRequired = t.nextID > MaxStreamID - s.id = h.streamID s.fc = &inFlow{limit: uint32(t.initialWindowSize)} t.mu.Lock() @@ -865,12 +799,6 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (*Stream, sh.HandleRPC(s.ctx, outHeader) } } - if transportDrainRequired { - if logger.V(logLevel) { - logger.Infof("transport: t.nextID > MaxStreamID. Draining") - } - t.GracefulClose() - } return s, nil } @@ -952,21 +880,20 @@ func (t *http2Client) closeStream(s *Stream, err error, rst bool, rstCode http2. // Close kicks off the shutdown process of the transport. This should be called // only once on a transport. Once it is called, the transport should not be // accessed any more. +// +// This method blocks until the addrConn that initiated this transport is +// re-connected. This happens because t.onClose() begins reconnect logic at the +// addrConn level and blocks until the addrConn is successfully connected. func (t *http2Client) Close(err error) { t.mu.Lock() - // Make sure we only close once. + // Make sure we only Close once. if t.state == closing { t.mu.Unlock() return } - if logger.V(logLevel) { - logger.Infof("transport: closing: %v", err) - } - // Call t.onClose ASAP to prevent the client from attempting to create new - // streams. - if t.state != draining { - t.onClose(GoAwayInvalid) - } + // Call t.onClose before setting the state to closing to prevent the client + // from attempting to create new streams ASAP. + t.onClose() t.state = closing streams := t.activeStreams t.activeStreams = nil @@ -1016,15 +943,11 @@ func (t *http2Client) GracefulClose() { t.mu.Unlock() return } - if logger.V(logLevel) { - logger.Infof("transport: GracefulClose called") - } - t.onClose(GoAwayInvalid) t.state = draining active := len(t.activeStreams) t.mu.Unlock() if active == 0 { - t.Close(connectionErrorf(true, nil, "no active streams left to process while draining")) + t.Close(ErrConnClosing) return } t.controlBuf.put(&incomingGoAway{}) @@ -1182,7 +1105,7 @@ func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) { statusCode, ok := http2ErrConvTab[f.ErrCode] if !ok { if logger.V(logLevel) { - logger.Warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error: %v", f.ErrCode) + logger.Warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode) } statusCode = codes.Unknown } @@ -1300,10 +1223,8 @@ func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { // Notify the clientconn about the GOAWAY before we set the state to // draining, to allow the client to stop attempting to create streams // before disallowing new streams on this connection. - if t.state != draining { - t.onClose(t.goAwayReason) - t.state = draining - } + t.onGoAway(t.goAwayReason) + t.state = draining } // All streams with IDs greater than the GoAwayId // and smaller than the previous GoAway ID should be killed. @@ -1561,35 +1482,33 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { t.closeStream(s, io.EOF, rst, http2.ErrCodeNo, statusGen, mdata, true) } -// readServerPreface reads and handles the initial settings frame from the -// server. -func (t *http2Client) readServerPreface() error { +// reader runs as a separate goroutine in charge of reading data from network +// connection. +// +// TODO(zhaoq): currently one reader per transport. Investigate whether this is +// optimal. +// TODO(zhaoq): Check the validity of the incoming frame sequence. +func (t *http2Client) reader() { + defer close(t.readerDone) + // Check the validity of server preface. frame, err := t.framer.fr.ReadFrame() if err != nil { - return connectionErrorf(true, err, "error reading server preface: %v", err) - } - sf, ok := frame.(*http2.SettingsFrame) - if !ok { - return connectionErrorf(true, nil, "initial http2 frame from server is not a settings frame: %T", frame) - } - t.handleSettings(sf, true) - return nil -} - -// reader verifies the server preface and reads all subsequent data from -// network connection. If the server preface is not read successfully, an -// error is pushed to errCh; otherwise errCh is closed with no error. -func (t *http2Client) reader(errCh chan<- error) { - defer close(t.readerDone) - - if err := t.readServerPreface(); err != nil { - errCh <- err + err = connectionErrorf(true, err, "error reading server preface: %v", err) + t.Close(err) // this kicks off resetTransport, so must be last before return return } - close(errCh) + t.conn.SetReadDeadline(time.Time{}) // reset deadline once we get the settings frame (we didn't time out, yay!) if t.keepaliveEnabled { atomic.StoreInt64(&t.lastRead, time.Now().UnixNano()) } + sf, ok := frame.(*http2.SettingsFrame) + if !ok { + // this kicks off resetTransport, so must be last before return + t.Close(connectionErrorf(true, nil, "initial http2 frame from server is not a settings frame: %T", frame)) + return + } + t.onPrefaceReceipt() + t.handleSettings(sf, true) // loop to keep reading incoming messages on this transport. for { @@ -1792,9 +1711,3 @@ func (t *http2Client) getOutFlowWindow() int64 { return -2 } } - -func (t *http2Client) stateForTesting() transportState { - t.mu.Lock() - defer t.mu.Unlock() - return t.state -} diff --git a/vendor/google.golang.org/grpc/internal/transport/http2_server.go b/vendor/google.golang.org/grpc/internal/transport/http2_server.go index bc3da706726d5..3dd15647bc84b 100644 --- a/vendor/google.golang.org/grpc/internal/transport/http2_server.go +++ b/vendor/google.golang.org/grpc/internal/transport/http2_server.go @@ -21,7 +21,6 @@ package transport import ( "bytes" "context" - "errors" "fmt" "io" "math" @@ -42,7 +41,6 @@ import ( "google.golang.org/grpc/credentials" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcrand" - "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" @@ -103,13 +101,13 @@ type http2Server struct { mu sync.Mutex // guard the following - // drainEvent is initialized when Drain() is called the first time. After - // which the server writes out the first GoAway(with ID 2^31-1) frame. Then - // an independent goroutine will be launched to later send the second - // GoAway. During this time we don't want to write another first GoAway(with - // ID 2^31 -1) frame. Thus call to Drain() will be a no-op if drainEvent is - // already initialized since draining is already underway. - drainEvent *grpcsync.Event + // drainChan is initialized when Drain() is called the first time. + // After which the server writes out the first GoAway(with ID 2^31-1) frame. + // Then an independent goroutine will be launched to later send the second GoAway. + // During this time we don't want to write another first GoAway(with ID 2^31 -1) frame. + // Thus call to Drain() will be a no-op if drainChan is already initialized since draining is + // already underway. + drainChan chan struct{} state transportState activeStreams map[uint32]*Stream // idle is the time instant when the connection went idle. @@ -295,7 +293,7 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, defer func() { if err != nil { - t.Close(err) + t.Close() } }() @@ -333,9 +331,10 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, go func() { t.loopy = newLoopyWriter(serverSide, t.framer, t.controlBuf, t.bdpEst) t.loopy.ssGoAwayHandler = t.outgoingGoAwayHandler - err := t.loopy.run() - if logger.V(logLevel) { - logger.Infof("transport: loopyWriter exited. Closing connection. Err: %v", err) + if err := t.loopy.run(); err != nil { + if logger.V(logLevel) { + logger.Errorf("transport: loopyWriter.run returning. Err: %v", err) + } } t.conn.Close() t.controlBuf.finish() @@ -345,9 +344,8 @@ func NewServerTransport(conn net.Conn, config *ServerConfig) (_ ServerTransport, return t, nil } -// operateHeaders takes action on the decoded headers. Returns an error if fatal -// error encountered and transport needs to close, otherwise returns nil. -func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func(*Stream), traceCtx func(context.Context, string) context.Context) error { +// operateHeader takes action on the decoded headers. +func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func(*Stream), traceCtx func(context.Context, string) context.Context) (fatal bool) { // Acquire max stream ID lock for entire duration t.maxStreamMu.Lock() defer t.maxStreamMu.Unlock() @@ -363,12 +361,15 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( rstCode: http2.ErrCodeFrameSize, onWrite: func() {}, }) - return nil + return false } if streamID%2 != 1 || streamID <= t.maxStreamID { // illegal gRPC stream id. - return fmt.Errorf("received an illegal stream id: %v. headers frame: %+v", streamID, frame) + if logger.V(logLevel) { + logger.Errorf("transport: http2Server.HandleStreams received an illegal stream id: %v", streamID) + } + return true } t.maxStreamID = streamID @@ -380,14 +381,13 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( fc: &inFlow{limit: uint32(t.initialWindowSize)}, } var ( - // if false, content-type was missing or invalid - isGRPC = false - contentType = "" - mdata = make(map[string][]string) - httpMethod string - // these are set if an error is encountered while parsing the headers - protocolError bool - headerError *status.Status + // If a gRPC Response-Headers has already been received, then it means + // that the peer is speaking gRPC and we are in gRPC mode. + isGRPC = false + mdata = make(map[string][]string) + httpMethod string + // headerError is set if an error is encountered while parsing the headers + headerError bool timeoutSet bool timeout time.Duration @@ -398,7 +398,6 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( case "content-type": contentSubtype, validContentType := grpcutil.ContentSubtype(hf.Value) if !validContentType { - contentType = hf.Value break } mdata[hf.Name] = append(mdata[hf.Name], hf.Value) @@ -414,7 +413,7 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( timeoutSet = true var err error if timeout, err = decodeTimeout(hf.Value); err != nil { - headerError = status.Newf(codes.Internal, "malformed grpc-timeout: %v", err) + headerError = true } // "Transports must consider requests containing the Connection header // as malformed." - A41 @@ -422,14 +421,14 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( if logger.V(logLevel) { logger.Errorf("transport: http2Server.operateHeaders parsed a :connection header which makes a request malformed as per the HTTP/2 spec") } - protocolError = true + headerError = true default: if isReservedHeader(hf.Name) && !isWhitelistedHeader(hf.Name) { break } v, err := decodeMetadataHeader(hf.Name, hf.Value) if err != nil { - headerError = status.Newf(codes.Internal, "malformed binary metadata %q in header %q: %v", hf.Value, hf.Name, err) + headerError = true logger.Warningf("Failed to decode metadata header (%q, %q): %v", hf.Name, hf.Value, err) break } @@ -448,43 +447,23 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( logger.Errorf("transport: %v", errMsg) } t.controlBuf.put(&earlyAbortStream{ - httpStatus: http.StatusBadRequest, + httpStatus: 400, streamID: streamID, contentSubtype: s.contentSubtype, status: status.New(codes.Internal, errMsg), rst: !frame.StreamEnded(), }) - return nil + return false } - if protocolError { + if !isGRPC || headerError { t.controlBuf.put(&cleanupStream{ streamID: streamID, rst: true, rstCode: http2.ErrCodeProtocol, onWrite: func() {}, }) - return nil - } - if !isGRPC { - t.controlBuf.put(&earlyAbortStream{ - httpStatus: http.StatusUnsupportedMediaType, - streamID: streamID, - contentSubtype: s.contentSubtype, - status: status.Newf(codes.InvalidArgument, "invalid gRPC request content-type %q", contentType), - rst: !frame.StreamEnded(), - }) - return nil - } - if headerError != nil { - t.controlBuf.put(&earlyAbortStream{ - httpStatus: http.StatusBadRequest, - streamID: streamID, - contentSubtype: s.contentSubtype, - status: headerError, - rst: !frame.StreamEnded(), - }) - return nil + return false } // "If :authority is missing, Host must be renamed to :authority." - A41 @@ -524,7 +503,7 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( if t.state != reachable { t.mu.Unlock() s.cancel() - return nil + return false } if uint32(len(t.activeStreams)) >= t.maxStreams { t.mu.Unlock() @@ -535,7 +514,7 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( onWrite: func() {}, }) s.cancel() - return nil + return false } if httpMethod != http.MethodPost { t.mu.Unlock() @@ -551,7 +530,7 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( rst: !frame.StreamEnded(), }) s.cancel() - return nil + return false } if t.inTapHandle != nil { var err error @@ -571,7 +550,7 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( status: stat, rst: !frame.StreamEnded(), }) - return nil + return false } } t.activeStreams[streamID] = s @@ -618,7 +597,7 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( wq: s.wq, }) handle(s) - return nil + return false } // HandleStreams receives incoming streams using the given handler. This is @@ -651,16 +630,19 @@ func (t *http2Server) HandleStreams(handle func(*Stream), traceCtx func(context. continue } if err == io.EOF || err == io.ErrUnexpectedEOF { - t.Close(err) + t.Close() return } - t.Close(err) + if logger.V(logLevel) { + logger.Warningf("transport: http2Server.HandleStreams failed to read frame: %v", err) + } + t.Close() return } switch frame := frame.(type) { case *http2.MetaHeadersFrame: - if err := t.operateHeaders(frame, handle, traceCtx); err != nil { - t.Close(err) + if t.operateHeaders(frame, handle, traceCtx) { + t.Close() break } case *http2.DataFrame: @@ -861,8 +843,8 @@ const ( func (t *http2Server) handlePing(f *http2.PingFrame) { if f.IsAck() { - if f.Data == goAwayPing.data && t.drainEvent != nil { - t.drainEvent.Fire() + if f.Data == goAwayPing.data && t.drainChan != nil { + close(t.drainChan) return } // Maybe it's a BDP ping. @@ -904,7 +886,10 @@ func (t *http2Server) handlePing(f *http2.PingFrame) { if t.pingStrikes > maxPingStrikes { // Send goaway and close the connection. - t.controlBuf.put(&goAway{code: http2.ErrCodeEnhanceYourCalm, debugData: []byte("too_many_pings"), closeConn: errors.New("got too many pings from the client")}) + if logger.V(logLevel) { + logger.Errorf("transport: Got too many pings from the client, closing the connection.") + } + t.controlBuf.put(&goAway{code: http2.ErrCodeEnhanceYourCalm, debugData: []byte("too_many_pings"), closeConn: true}) } } @@ -1168,7 +1153,7 @@ func (t *http2Server) keepalive() { if logger.V(logLevel) { logger.Infof("transport: closing server transport due to maximum connection age.") } - t.controlBuf.put(closeConnection{}) + t.Close() case <-t.done: } return @@ -1184,7 +1169,10 @@ func (t *http2Server) keepalive() { continue } if outstandingPing && kpTimeoutLeft <= 0 { - t.Close(fmt.Errorf("keepalive ping not acked within timeout %s", t.kp.Time)) + if logger.V(logLevel) { + logger.Infof("transport: closing server transport due to idleness.") + } + t.Close() return } if !outstandingPing { @@ -1211,15 +1199,12 @@ func (t *http2Server) keepalive() { // Close starts shutting down the http2Server transport. // TODO(zhaoq): Now the destruction is not blocked on any pending streams. This // could cause some resource issue. Revisit this later. -func (t *http2Server) Close(err error) { +func (t *http2Server) Close() { t.mu.Lock() if t.state == closing { t.mu.Unlock() return } - if logger.V(logLevel) { - logger.Infof("transport: closing: %v", err) - } t.state = closing streams := t.activeStreams t.activeStreams = nil @@ -1310,10 +1295,10 @@ func (t *http2Server) RemoteAddr() net.Addr { func (t *http2Server) Drain() { t.mu.Lock() defer t.mu.Unlock() - if t.drainEvent != nil { + if t.drainChan != nil { return } - t.drainEvent = grpcsync.NewEvent() + t.drainChan = make(chan struct{}) t.controlBuf.put(&goAway{code: http2.ErrCodeNo, debugData: []byte{}, headsUp: true}) } @@ -1334,20 +1319,19 @@ func (t *http2Server) outgoingGoAwayHandler(g *goAway) (bool, error) { // Stop accepting more streams now. t.state = draining sid := t.maxStreamID - retErr := g.closeConn if len(t.activeStreams) == 0 { - retErr = errors.New("second GOAWAY written and no active streams left to process") + g.closeConn = true } t.mu.Unlock() t.maxStreamMu.Unlock() if err := t.framer.fr.WriteGoAway(sid, g.code, g.debugData); err != nil { return false, err } - if retErr != nil { + if g.closeConn { // Abruptly close the connection following the GoAway (via // loopywriter). But flush out what's inside the buffer first. t.framer.writer.Flush() - return false, retErr + return false, fmt.Errorf("transport: Connection closing") } return true, nil } @@ -1369,7 +1353,7 @@ func (t *http2Server) outgoingGoAwayHandler(g *goAway) (bool, error) { timer := time.NewTimer(time.Minute) defer timer.Stop() select { - case <-t.drainEvent.Done(): + case <-t.drainChan: case <-timer.C: case <-t.done: return diff --git a/vendor/google.golang.org/grpc/internal/transport/transport.go b/vendor/google.golang.org/grpc/internal/transport/transport.go index 0ac77ea4f8c70..6c3ba8515940e 100644 --- a/vendor/google.golang.org/grpc/internal/transport/transport.go +++ b/vendor/google.golang.org/grpc/internal/transport/transport.go @@ -43,10 +43,6 @@ import ( "google.golang.org/grpc/tap" ) -// ErrNoHeaders is used as a signal that a trailers only response was received, -// and is not a real error. -var ErrNoHeaders = errors.New("stream has no headers") - const logLevel = 2 type bufferPool struct { @@ -370,15 +366,9 @@ func (s *Stream) Header() (metadata.MD, error) { return s.header.Copy(), nil } s.waitOnHeader() - if !s.headerValid { return nil, s.status.Err() } - - if s.noHeaders { - return nil, ErrNoHeaders - } - return s.header.Copy(), nil } @@ -583,8 +573,8 @@ type ConnectOptions struct { // NewClientTransport establishes the transport with the required ConnectOptions // and returns it to the caller. -func NewClientTransport(connectCtx, ctx context.Context, addr resolver.Address, opts ConnectOptions, onClose func(GoAwayReason)) (ClientTransport, error) { - return newHTTP2Client(connectCtx, ctx, addr, opts, onClose) +func NewClientTransport(connectCtx, ctx context.Context, addr resolver.Address, opts ConnectOptions, onPrefaceReceipt func(), onGoAway func(GoAwayReason), onClose func()) (ClientTransport, error) { + return newHTTP2Client(connectCtx, ctx, addr, opts, onPrefaceReceipt, onGoAway, onClose) } // Options provides additional hints and information for message @@ -701,7 +691,7 @@ type ServerTransport interface { // Close tears down the transport. Once it is called, the transport // should not be accessed any more. All the pending streams and their // handlers will be terminated asynchronously. - Close(err error) + Close() // RemoteAddr returns the remote network address. RemoteAddr() net.Addr diff --git a/vendor/google.golang.org/grpc/metadata/metadata.go b/vendor/google.golang.org/grpc/metadata/metadata.go index fb4a88f59bd3c..98d62e0675f61 100644 --- a/vendor/google.golang.org/grpc/metadata/metadata.go +++ b/vendor/google.golang.org/grpc/metadata/metadata.go @@ -41,11 +41,10 @@ type MD map[string][]string // New creates an MD from a given key-value map. // // Only the following ASCII characters are allowed in keys: -// - digits: 0-9 -// - uppercase letters: A-Z (normalized to lower) -// - lowercase letters: a-z -// - special characters: -_. -// +// - digits: 0-9 +// - uppercase letters: A-Z (normalized to lower) +// - lowercase letters: a-z +// - special characters: -_. // Uppercase letters are automatically converted to lowercase. // // Keys beginning with "grpc-" are reserved for grpc-internal use only and may @@ -63,11 +62,10 @@ func New(m map[string]string) MD { // Pairs panics if len(kv) is odd. // // Only the following ASCII characters are allowed in keys: -// - digits: 0-9 -// - uppercase letters: A-Z (normalized to lower) -// - lowercase letters: a-z -// - special characters: -_. -// +// - digits: 0-9 +// - uppercase letters: A-Z (normalized to lower) +// - lowercase letters: a-z +// - special characters: -_. // Uppercase letters are automatically converted to lowercase. // // Keys beginning with "grpc-" are reserved for grpc-internal use only and may @@ -198,7 +196,7 @@ func FromIncomingContext(ctx context.Context) (MD, bool) { // ValueFromIncomingContext returns the metadata value corresponding to the metadata // key from the incoming metadata if it exists. Key must be lower-case. // -// # Experimental +// Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. diff --git a/vendor/google.golang.org/grpc/picker_wrapper.go b/vendor/google.golang.org/grpc/picker_wrapper.go index c525dc070fc6d..843633c910a11 100644 --- a/vendor/google.golang.org/grpc/picker_wrapper.go +++ b/vendor/google.golang.org/grpc/picker_wrapper.go @@ -26,7 +26,6 @@ import ( "google.golang.org/grpc/balancer" "google.golang.org/grpc/codes" "google.golang.org/grpc/internal/channelz" - istatus "google.golang.org/grpc/internal/status" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/status" ) @@ -58,18 +57,12 @@ func (pw *pickerWrapper) updatePicker(p balancer.Picker) { pw.mu.Unlock() } -// doneChannelzWrapper performs the following: -// - increments the calls started channelz counter -// - wraps the done function in the passed in result to increment the calls -// failed or calls succeeded channelz counter before invoking the actual -// done function. -func doneChannelzWrapper(acw *acBalancerWrapper, result *balancer.PickResult) { +func doneChannelzWrapper(acw *acBalancerWrapper, done func(balancer.DoneInfo)) func(balancer.DoneInfo) { acw.mu.Lock() ac := acw.ac acw.mu.Unlock() ac.incrCallsStarted() - done := result.Done - result.Done = func(b balancer.DoneInfo) { + return func(b balancer.DoneInfo) { if b.Err != nil && b.Err != io.EOF { ac.incrCallsFailed() } else { @@ -88,7 +81,7 @@ func doneChannelzWrapper(acw *acBalancerWrapper, result *balancer.PickResult) { // - the current picker returns other errors and failfast is false. // - the subConn returned by the current picker is not READY // When one of these situations happens, pick blocks until the picker gets updated. -func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer.PickInfo) (transport.ClientTransport, balancer.PickResult, error) { +func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer.PickInfo) (transport.ClientTransport, func(balancer.DoneInfo), error) { var ch chan struct{} var lastPickErr error @@ -96,7 +89,7 @@ func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer. pw.mu.Lock() if pw.done { pw.mu.Unlock() - return nil, balancer.PickResult{}, ErrClientConnClosing + return nil, nil, ErrClientConnClosing } if pw.picker == nil { @@ -117,9 +110,9 @@ func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer. } switch ctx.Err() { case context.DeadlineExceeded: - return nil, balancer.PickResult{}, status.Error(codes.DeadlineExceeded, errStr) + return nil, nil, status.Error(codes.DeadlineExceeded, errStr) case context.Canceled: - return nil, balancer.PickResult{}, status.Error(codes.Canceled, errStr) + return nil, nil, status.Error(codes.Canceled, errStr) } case <-ch: } @@ -131,17 +124,14 @@ func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer. pw.mu.Unlock() pickResult, err := p.Pick(info) + if err != nil { if err == balancer.ErrNoSubConnAvailable { continue } - if st, ok := status.FromError(err); ok { + if _, ok := status.FromError(err); ok { // Status error: end the RPC unconditionally with this status. - // First restrict the code to the list allowed by gRFC A54. - if istatus.IsRestrictedControlPlaneCode(st) { - err = status.Errorf(codes.Internal, "received picker error with illegal status: %v", err) - } - return nil, balancer.PickResult{}, dropError{error: err} + return nil, nil, dropError{error: err} } // For all other errors, wait for ready RPCs should block and other // RPCs should fail with unavailable. @@ -149,7 +139,7 @@ func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer. lastPickErr = err continue } - return nil, balancer.PickResult{}, status.Error(codes.Unavailable, err.Error()) + return nil, nil, status.Error(codes.Unavailable, err.Error()) } acw, ok := pickResult.SubConn.(*acBalancerWrapper) @@ -159,10 +149,9 @@ func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer. } if t := acw.getAddrConn().getReadyTransport(); t != nil { if channelz.IsOn() { - doneChannelzWrapper(acw, &pickResult) - return t, pickResult, nil + return t, doneChannelzWrapper(acw, pickResult.Done), nil } - return t, pickResult, nil + return t, pickResult.Done, nil } if pickResult.Done != nil { // Calling done with nil error, no bytes sent and no bytes received. diff --git a/vendor/google.golang.org/grpc/pickfirst.go b/vendor/google.golang.org/grpc/pickfirst.go index fc91b4d266de2..fb7a99e0a2734 100644 --- a/vendor/google.golang.org/grpc/pickfirst.go +++ b/vendor/google.golang.org/grpc/pickfirst.go @@ -51,7 +51,7 @@ type pickfirstBalancer struct { func (b *pickfirstBalancer) ResolverError(err error) { if logger.V(2) { - logger.Infof("pickfirstBalancer: ResolverError called with error: %v", err) + logger.Infof("pickfirstBalancer: ResolverError called with error %v", err) } if b.subConn == nil { b.state = connectivity.TransientFailure @@ -102,8 +102,8 @@ func (b *pickfirstBalancer) UpdateClientConnState(state balancer.ClientConnState b.subConn = subConn b.state = connectivity.Idle b.cc.UpdateState(balancer.State{ - ConnectivityState: connectivity.Connecting, - Picker: &picker{err: balancer.ErrNoSubConnAvailable}, + ConnectivityState: connectivity.Idle, + Picker: &picker{result: balancer.PickResult{SubConn: b.subConn}}, }) b.subConn.Connect() return nil diff --git a/vendor/google.golang.org/grpc/preloader.go b/vendor/google.golang.org/grpc/preloader.go index cd45547854f07..0a1e975ad9164 100644 --- a/vendor/google.golang.org/grpc/preloader.go +++ b/vendor/google.golang.org/grpc/preloader.go @@ -25,7 +25,7 @@ import ( // PreparedMsg is responsible for creating a Marshalled and Compressed object. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. diff --git a/vendor/google.golang.org/grpc/regenerate.sh b/vendor/google.golang.org/grpc/regenerate.sh index a6f26c8ab0f03..99db79fafcfb8 100644 --- a/vendor/google.golang.org/grpc/regenerate.sh +++ b/vendor/google.golang.org/grpc/regenerate.sh @@ -57,8 +57,7 @@ LEGACY_SOURCES=( ${WORKDIR}/grpc-proto/grpc/health/v1/health.proto ${WORKDIR}/grpc-proto/grpc/lb/v1/load_balancer.proto profiling/proto/service.proto - ${WORKDIR}/grpc-proto/grpc/reflection/v1alpha/reflection.proto - ${WORKDIR}/grpc-proto/grpc/reflection/v1/reflection.proto + reflection/grpc_reflection_v1alpha/reflection.proto ) # Generates only the new gRPC Service symbols @@ -120,4 +119,8 @@ mv ${WORKDIR}/out/google.golang.org/grpc/lookup/grpc_lookup_v1/* ${WORKDIR}/out/ # see grpc_testing_not_regenerate/README.md for details. rm ${WORKDIR}/out/google.golang.org/grpc/reflection/grpc_testing_not_regenerate/*.pb.go +# grpc/testing does not have a go_package option. +mv ${WORKDIR}/out/grpc/testing/*.pb.go interop/grpc_testing/ +mv ${WORKDIR}/out/grpc/core/*.pb.go interop/grpc_testing/core/ + cp -R ${WORKDIR}/out/google.golang.org/grpc/* . diff --git a/vendor/google.golang.org/grpc/resolver/resolver.go b/vendor/google.golang.org/grpc/resolver/resolver.go index 654e9ce69f4a8..ca2e35a3596f7 100644 --- a/vendor/google.golang.org/grpc/resolver/resolver.go +++ b/vendor/google.golang.org/grpc/resolver/resolver.go @@ -24,7 +24,6 @@ import ( "context" "net" "net/url" - "strings" "google.golang.org/grpc/attributes" "google.golang.org/grpc/credentials" @@ -97,7 +96,7 @@ const ( // Address represents a server the client connects to. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -237,17 +236,20 @@ type ClientConn interface { // // Examples: // -// - "dns://some_authority/foo.bar" -// Target{Scheme: "dns", Authority: "some_authority", Endpoint: "foo.bar"} -// - "foo.bar" -// Target{Scheme: resolver.GetDefaultScheme(), Endpoint: "foo.bar"} -// - "unknown_scheme://authority/endpoint" -// Target{Scheme: resolver.GetDefaultScheme(), Endpoint: "unknown_scheme://authority/endpoint"} +// - "dns://some_authority/foo.bar" +// Target{Scheme: "dns", Authority: "some_authority", Endpoint: "foo.bar"} +// - "foo.bar" +// Target{Scheme: resolver.GetDefaultScheme(), Endpoint: "foo.bar"} +// - "unknown_scheme://authority/endpoint" +// Target{Scheme: resolver.GetDefaultScheme(), Endpoint: "unknown_scheme://authority/endpoint"} type Target struct { // Deprecated: use URL.Scheme instead. Scheme string // Deprecated: use URL.Host instead. Authority string + // Deprecated: use URL.Path or URL.Opaque instead. The latter is set when + // the former is empty. + Endpoint string // URL contains the parsed dial target with an optional default scheme added // to it if the original dial target contained no scheme or contained an // unregistered scheme. Any query params specified in the original dial @@ -255,24 +257,6 @@ type Target struct { URL url.URL } -// Endpoint retrieves endpoint without leading "/" from either `URL.Path` -// or `URL.Opaque`. The latter is used when the former is empty. -func (t Target) Endpoint() string { - endpoint := t.URL.Path - if endpoint == "" { - endpoint = t.URL.Opaque - } - // For targets of the form "[scheme]://[authority]/endpoint, the endpoint - // value returned from url.Parse() contains a leading "/". Although this is - // in accordance with RFC 3986, we do not want to break existing resolver - // implementations which expect the endpoint without the leading "/". So, we - // end up stripping the leading "/" here. But this will result in an - // incorrect parsing for something like "unix:///path/to/socket". Since we - // own the "unix" resolver, we can workaround in the unix resolver by using - // the `URL` field. - return strings.TrimPrefix(endpoint, "/") -} - // Builder creates a resolver that will be used to watch name resolution updates. type Builder interface { // Build creates a new resolver for the given target. diff --git a/vendor/google.golang.org/grpc/rpc_util.go b/vendor/google.golang.org/grpc/rpc_util.go index cb7020ebecd78..5d407b004b0ed 100644 --- a/vendor/google.golang.org/grpc/rpc_util.go +++ b/vendor/google.golang.org/grpc/rpc_util.go @@ -25,6 +25,7 @@ import ( "encoding/binary" "fmt" "io" + "io/ioutil" "math" "strings" "sync" @@ -76,7 +77,7 @@ func NewGZIPCompressorWithLevel(level int) (Compressor, error) { return &gzipCompressor{ pool: sync.Pool{ New: func() interface{} { - w, err := gzip.NewWriterLevel(io.Discard, level) + w, err := gzip.NewWriterLevel(ioutil.Discard, level) if err != nil { panic(err) } @@ -142,7 +143,7 @@ func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) { z.Close() d.pool.Put(z) }() - return io.ReadAll(z) + return ioutil.ReadAll(z) } func (d *gzipDecompressor) Type() string { @@ -197,7 +198,7 @@ func Header(md *metadata.MD) CallOption { // HeaderCallOption is a CallOption for collecting response header metadata. // The metadata field will be populated *after* the RPC completes. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -219,7 +220,7 @@ func Trailer(md *metadata.MD) CallOption { // TrailerCallOption is a CallOption for collecting response trailer metadata. // The metadata field will be populated *after* the RPC completes. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -241,7 +242,7 @@ func Peer(p *peer.Peer) CallOption { // PeerCallOption is a CallOption for collecting the identity of the remote // peer. The peer field will be populated *after* the RPC completes. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -281,7 +282,7 @@ func FailFast(failFast bool) CallOption { // FailFastCallOption is a CallOption for indicating whether an RPC should fail // fast or not. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -296,8 +297,7 @@ func (o FailFastCallOption) before(c *callInfo) error { func (o FailFastCallOption) after(c *callInfo, attempt *csAttempt) {} // MaxCallRecvMsgSize returns a CallOption which sets the maximum message size -// in bytes the client can receive. If this is not set, gRPC uses the default -// 4MB. +// in bytes the client can receive. func MaxCallRecvMsgSize(bytes int) CallOption { return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: bytes} } @@ -305,7 +305,7 @@ func MaxCallRecvMsgSize(bytes int) CallOption { // MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message // size in bytes the client can receive. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -320,8 +320,7 @@ func (o MaxRecvMsgSizeCallOption) before(c *callInfo) error { func (o MaxRecvMsgSizeCallOption) after(c *callInfo, attempt *csAttempt) {} // MaxCallSendMsgSize returns a CallOption which sets the maximum message size -// in bytes the client can send. If this is not set, gRPC uses the default -// `math.MaxInt32`. +// in bytes the client can send. func MaxCallSendMsgSize(bytes int) CallOption { return MaxSendMsgSizeCallOption{MaxSendMsgSize: bytes} } @@ -329,7 +328,7 @@ func MaxCallSendMsgSize(bytes int) CallOption { // MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message // size in bytes the client can send. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -352,7 +351,7 @@ func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption { // PerRPCCredsCallOption is a CallOption that indicates the per-RPC // credentials to use for the call. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -370,7 +369,7 @@ func (o PerRPCCredsCallOption) after(c *callInfo, attempt *csAttempt) {} // sending the request. If WithCompressor is also set, UseCompressor has // higher priority. // -// # Experimental +// Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. @@ -380,7 +379,7 @@ func UseCompressor(name string) CallOption { // CompressorCallOption is a CallOption that indicates the compressor to use. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -417,7 +416,7 @@ func CallContentSubtype(contentSubtype string) CallOption { // ContentSubtypeCallOption is a CallOption that indicates the content-subtype // used for marshaling messages. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -445,7 +444,7 @@ func (o ContentSubtypeCallOption) after(c *callInfo, attempt *csAttempt) {} // This function is provided for advanced users; prefer to use only // CallContentSubtype to select a registered codec instead. // -// # Experimental +// Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. @@ -456,7 +455,7 @@ func ForceCodec(codec encoding.Codec) CallOption { // ForceCodecCallOption is a CallOption that indicates the codec used for // marshaling messages. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -481,7 +480,7 @@ func CallCustomCodec(codec Codec) CallOption { // CustomCodecCallOption is a CallOption that indicates the codec used for // marshaling messages. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -498,7 +497,7 @@ func (o CustomCodecCallOption) after(c *callInfo, attempt *csAttempt) {} // MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory // used for buffering this RPC's requests for retry purposes. // -// # Experimental +// Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. @@ -509,7 +508,7 @@ func MaxRetryRPCBufferSize(bytes int) CallOption { // MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of // memory to be used for caching this RPC for retry purposes. // -// # Experimental +// Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. @@ -549,11 +548,10 @@ type parser struct { // format. The caller owns the returned msg memory. // // If there is an error, possible values are: -// - io.EOF, when no messages remain -// - io.ErrUnexpectedEOF -// - of type transport.ConnectionError -// - an error from the status package -// +// * io.EOF, when no messages remain +// * io.ErrUnexpectedEOF +// * of type transport.ConnectionError +// * an error from the status package // No other error values or types must be returned, which also means // that the underlying io.Reader must not return an incompatible // error. @@ -712,7 +710,7 @@ func recvAndDecompress(p *parser, s *transport.Stream, dc Decompressor, maxRecei d, size, err = decompress(compressor, d, maxReceiveMessageSize) } if err != nil { - return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message: %v", err) + return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) } if size > maxReceiveMessageSize { // TODO: Revisit the error code. Currently keep it consistent with java @@ -747,7 +745,7 @@ func decompress(compressor encoding.Compressor, d []byte, maxReceiveMessageSize } // Read from LimitReader with limit max+1. So if the underlying // reader is over limit, the result will be bigger than max. - d, err = io.ReadAll(io.LimitReader(dcReader, int64(maxReceiveMessageSize)+1)) + d, err = ioutil.ReadAll(io.LimitReader(dcReader, int64(maxReceiveMessageSize)+1)) return d, len(d), err } @@ -760,7 +758,7 @@ func recv(p *parser, c baseCodec, s *transport.Stream, dc Decompressor, m interf return err } if err := c.Unmarshal(d, m); err != nil { - return status.Errorf(codes.Internal, "grpc: failed to unmarshal the received message: %v", err) + return status.Errorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err) } if payInfo != nil { payInfo.uncompressedBytes = d diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go index d5a6e78be44d0..f4dde72b41f89 100644 --- a/vendor/google.golang.org/grpc/server.go +++ b/vendor/google.golang.org/grpc/server.go @@ -233,11 +233,10 @@ func newJoinServerOption(opts ...ServerOption) ServerOption { return &joinServerOption{opts: opts} } -// WriteBufferSize determines how much data can be batched before doing a write -// on the wire. The corresponding memory allocation for this buffer will be -// twice the size to keep syscalls low. The default value for this buffer is -// 32KB. Zero or negative values will disable the write buffer such that each -// write will be on underlying connection. +// WriteBufferSize determines how much data can be batched before doing a write on the wire. +// The corresponding memory allocation for this buffer will be twice the size to keep syscalls low. +// The default value for this buffer is 32KB. +// Zero will disable the write buffer such that each write will be on underlying connection. // Note: A Send call may not directly translate to a write. func WriteBufferSize(s int) ServerOption { return newFuncServerOption(func(o *serverOptions) { @@ -245,10 +244,11 @@ func WriteBufferSize(s int) ServerOption { }) } -// ReadBufferSize lets you set the size of read buffer, this determines how much -// data can be read at most for one read syscall. The default value for this -// buffer is 32KB. Zero or negative values will disable read buffer for a -// connection so data framer can access the underlying conn directly. +// ReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most +// for one read syscall. +// The default value for this buffer is 32KB. +// Zero will disable read buffer for a connection so data framer can access the underlying +// conn directly. func ReadBufferSize(s int) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.readBufferSize = s @@ -942,7 +942,7 @@ func (s *Server) newHTTP2Transport(c net.Conn) transport.ServerTransport { } func (s *Server) serveStreams(st transport.ServerTransport) { - defer st.Close(errors.New("finished serving streams for the server transport")) + defer st.Close() var wg sync.WaitGroup var roundRobinCounter uint32 @@ -1008,8 +1008,7 @@ var _ http.Handler = (*Server)(nil) func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { st, err := transport.NewServerHandlerTransport(w, r, s.opts.statsHandlers) if err != nil { - // Errors returned from transport.NewServerHandlerTransport have - // already been written to w. + http.Error(w, err.Error(), http.StatusInternalServerError) return } if !s.addConn(listenerAddressForServeHTTP, st) { @@ -1047,7 +1046,7 @@ func (s *Server) addConn(addr string, st transport.ServerTransport) bool { s.mu.Lock() defer s.mu.Unlock() if s.conns == nil { - st.Close(errors.New("Server.addConn called when server has already been stopped")) + st.Close() return false } if s.drain { @@ -1151,16 +1150,21 @@ func chainUnaryServerInterceptors(s *Server) { func chainUnaryInterceptors(interceptors []UnaryServerInterceptor) UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (interface{}, error) { - return interceptors[0](ctx, req, info, getChainUnaryHandler(interceptors, 0, info, handler)) - } -} - -func getChainUnaryHandler(interceptors []UnaryServerInterceptor, curr int, info *UnaryServerInfo, finalHandler UnaryHandler) UnaryHandler { - if curr == len(interceptors)-1 { - return finalHandler - } - return func(ctx context.Context, req interface{}) (interface{}, error) { - return interceptors[curr+1](ctx, req, info, getChainUnaryHandler(interceptors, curr+1, info, finalHandler)) + // the struct ensures the variables are allocated together, rather than separately, since we + // know they should be garbage collected together. This saves 1 allocation and decreases + // time/call by about 10% on the microbenchmark. + var state struct { + i int + next UnaryHandler + } + state.next = func(ctx context.Context, req interface{}) (interface{}, error) { + if state.i == len(interceptors)-1 { + return interceptors[state.i](ctx, req, info, handler) + } + state.i++ + return interceptors[state.i-1](ctx, req, info, state.next) + } + return state.next(ctx, req) } } @@ -1299,7 +1303,7 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. d, err := recvAndDecompress(&parser{r: stream}, stream, dc, s.opts.maxReceiveMessageSize, payInfo, decomp) if err != nil { if e := t.WriteStatus(stream, status.Convert(err)); e != nil { - channelz.Warningf(logger, s.channelzID, "grpc: Server.processUnaryRPC failed to write status: %v", e) + channelz.Warningf(logger, s.channelzID, "grpc: Server.processUnaryRPC failed to write status %v", e) } return err } @@ -1466,16 +1470,21 @@ func chainStreamServerInterceptors(s *Server) { func chainStreamInterceptors(interceptors []StreamServerInterceptor) StreamServerInterceptor { return func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error { - return interceptors[0](srv, ss, info, getChainStreamHandler(interceptors, 0, info, handler)) - } -} - -func getChainStreamHandler(interceptors []StreamServerInterceptor, curr int, info *StreamServerInfo, finalHandler StreamHandler) StreamHandler { - if curr == len(interceptors)-1 { - return finalHandler - } - return func(srv interface{}, stream ServerStream) error { - return interceptors[curr+1](srv, stream, info, getChainStreamHandler(interceptors, curr+1, info, finalHandler)) + // the struct ensures the variables are allocated together, rather than separately, since we + // know they should be garbage collected together. This saves 1 allocation and decreases + // time/call by about 10% on the microbenchmark. + var state struct { + i int + next StreamHandler + } + state.next = func(srv interface{}, ss ServerStream) error { + if state.i == len(interceptors)-1 { + return interceptors[state.i](srv, ss, info, handler) + } + state.i++ + return interceptors[state.i-1](srv, ss, info, state.next) + } + return state.next(srv, ss) } } @@ -1810,7 +1819,7 @@ func (s *Server) Stop() { } for _, cs := range conns { for st := range cs { - st.Close(errors.New("Server.Stop called")) + st.Close() } } if s.opts.numServerWorkers > 0 { diff --git a/vendor/google.golang.org/grpc/service_config.go b/vendor/google.golang.org/grpc/service_config.go index f22acace4253c..01bbb2025aed4 100644 --- a/vendor/google.golang.org/grpc/service_config.go +++ b/vendor/google.golang.org/grpc/service_config.go @@ -226,7 +226,7 @@ func parseServiceConfig(js string) *serviceconfig.ParseResult { var rsc jsonSC err := json.Unmarshal([]byte(js), &rsc) if err != nil { - logger.Warningf("grpc: unmarshaling service config %s: %v", js, err) + logger.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err) return &serviceconfig.ParseResult{Err: err} } sc := ServiceConfig{ @@ -254,7 +254,7 @@ func parseServiceConfig(js string) *serviceconfig.ParseResult { } d, err := parseDuration(m.Timeout) if err != nil { - logger.Warningf("grpc: unmarshaling service config %s: %v", js, err) + logger.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err) return &serviceconfig.ParseResult{Err: err} } @@ -263,7 +263,7 @@ func parseServiceConfig(js string) *serviceconfig.ParseResult { Timeout: d, } if mc.RetryPolicy, err = convertRetryPolicy(m.RetryPolicy); err != nil { - logger.Warningf("grpc: unmarshaling service config %s: %v", js, err) + logger.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err) return &serviceconfig.ParseResult{Err: err} } if m.MaxRequestMessageBytes != nil { @@ -283,13 +283,13 @@ func parseServiceConfig(js string) *serviceconfig.ParseResult { for i, n := range *m.Name { path, err := n.generatePath() if err != nil { - logger.Warningf("grpc: error unmarshaling service config %s due to methodConfig[%d]: %v", js, i, err) + logger.Warningf("grpc: parseServiceConfig error unmarshaling %s due to methodConfig[%d]: %v", js, i, err) return &serviceconfig.ParseResult{Err: err} } if _, ok := paths[path]; ok { err = errDuplicatedName - logger.Warningf("grpc: error unmarshaling service config %s due to methodConfig[%d]: %v", js, i, err) + logger.Warningf("grpc: parseServiceConfig error unmarshaling %s due to methodConfig[%d]: %v", js, i, err) return &serviceconfig.ParseResult{Err: err} } paths[path] = struct{}{} diff --git a/vendor/google.golang.org/grpc/serviceconfig/serviceconfig.go b/vendor/google.golang.org/grpc/serviceconfig/serviceconfig.go index 35e7a20a04baa..73a2f926613e4 100644 --- a/vendor/google.golang.org/grpc/serviceconfig/serviceconfig.go +++ b/vendor/google.golang.org/grpc/serviceconfig/serviceconfig.go @@ -19,7 +19,7 @@ // Package serviceconfig defines types and methods for operating on gRPC // service configs. // -// # Experimental +// Experimental // // Notice: This package is EXPERIMENTAL and may be changed or removed in a // later release. diff --git a/vendor/google.golang.org/grpc/status/status.go b/vendor/google.golang.org/grpc/status/status.go index 623be39f26bab..6d163b6e38422 100644 --- a/vendor/google.golang.org/grpc/status/status.go +++ b/vendor/google.golang.org/grpc/status/status.go @@ -76,14 +76,14 @@ func FromProto(s *spb.Status) *Status { // FromError returns a Status representation of err. // -// - If err was produced by this package or implements the method `GRPCStatus() -// *Status`, the appropriate Status is returned. +// - If err was produced by this package or implements the method `GRPCStatus() +// *Status`, the appropriate Status is returned. // -// - If err is nil, a Status is returned with codes.OK and no message. +// - If err is nil, a Status is returned with codes.OK and no message. // -// - Otherwise, err is an error not compatible with this package. In this -// case, a Status is returned with codes.Unknown and err's Error() message, -// and ok is false. +// - Otherwise, err is an error not compatible with this package. In this +// case, a Status is returned with codes.Unknown and err's Error() message, +// and ok is false. func FromError(err error) (s *Status, ok bool) { if err == nil { return nil, true diff --git a/vendor/google.golang.org/grpc/stream.go b/vendor/google.golang.org/grpc/stream.go index 93231af2ac569..0c16cfb2ea807 100644 --- a/vendor/google.golang.org/grpc/stream.go +++ b/vendor/google.golang.org/grpc/stream.go @@ -39,7 +39,6 @@ import ( imetadata "google.golang.org/grpc/internal/metadata" iresolver "google.golang.org/grpc/internal/resolver" "google.golang.org/grpc/internal/serviceconfig" - istatus "google.golang.org/grpc/internal/status" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" @@ -196,13 +195,6 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth rpcInfo := iresolver.RPCInfo{Context: ctx, Method: method} rpcConfig, err := cc.safeConfigSelector.SelectConfig(rpcInfo) if err != nil { - if st, ok := status.FromError(err); ok { - // Restrict the code to the list allowed by gRFC A54. - if istatus.IsRestrictedControlPlaneCode(st) { - err = status.Errorf(codes.Internal, "config selector returned illegal status: %v", err) - } - return nil, err - } return nil, toRPCErr(err) } @@ -416,7 +408,7 @@ func (cs *clientStream) newAttemptLocked(isTransparent bool) (*csAttempt, error) ctx = trace.NewContext(ctx, trInfo.tr) } - if cs.cc.parsedTarget.URL.Scheme == "xds" { + if cs.cc.parsedTarget.Scheme == "xds" { // Add extra metadata (metadata that will be added by transport) to context // so the balancer can see them. ctx = grpcutil.WithExtraMetadata(ctx, metadata.Pairs( @@ -438,7 +430,7 @@ func (a *csAttempt) getTransport() error { cs := a.cs var err error - a.t, a.pickResult, err = cs.cc.getTransport(a.ctx, cs.callInfo.failFast, cs.callHdr.Method) + a.t, a.done, err = cs.cc.getTransport(a.ctx, cs.callInfo.failFast, cs.callHdr.Method) if err != nil { if de, ok := err.(dropError); ok { err = de.error @@ -455,25 +447,6 @@ func (a *csAttempt) getTransport() error { func (a *csAttempt) newStream() error { cs := a.cs cs.callHdr.PreviousAttempts = cs.numRetries - - // Merge metadata stored in PickResult, if any, with existing call metadata. - // It is safe to overwrite the csAttempt's context here, since all state - // maintained in it are local to the attempt. When the attempt has to be - // retried, a new instance of csAttempt will be created. - if a.pickResult.Metatada != nil { - // We currently do not have a function it the metadata package which - // merges given metadata with existing metadata in a context. Existing - // function `AppendToOutgoingContext()` takes a variadic argument of key - // value pairs. - // - // TODO: Make it possible to retrieve key value pairs from metadata.MD - // in a form passable to AppendToOutgoingContext(), or create a version - // of AppendToOutgoingContext() that accepts a metadata.MD. - md, _ := metadata.FromOutgoingContext(a.ctx) - md = metadata.Join(md, a.pickResult.Metatada) - a.ctx = metadata.NewOutgoingContext(a.ctx, md) - } - s, err := a.t.NewStream(a.ctx, cs.callHdr) if err != nil { nse, ok := err.(*transport.NewStreamError) @@ -548,12 +521,12 @@ type clientStream struct { // csAttempt implements a single transport stream attempt within a // clientStream. type csAttempt struct { - ctx context.Context - cs *clientStream - t transport.ClientTransport - s *transport.Stream - p *parser - pickResult balancer.PickResult + ctx context.Context + cs *clientStream + t transport.ClientTransport + s *transport.Stream + p *parser + done func(balancer.DoneInfo) finished bool dc Decompressor @@ -771,25 +744,17 @@ func (cs *clientStream) withRetry(op func(a *csAttempt) error, onSuccess func()) func (cs *clientStream) Header() (metadata.MD, error) { var m metadata.MD - noHeader := false err := cs.withRetry(func(a *csAttempt) error { var err error m, err = a.s.Header() - if err == transport.ErrNoHeaders { - noHeader = true - return nil - } return toRPCErr(err) }, cs.commitAttemptLocked) - if err != nil { cs.finish(err) return nil, err } - - if len(cs.binlogs) != 0 && !cs.serverHeaderBinlogged && !noHeader { - // Only log if binary log is on and header has not been logged, and - // there is actually headers to log. + if len(cs.binlogs) != 0 && !cs.serverHeaderBinlogged { + // Only log if binary log is on and header has not been logged. logEntry := &binarylog.ServerHeader{ OnClientSide: true, Header: m, @@ -1122,12 +1087,12 @@ func (a *csAttempt) finish(err error) { tr = a.s.Trailer() } - if a.pickResult.Done != nil { + if a.done != nil { br := false if a.s != nil { br = a.s.BytesReceived() } - a.pickResult.Done(balancer.DoneInfo{ + a.done(balancer.DoneInfo{ Err: err, Trailer: tr, BytesSent: a.s != nil, @@ -1483,9 +1448,6 @@ type ServerStream interface { // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not safe // to call SendMsg on the same stream in different goroutines. - // - // It is not safe to modify the message after calling SendMsg. Tracing - // libraries and stats handlers may use the message lazily. SendMsg(m interface{}) error // RecvMsg blocks until it receives a message into m or the stream is // done. It returns io.EOF when the client has performed a CloseSend. On diff --git a/vendor/google.golang.org/grpc/tap/tap.go b/vendor/google.golang.org/grpc/tap/tap.go index bfa5dfa40e4d1..dbf34e6bb5f57 100644 --- a/vendor/google.golang.org/grpc/tap/tap.go +++ b/vendor/google.golang.org/grpc/tap/tap.go @@ -19,7 +19,7 @@ // Package tap defines the function handles which are executed on the transport // layer of gRPC-Go and related information. // -// # Experimental +// Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. diff --git a/vendor/google.golang.org/grpc/version.go b/vendor/google.golang.org/grpc/version.go index fe552c315be22..d472ca64307bb 100644 --- a/vendor/google.golang.org/grpc/version.go +++ b/vendor/google.golang.org/grpc/version.go @@ -19,4 +19,4 @@ package grpc // Version is the current grpc version. -const Version = "1.53.0" +const Version = "1.50.1" diff --git a/vendor/google.golang.org/grpc/vet.sh b/vendor/google.golang.org/grpc/vet.sh index 3728aed04fc74..c3fc8253b13a6 100644 --- a/vendor/google.golang.org/grpc/vet.sh +++ b/vendor/google.golang.org/grpc/vet.sh @@ -66,21 +66,8 @@ elif [[ "$#" -ne 0 ]]; then die "Unknown argument(s): $*" fi -# - Check that generated proto files are up to date. -if [[ -z "${VET_SKIP_PROTO}" ]]; then - PATH="/home/travis/bin:${PATH}" make proto && \ - git status --porcelain 2>&1 | fail_on_output || \ - (git status; git --no-pager diff; exit 1) -fi - -if [[ -n "${VET_ONLY_PROTO}" ]]; then - exit 0 -fi - # - Ensure all source files contain a copyright message. -# (Done in two parts because Darwin "git grep" has broken support for compound -# exclusion matches.) -(grep -L "DO NOT EDIT" $(git grep -L "\(Copyright [0-9]\{4,\} gRPC authors\)" -- '*.go') || true) | fail_on_output +not git grep -L "\(Copyright [0-9]\{4,\} gRPC authors\)\|DO NOT EDIT" -- '*.go' # - Make sure all tests in grpc and grpc/test use leakcheck via Teardown. not grep 'func Test[^(]' *_test.go @@ -94,7 +81,7 @@ not git grep -l 'x/net/context' -- "*.go" git grep -l '"math/rand"' -- "*.go" 2>&1 | not grep -v '^examples\|^stress\|grpcrand\|^benchmark\|wrr_test' # - Do not call grpclog directly. Use grpclog.Component instead. -git grep -l -e 'grpclog.I' --or -e 'grpclog.W' --or -e 'grpclog.E' --or -e 'grpclog.F' --or -e 'grpclog.V' -- "*.go" | not grep -v '^grpclog/component.go\|^internal/grpctest/tlogger_test.go' +git grep -l 'grpclog.I\|grpclog.W\|grpclog.E\|grpclog.F\|grpclog.V' -- "*.go" | not grep -v '^grpclog/component.go\|^internal/grpctest/tlogger_test.go' # - Ensure all ptypes proto packages are renamed when importing. not git grep "\(import \|^\s*\)\"github.com/golang/protobuf/ptypes/" -- "*.go" @@ -104,6 +91,13 @@ git grep '"github.com/envoyproxy/go-control-plane/envoy' -- '*.go' ':(exclude)*. misspell -error . +# - Check that generated proto files are up to date. +if [[ -z "${VET_SKIP_PROTO}" ]]; then + PATH="/home/travis/bin:${PATH}" make proto && \ + git status --porcelain 2>&1 | fail_on_output || \ + (git status; git --no-pager diff; exit 1) +fi + # - gofmt, goimports, golint (with exceptions for generated code), go vet, # go mod tidy. # Perform these checks on each module inside gRPC. @@ -115,7 +109,7 @@ for MOD_FILE in $(find . -name 'go.mod'); do goimports -l . 2>&1 | not grep -vE "\.pb\.go" golint ./... 2>&1 | not grep -vE "/grpc_testing_not_regenerate/.*\.pb\.go:" - go mod tidy -compat=1.17 + go mod tidy git status --porcelain 2>&1 | fail_on_output || \ (git status; git --no-pager diff; exit 1) popd @@ -125,9 +119,8 @@ done # # TODO(dfawley): don't use deprecated functions in examples or first-party # plugins. -# TODO(dfawley): enable ST1019 (duplicate imports) but allow for protobufs. SC_OUT="$(mktemp)" -staticcheck -go 1.19 -checks 'inherit,-ST1015,-ST1019,-SA1019' ./... > "${SC_OUT}" || true +staticcheck -go 1.9 -checks 'inherit,-ST1015' ./... > "${SC_OUT}" || true # Error if anything other than deprecation warnings are printed. not grep -v "is deprecated:.*SA1019" "${SC_OUT}" # Only ignore the following deprecated types/fields/functions. diff --git a/vendor/modules.txt b/vendor/modules.txt index a894ff738e21e..5e3afa51fcba2 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -486,6 +486,7 @@ github.com/golang/gddo/httputil/header github.com/golang/groupcache/lru # github.com/golang/protobuf v1.5.2 ## explicit; go 1.9 +github.com/golang/protobuf/descriptor github.com/golang/protobuf/jsonpb github.com/golang/protobuf/proto github.com/golang/protobuf/protoc-gen-go/descriptor @@ -541,11 +542,11 @@ github.com/grpc-ecosystem/go-grpc-middleware # github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 ## explicit github.com/grpc-ecosystem/go-grpc-prometheus -# github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0 +# github.com/grpc-ecosystem/grpc-gateway v1.16.0 ## explicit; go 1.14 -github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule -github.com/grpc-ecosystem/grpc-gateway/v2/runtime -github.com/grpc-ecosystem/grpc-gateway/v2/utilities +github.com/grpc-ecosystem/grpc-gateway/internal +github.com/grpc-ecosystem/grpc-gateway/runtime +github.com/grpc-ecosystem/grpc-gateway/utilities # github.com/hashicorp/errwrap v1.1.0 ## explicit github.com/hashicorp/errwrap @@ -1019,8 +1020,8 @@ go.opencensus.io/trace go.opencensus.io/trace/internal go.opencensus.io/trace/propagation go.opencensus.io/trace/tracestate -# go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.40.0 -## explicit; go 1.18 +# go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.40.0 => go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.29.0 +## explicit; go 1.16 go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal # go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.29.0 @@ -1035,8 +1036,6 @@ go.opentelemetry.io/otel go.opentelemetry.io/otel/attribute go.opentelemetry.io/otel/baggage go.opentelemetry.io/otel/codes -go.opentelemetry.io/otel/exporters/otlp/internal -go.opentelemetry.io/otel/exporters/otlp/internal/envconfig go.opentelemetry.io/otel/internal go.opentelemetry.io/otel/internal/attribute go.opentelemetry.io/otel/internal/baggage @@ -1050,23 +1049,28 @@ go.opentelemetry.io/otel/semconv/v1.7.0 # go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.14.0 ## explicit; go 1.18 go.opentelemetry.io/otel/exporters/otlp/internal/retry -# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0 -## explicit; go 1.18 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.14.0 => go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.4.1 +## explicit; go 1.16 go.opentelemetry.io/otel/exporters/otlp/otlptrace go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/otlpconfig go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform -# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0 -## explicit; go 1.18 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.14.0 => go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.4.1 +## explicit; go 1.16 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc -# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.14.0 -## explicit; go 1.18 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.14.0 => go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.4.1 +## explicit; go 1.16 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp -# go.opentelemetry.io/otel/metric v0.37.0 -## explicit; go 1.18 +# go.opentelemetry.io/otel/internal/metric v0.27.0 => go.opentelemetry.io/otel/internal/metric v0.27.0 +## explicit; go 1.16 +go.opentelemetry.io/otel/internal/metric/global +go.opentelemetry.io/otel/internal/metric/registry +# go.opentelemetry.io/otel/metric v0.37.0 => go.opentelemetry.io/otel/metric v0.27.0 +## explicit; go 1.16 go.opentelemetry.io/otel/metric go.opentelemetry.io/otel/metric/global -go.opentelemetry.io/otel/metric/instrument -go.opentelemetry.io/otel/metric/internal/global +go.opentelemetry.io/otel/metric/number +go.opentelemetry.io/otel/metric/sdkapi +go.opentelemetry.io/otel/metric/unit # go.opentelemetry.io/otel/sdk v1.14.0 ## explicit; go 1.18 go.opentelemetry.io/otel/sdk/instrumentation @@ -1078,7 +1082,7 @@ go.opentelemetry.io/otel/sdk/trace/tracetest # go.opentelemetry.io/otel/trace v1.14.0 ## explicit; go 1.18 go.opentelemetry.io/otel/trace -# go.opentelemetry.io/proto/otlp v0.19.0 +# go.opentelemetry.io/proto/otlp v0.19.0 => go.opentelemetry.io/proto/otlp v0.12.0 ## explicit; go 1.14 go.opentelemetry.io/proto/otlp/collector/trace/v1 go.opentelemetry.io/proto/otlp/common/v1 @@ -1241,7 +1245,7 @@ google.golang.org/genproto/googleapis/rpc/code google.golang.org/genproto/googleapis/rpc/errdetails google.golang.org/genproto/googleapis/rpc/status google.golang.org/genproto/protobuf/field_mask -# google.golang.org/grpc v1.53.0 +# google.golang.org/grpc v1.53.0 => google.golang.org/grpc v1.50.1 ## explicit; go 1.17 google.golang.org/grpc google.golang.org/grpc/attributes @@ -1371,3 +1375,11 @@ k8s.io/klog/v2/internal/severity # resenje.org/singleflight v0.3.0 ## explicit; go 1.18 resenje.org/singleflight +# go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc => go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.29.0 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace => go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.4.1 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc => go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.4.1 +# go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp => go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.4.1 +# go.opentelemetry.io/otel/internal/metric => go.opentelemetry.io/otel/internal/metric v0.27.0 +# go.opentelemetry.io/otel/metric => go.opentelemetry.io/otel/metric v0.27.0 +# go.opentelemetry.io/proto/otlp => go.opentelemetry.io/proto/otlp v0.12.0 +# google.golang.org/grpc => google.golang.org/grpc v1.50.1