Propagate trace contexts to shims

This adds trace context propagation over the grpc/ttrpc calls to a shim.

It also adds the otlp plugin to the runc shim so that it will send
traces to the configured tracer (which is inherited from containerd's
config).
It doesn't look like this is adding any real overhead to the runc shim's
memory usage, however it does add 2MB to the binary size.
As such this is gated by a build tag `shim_tracing`

Signed-off-by: Brian Goff <cpuguy83@gmail.com>
This commit is contained in:
Brian Goff 2024-05-07 18:24:03 +00:00
parent 03db11c3f2
commit 17d4a1357e
24 changed files with 2865 additions and 5 deletions

View File

@ -0,0 +1,21 @@
//go:build shim_tracing
/*
Copyright The containerd 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 main
import _ "github.com/containerd/containerd/v2/pkg/tracing/plugin"

View File

@ -104,6 +104,7 @@ func newCommand(ctx context.Context, id, containerdAddress, containerdTTRPCAddre
cmd := exec.Command(self, args...) cmd := exec.Command(self, args...)
cmd.Dir = cwd cmd.Dir = cwd
cmd.Env = append(os.Environ(), "GOMAXPROCS=4") cmd.Env = append(os.Environ(), "GOMAXPROCS=4")
cmd.Env = append(cmd.Env, "OTEL_SERVICE_NAME=containerd-shim-"+id)
cmd.SysProcAttr = &syscall.SysProcAttr{ cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true, Setpgid: true,
} }

View File

@ -26,6 +26,7 @@ import (
srvconfig "github.com/containerd/containerd/v2/cmd/containerd/server/config" srvconfig "github.com/containerd/containerd/v2/cmd/containerd/server/config"
"github.com/containerd/containerd/v2/pkg/sys" "github.com/containerd/containerd/v2/pkg/sys"
"github.com/containerd/log" "github.com/containerd/log"
"github.com/containerd/otelttrpc"
"github.com/containerd/ttrpc" "github.com/containerd/ttrpc"
specs "github.com/opencontainers/runtime-spec/specs-go" specs "github.com/opencontainers/runtime-spec/specs-go"
) )
@ -66,5 +67,8 @@ func apply(ctx context.Context, config *srvconfig.Config) error {
} }
func newTTRPCServer() (*ttrpc.Server, error) { func newTTRPCServer() (*ttrpc.Server, error) {
return ttrpc.NewServer(ttrpc.WithServerHandshaker(ttrpc.UnixSocketRequireSameUser())) return ttrpc.NewServer(
ttrpc.WithServerHandshaker(ttrpc.UnixSocketRequireSameUser()),
ttrpc.WithUnaryServerInterceptor(otelttrpc.UnaryServerInterceptor()),
)
} }

View File

@ -20,6 +20,7 @@ import (
"context" "context"
srvconfig "github.com/containerd/containerd/v2/cmd/containerd/server/config" srvconfig "github.com/containerd/containerd/v2/cmd/containerd/server/config"
"github.com/containerd/otelttrpc"
"github.com/containerd/ttrpc" "github.com/containerd/ttrpc"
) )
@ -28,5 +29,7 @@ func apply(_ context.Context, _ *srvconfig.Config) error {
} }
func newTTRPCServer() (*ttrpc.Server, error) { func newTTRPCServer() (*ttrpc.Server, error) {
return ttrpc.NewServer() return ttrpc.NewServer(
ttrpc.WithUnaryServerInterceptor(otelttrpc.UnaryServerInterceptor()),
)
} }

View File

@ -28,6 +28,7 @@ import (
"strings" "strings"
"time" "time"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/connectivity" "google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/credentials/insecure"
@ -46,6 +47,7 @@ import (
"github.com/containerd/containerd/v2/pkg/timeout" "github.com/containerd/containerd/v2/pkg/timeout"
"github.com/containerd/errdefs" "github.com/containerd/errdefs"
"github.com/containerd/log" "github.com/containerd/log"
"github.com/containerd/otelttrpc"
"github.com/containerd/ttrpc" "github.com/containerd/ttrpc"
"github.com/containerd/typeurl/v2" "github.com/containerd/typeurl/v2"
) )
@ -273,10 +275,16 @@ func makeConnection(ctx context.Context, id string, params client.BootstrapParam
} }
}() }()
return ttrpc.NewClient(conn, ttrpc.WithOnClose(onClose)), nil return ttrpc.NewClient(
conn,
ttrpc.WithOnClose(onClose),
ttrpc.WithUnaryClientInterceptor(otelttrpc.UnaryClientInterceptor()),
), nil
case "grpc": case "grpc":
gopts := []grpc.DialOption{ gopts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor()), //nolint:staticcheck // Ignore SA1019. Deprecation assumes use of [grpc.NewClient] but we are not using that here.
grpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor()), //nolint:staticcheck // Ignore SA1019. Deprecation assumes use of [grpc.NewClient] but we are not using that here.
} }
return grpcDialContext(params.Address, onClose, gopts...) return grpcDialContext(params.Address, onClose, gopts...)
default: default:

1
go.mod
View File

@ -22,6 +22,7 @@ require (
github.com/containerd/imgcrypt v1.2.0-rc1 github.com/containerd/imgcrypt v1.2.0-rc1
github.com/containerd/log v0.1.0 github.com/containerd/log v0.1.0
github.com/containerd/nri v0.6.1 github.com/containerd/nri v0.6.1
github.com/containerd/otelttrpc v0.0.0-20240305015340-ea5083fda723
github.com/containerd/platforms v0.2.1 github.com/containerd/platforms v0.2.1
github.com/containerd/plugin v0.1.0 github.com/containerd/plugin v0.1.0
github.com/containerd/ttrpc v1.2.5 github.com/containerd/ttrpc v1.2.5

1415
go.sum

File diff suppressed because it is too large Load Diff

View File

@ -43,8 +43,20 @@ type item struct {
count int count int
} }
type publisherConfig struct {
ttrpcOpts []ttrpc.ClientOpts
}
type PublisherOpts func(*publisherConfig)
func WithPublishTTRPCOpts(opts ...ttrpc.ClientOpts) PublisherOpts {
return func(cfg *publisherConfig) {
cfg.ttrpcOpts = append(cfg.ttrpcOpts, opts...)
}
}
// NewPublisher creates a new remote events publisher // NewPublisher creates a new remote events publisher
func NewPublisher(address string) (*RemoteEventsPublisher, error) { func NewPublisher(address string, opts ...PublisherOpts) (*RemoteEventsPublisher, error) {
client, err := ttrpcutil.NewClient(address) client, err := ttrpcutil.NewClient(address)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -43,6 +43,7 @@ import (
"github.com/containerd/containerd/v2/plugins" "github.com/containerd/containerd/v2/plugins"
"github.com/containerd/containerd/v2/version" "github.com/containerd/containerd/v2/version"
"github.com/containerd/log" "github.com/containerd/log"
"github.com/containerd/otelttrpc"
"github.com/containerd/plugin" "github.com/containerd/plugin"
"github.com/containerd/plugin/registry" "github.com/containerd/plugin/registry"
"github.com/containerd/ttrpc" "github.com/containerd/ttrpc"
@ -248,7 +249,9 @@ func run(ctx context.Context, manager Manager, config Config) error {
} }
ttrpcAddress := os.Getenv(ttrpcAddressEnv) ttrpcAddress := os.Getenv(ttrpcAddressEnv)
publisher, err := NewPublisher(ttrpcAddress) publisher, err := NewPublisher(ttrpcAddress, WithPublishTTRPCOpts(
ttrpc.WithUnaryClientInterceptor(otelttrpc.UnaryClientInterceptor()),
))
if err != nil { if err != nil {
return err return err
} }
@ -398,6 +401,8 @@ func run(ctx context.Context, manager Manager, config Config) error {
return fmt.Errorf("required that ttrpc service") return fmt.Errorf("required that ttrpc service")
} }
ttrpcUnaryInterceptors = append(ttrpcUnaryInterceptors, otelttrpc.UnaryServerInterceptor())
unaryInterceptor := chainUnaryServerInterceptors(ttrpcUnaryInterceptors...) unaryInterceptor := chainUnaryServerInterceptors(ttrpcUnaryInterceptors...)
server, err := newServer(ttrpc.WithUnaryServerInterceptor(unaryInterceptor)) server, err := newServer(ttrpc.WithUnaryServerInterceptor(unaryInterceptor))
if err != nil { if err != nil {

View File

@ -203,6 +203,9 @@ func newTracer(ctx context.Context, procs []trace.SpanProcessor) (io.Closer, err
} }
func warnTraceConfig(ic *plugin.InitContext) error { func warnTraceConfig(ic *plugin.InitContext) error {
if ic.Config == nil {
return nil
}
ctx := ic.Context ctx := ic.Context
cfg := ic.Config.(*TraceConfig) cfg := ic.Config.(*TraceConfig)
var warn bool var warn bool
@ -227,6 +230,9 @@ func warnTraceConfig(ic *plugin.InitContext) error {
} }
func warnOTLPConfig(ic *plugin.InitContext) error { func warnOTLPConfig(ic *plugin.InitContext) error {
if ic.Config == nil {
return nil
}
ctx := ic.Context ctx := ic.Context
cfg := ic.Config.(*OTLPConfig) cfg := ic.Config.(*OTLPConfig)
var warn bool var warn bool

13
vendor/github.com/containerd/otelttrpc/.gitignore generated vendored Normal file
View File

@ -0,0 +1,13 @@
# Binaries for programs and plugins
/bin/
*.exe
*.dll
*.so
*.dylib
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
coverage.txt

201
vendor/github.com/containerd/otelttrpc/LICENSE generated vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

126
vendor/github.com/containerd/otelttrpc/Makefile generated vendored Normal file
View File

@ -0,0 +1,126 @@
# Copyright The containerd 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.
# Default commands and binaries used for builds, testing, etc.
GO ?= go
GOTEST ?= $(GO) test
GOBUILD ?= $(GO) build ${DEBUG_GO_GCFLAGS} ${GO_GCFLAGS} ${GO_BUILD_FLAGS} ${EXTRA_FLAGS}
GOINSTALL ?= $(GO) install
INSTALL ?= install
# Go build tags.
ifdef BUILDTAGS
GO_BUILDTAGS = ${BUILDTAGS}
endif
GO_BUILDTAGS ?=
GO_TAGS = $(if $(GO_BUILDTAGS),-tags "$(strip $(GO_BUILDTAGS))",)
# Go build and test flags.
GO_BUILD_FLAGS =
TESTFLAGS_RACE =
TESTFLAGS ?= $(TESTFLAGS_RACE) $(EXTRA_TESTFLAGS)
TESTFLAGS_PARALLEL ?= 8
# See Golang issue re: '-trimpath': https://github.com/golang/go/issues/13809
GOPATHS = $(shell echo ${GOPATH} | tr ":" "\n" | tr ";" "\n")
GO_GCFLAGS= $(shell \
set -- ${GOPATHS}; \
echo "-gcflags=-trimpath=$${1}/src";)
# Project packages.
PACKAGES ?= $(shell \
$(GO) list ${GO_TAGS} ./... | \
grep -v /example)
# Packages to $(GOTEST).
TESTPACKAGES ?= $(shell \
$(GO) list ${GO_TAGS} ./... | \
grep -v /cmd | grep -v /integration | grep -v /example)
define BUILD_BINARY
$(call WHALE_TARGET); \
$(GOBUILD) -o $@ ${GO_TAGS} ./$<
endef
SUBPACKAGES ?= $(shell \
find . -name go.mod | tr -s ' ' '\n' | \
grep -v '\./go.mod' | grep -v /example | \
sed 's:/go.mod::g')
define WHALE_TARGET
$(if $(SUBPKG),echo "$(WHALE) $@ $(SUBPKG)",echo "$(WHALE) $@")
endef
WHALE := "🇩"
ONI := "👹"
# Do quiet builds by default. Override with V=1 or Q=
ifeq ($(V),1)
Q =
else
Q = @
endif
all: build
showvar:
$(Q)echo $(VAR)=$($(VAR))
lint: ## run all linters
$(Q)echo "$(WHALE) $@"; \
GOGC=75 golangci-lint run;
build: ## build the go packages
$(Q)echo "$(WHALE) $@"; \
$(GOBUILD) -v ${PACKAGES};
test: ## run tests
$(Q)echo "$(WHALE) $@"; \
$(GOTEST) ${TESTFLAGS} ${TESTPACKAGES};
coverage: ## generate coverprofiles from the unit tests, except tests that require root
$(Q)echo "$(WHALE) $@"; \
rm -f coverage.txt; \
$(GOTEST) ${TESTFLAGS} ${TESTPACKAGES} 2> /dev/null; \
for pkg in ${PACKAGES}; do \
$(GOTEST) ${TESTFLAGS} \
-cover \
-coverprofile=profile.out \
-covermode=atomic $$pkg || exit; \
if [ -f profile.out ]; then \
cat profile.out >> coverage.txt.raw; \
rm profile.out; \
fi; \
done; \
sort -u coverage.txt.raw > coverage.txt; \
rm coverage.txt.raw;
vendor: ## ensure that all the go.mod/go.sum files are up-to-date
$(Q)echo "$(WHALE) $@"; \
$(GO) mod tidy && \
$(GO) mod verify
verify-vendor: vendor ## verify if all the go.mod/go.sum files are up-to-date
$(Q)echo "$(WHALE) $@"; \
test -z "$$(git status --short | grep "go.sum" | tee /dev/stderr)" || \
((git diff | cat) && \
(echo "$(ONI) make sure to checkin changes after go mod tidy" && false))
help: ## this help
$(Q)awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST) | sort
.PHONY: lint build test coverage vendor verify-vendor help
.DEFAULT: default

61
vendor/github.com/containerd/otelttrpc/README.md generated vendored Normal file
View File

@ -0,0 +1,61 @@
# ttrpc OpenTelemetry Instrumentation
This golang package implements OpenTelemetry instrumentation support for
ttrpc. It can be used to automatically generate OpenTelemetry trace spans
for RPC methods called on the ttrpc client side and served on the ttrpc
server side.
# Usage
Instrumentation is provided by two interceptors, one to enable instrumentation
for unary clients and another for enabling instrumentation for unary servers.
These interceptors can be passed as ttrpc.ClientOpts and ttrpc.ServerOpt to
ttrpc during client and server creation with code like this:
```golang
import (
"github.com/containerd/ttrpc"
"github.com/containerd/otelttrpc"
)
// on the client side
...
client := ttrpc.NewClient(
conn,
ttrpc.UnaryClientInterceptor(
otelttrpc.UnaryClientInterceptor(),
),
)
// and on the server side
...
server, err := ttrpc.NewServer(
ttrpc.WithUnaryServerInterceptor(
otelttrpc.UnaryServerInterceptor(),
),
)
```
Once enabled, the interceptors generate trace Spans for all called and served
unary method calls. If the rest of the code is properly set up to collect and
export tracing data to opentelemetry, these spans should show up as part of
the collected traces.
For a more complete example see the [sample client](example/client/main.go)
and the [sample server](example/server/main.go) code.
# Limitations
Currently only unary client and unary server methods can be instrumented.
Support for streaming interfaces is yet to be implemented.
# Project details
otelttrpc is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE).
As a containerd sub-project, you will find the:
* [Project governance](https://github.com/containerd/project/blob/main/GOVERNANCE.md),
* [Maintainers](https://github.com/containerd/project/blob/main/MAINTAINERS),
* and [Contributing guidelines](https://github.com/containerd/project/blob/main/CONTRIBUTING.md)
information in our [`containerd/project`](https://github.com/containerd/project) repository.

175
vendor/github.com/containerd/otelttrpc/config.go generated vendored Normal file
View File

@ -0,0 +1,175 @@
/*
Copyright The containerd 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.
*/
/*
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 otelttrpc
import (
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/propagation"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
"go.opentelemetry.io/otel/trace"
)
const (
// instrumentationName is the name of this instrumentation package.
instrumentationName = "github.com/containerd/otelttrpc"
// TTRPCStatusCodeKey is convention for numeric status code of a ttRPC request.
TTRPCStatusCodeKey = attribute.Key("rpc.ttrpc.status_code")
)
// config is a group of options for this instrumentation.
type config struct {
Propagators propagation.TextMapPropagator
TracerProvider trace.TracerProvider
MeterProvider metric.MeterProvider
ReceivedEvent bool
SentEvent bool
meter metric.Meter
rpcServerDuration metric.Int64Histogram
}
// Option applies an option value for a config.
type Option interface {
apply(*config)
}
// newConfig returns a config configured with all the passed Options.
func newConfig(opts []Option) *config {
c := &config{
Propagators: otel.GetTextMapPropagator(),
TracerProvider: otel.GetTracerProvider(),
MeterProvider: otel.GetMeterProvider(),
}
for _, o := range opts {
o.apply(c)
}
var err error
c.meter = c.MeterProvider.Meter(
instrumentationName,
metric.WithInstrumentationVersion(Version()),
metric.WithSchemaURL(semconv.SchemaURL),
)
if c.rpcServerDuration, err = c.meter.Int64Histogram(
"rpc.server.duration",
metric.WithUnit("ms"),
); err != nil {
otel.Handle(err)
}
return c
}
type propagatorsOption struct{ p propagation.TextMapPropagator }
func (o propagatorsOption) apply(c *config) {
if o.p != nil {
c.Propagators = o.p
}
}
// WithPropagators returns an Option for setting the Propagators used
// to inject and extract trace context from requests. If this option
// is not provided the global TextMapPropagator will be used.
func WithPropagators(p propagation.TextMapPropagator) Option {
return propagatorsOption{p: p}
}
type tracerProviderOption struct{ tp trace.TracerProvider }
func (o tracerProviderOption) apply(c *config) {
if o.tp != nil {
c.TracerProvider = o.tp
}
}
// WithTracerProvider returns an Option for setting the TracerProvider
// for creating a Tracer. If this option is not provided the global
// TracerProvider will be used.
func WithTracerProvider(tp trace.TracerProvider) Option {
return tracerProviderOption{tp: tp}
}
type meterProviderOption struct{ mp metric.MeterProvider }
func (o meterProviderOption) apply(c *config) {
if o.mp != nil {
c.MeterProvider = o.mp
}
}
// WithMeterProvider returns an Option for setting the MeterProvider
// when creating a Meter. If this option is not provided the global
// MeterProvider will be used.
func WithMeterProvider(mp metric.MeterProvider) Option {
return meterProviderOption{mp: mp}
}
// Event type that can be recorded, see WithMessageEvents.
type Event int
// Different types of events that can be recorded, see WithMessageEvents.
const (
ReceivedEvents Event = iota
SentEvents
)
type messageEventsProviderOption struct {
events []Event
}
func (m messageEventsProviderOption) apply(c *config) {
for _, e := range m.events {
switch e {
case ReceivedEvents:
c.ReceivedEvent = true
case SentEvents:
c.SentEvent = true
}
}
}
// WithMessageEvents configures the interceptors to record the specified
// events (span.AddEvent) on spans. By default only summary attributes
// are added at the end of the request.
//
// Valid events are:
// - ReceivedEvents: Record an event for every message received.
// - SentEvents: Record an event for every message sent.
func WithMessageEvents(events ...Event) Option {
return messageEventsProviderOption{events: events}
}

27
vendor/github.com/containerd/otelttrpc/doc.go generated vendored Normal file
View File

@ -0,0 +1,27 @@
/*
Copyright The containerd 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 otelttrpc implements Opentelemetry instrumentation support for ttRPC.
The package implements unary client and server interceptors for opentelemetry
tracing instrumentation. The interceptors can be passed as ttrpc.ClientOpts
and ttrpc.ServerOpt to ttRPC during client and server creation. The interceptors
then automatically handle generating trace spans for all called and served
unary method calls. If the rest of the code is properly set up to collect and
export tracing data to opentelemetry, these spans should show up as part of the
collected traces.
*/
package otelttrpc

255
vendor/github.com/containerd/otelttrpc/interceptor.go generated vendored Normal file
View File

@ -0,0 +1,255 @@
/*
Copyright The containerd 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.
*/
/*
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 otelttrpc
import (
"context"
"net"
"strconv"
"time"
"github.com/containerd/ttrpc"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
"go.opentelemetry.io/otel/trace"
grpc_codes "google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/containerd/otelttrpc/internal"
)
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{}) {
span := trace.SpanFromContext(ctx)
if !span.IsRecording() {
return
}
span.AddEvent("message", trace.WithAttributes(
attribute.KeyValue(m),
RPCMessageIDKey.Int(id),
))
}
var (
messageSent = messageType(RPCMessageTypeSent)
messageReceived = messageType(RPCMessageTypeReceived)
)
// UnaryClientInterceptor returns a ttrpc.UnaryClientInterceptor suitable
// for use in a ttrpc.NewClient call.
func UnaryClientInterceptor(opts ...Option) ttrpc.UnaryClientInterceptor {
cfg := newConfig(opts)
tracer := cfg.TracerProvider.Tracer(
instrumentationName,
trace.WithInstrumentationVersion(Version()),
)
return func(
ctx context.Context,
req *ttrpc.Request, reply *ttrpc.Response,
info *ttrpc.UnaryClientInfo,
invoker ttrpc.Invoker,
) error {
name, attr := spanInfo(info.FullMethod, peerFromCtx(ctx))
var span trace.Span
ctx, span = tracer.Start(
ctx,
name,
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(attr...),
)
defer span.End()
ctx = inject(ctx, cfg.Propagators, req)
if cfg.SentEvent {
messageSent.Event(ctx, 1, req)
}
err := invoker(ctx, req, reply)
if cfg.ReceivedEvent {
messageReceived.Event(ctx, 1, reply)
}
if err != nil {
s, _ := status.FromError(err)
span.SetStatus(codes.Error, s.Message())
span.SetAttributes(statusCodeAttr(s.Code()))
} else {
span.SetAttributes(statusCodeAttr(grpc_codes.OK))
}
return err
}
}
// UnaryServerInterceptor returns ttrpc.UnaryServerInterceptor suitable
// for use in a ttrpc.NewServer call.
func UnaryServerInterceptor(opts ...Option) ttrpc.UnaryServerInterceptor {
cfg := newConfig(opts)
tracer := cfg.TracerProvider.Tracer(
instrumentationName,
trace.WithInstrumentationVersion(Version()),
)
return func(
ctx context.Context,
unmarshal ttrpc.Unmarshaler, info *ttrpc.UnaryServerInfo, method ttrpc.Method) (interface{}, error) {
ctx = extract(ctx, cfg.Propagators)
name, attr := spanInfo(info.FullMethod, peerFromCtx(ctx))
ctx, span := tracer.Start(
trace.ContextWithRemoteSpanContext(ctx, trace.SpanContextFromContext(ctx)),
name,
trace.WithSpanKind(trace.SpanKindServer),
trace.WithAttributes(attr...),
)
defer span.End()
if cfg.ReceivedEvent {
messageReceived.Event(ctx, 1, nil)
}
var statusCode grpc_codes.Code
defer func(t time.Time) {
elapsedTime := time.Since(t) / time.Millisecond
attr = append(attr, TTRPCStatusCodeKey.Int64(int64(statusCode)))
o := metric.WithAttributes(attr...)
cfg.rpcServerDuration.Record(ctx, int64(elapsedTime), o)
}(time.Now())
resp, err := method(ctx, unmarshal)
if err != nil {
s, _ := status.FromError(err)
statusCode, msg := serverStatus(s)
span.SetStatus(statusCode, msg)
span.SetAttributes(statusCodeAttr(s.Code()))
if cfg.SentEvent {
messageSent.Event(ctx, 1, s.Proto())
}
} else {
statusCode = grpc_codes.OK
span.SetAttributes(statusCodeAttr(grpc_codes.OK))
if cfg.SentEvent {
messageSent.Event(ctx, 1, resp)
}
}
return resp, err
}
}
// spanInfo returns a span name and all appropriate attributes from the ttRPC
// method and peer address.
func spanInfo(fullMethod, peerAddress string) (string, []attribute.KeyValue) {
attrs := []attribute.KeyValue{RPCSystemTTRPC}
name, mAttrs := internal.ParseFullMethod(fullMethod)
attrs = append(attrs, mAttrs...)
attrs = append(attrs, peerAttr(peerAddress)...)
return name, attrs
}
// peerAttr returns attributes about the peer address.
func peerAttr(addr string) []attribute.KeyValue {
host, p, err := net.SplitHostPort(addr)
if err != nil {
return []attribute.KeyValue(nil)
}
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 attr
}
// peerFromCtx returns a peer address from a context, if one exists.
func peerFromCtx(_ context.Context) string {
// TODO(klihub): we can't get our peer address here now.
// One possiblity would be to have the client set it in
// the metadata in Call().
return ""
}
// statusCodeAttr returns status code attribute based on given RPC code.
func statusCodeAttr(c grpc_codes.Code) attribute.KeyValue {
return TTRPCStatusCodeKey.Int64(int64(c))
}
// serverStatus returns a span status code and message for a given RPC
// status code. It maps specific RPC status codes to a corresponding span
// status code and message. This function is intended for use on the server
// side of a RPC connection.
//
// If the RPC status code is Unknown, DeadlineExceeded, Unimplemented,
// Internal, Unavailable, or DataLoss, it returns a span status code of Error
// and the message from the RPC status. Otherwise, it returns a span status
// code of Unset and an empty message.
func serverStatus(rpcStatus *status.Status) (codes.Code, string) {
switch rpcStatus.Code() {
case grpc_codes.Unknown,
grpc_codes.DeadlineExceeded,
grpc_codes.Unimplemented,
grpc_codes.Internal,
grpc_codes.Unavailable,
grpc_codes.DataLoss:
return codes.Error, rpcStatus.Message()
default:
return codes.Unset, ""
}
}

View File

@ -0,0 +1,65 @@
/*
Copyright The containerd 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.
*/
/*
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 (
"strings"
"go.opentelemetry.io/otel/attribute"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
)
// ParseFullMethod returns a span name following the OpenTelemetry semantic
// conventions as well as all applicable span attribute.KeyValue attributes based
// on a ttRPC FullMethod.
func ParseFullMethod(fullMethod string) (string, []attribute.KeyValue) {
var (
attrs []attribute.KeyValue
name = strings.TrimLeft(fullMethod, "/")
)
service, method, ok := strings.Cut(name, "/")
if !ok {
// Invalid format, does not follow `/package.service/method`.
return name, attrs
}
if service != "" {
attrs = append(attrs, semconv.RPCService(service))
}
if method != "" {
attrs = append(attrs, semconv.RPCMethod(method))
}
return name, attrs
}

View File

@ -0,0 +1,235 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.1
// protoc v3.20.1
// source: github.com/containerd/ttrpc/test.proto
package internal
import (
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)
)
type TestPayload struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Foo string `protobuf:"bytes,1,opt,name=foo,proto3" json:"foo,omitempty"`
Deadline int64 `protobuf:"varint,2,opt,name=deadline,proto3" json:"deadline,omitempty"`
Metadata string `protobuf:"bytes,3,opt,name=metadata,proto3" json:"metadata,omitempty"`
}
func (x *TestPayload) Reset() {
*x = TestPayload{}
if protoimpl.UnsafeEnabled {
mi := &file_github_com_containerd_ttrpc_test_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *TestPayload) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*TestPayload) ProtoMessage() {}
func (x *TestPayload) ProtoReflect() protoreflect.Message {
mi := &file_github_com_containerd_ttrpc_test_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 TestPayload.ProtoReflect.Descriptor instead.
func (*TestPayload) Descriptor() ([]byte, []int) {
return file_github_com_containerd_ttrpc_test_proto_rawDescGZIP(), []int{0}
}
func (x *TestPayload) GetFoo() string {
if x != nil {
return x.Foo
}
return ""
}
func (x *TestPayload) GetDeadline() int64 {
if x != nil {
return x.Deadline
}
return 0
}
func (x *TestPayload) GetMetadata() string {
if x != nil {
return x.Metadata
}
return ""
}
type EchoPayload struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Seq int64 `protobuf:"varint,1,opt,name=seq,proto3" json:"seq,omitempty"`
Msg string `protobuf:"bytes,2,opt,name=msg,proto3" json:"msg,omitempty"`
}
func (x *EchoPayload) Reset() {
*x = EchoPayload{}
if protoimpl.UnsafeEnabled {
mi := &file_github_com_containerd_ttrpc_test_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *EchoPayload) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*EchoPayload) ProtoMessage() {}
func (x *EchoPayload) ProtoReflect() protoreflect.Message {
mi := &file_github_com_containerd_ttrpc_test_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 EchoPayload.ProtoReflect.Descriptor instead.
func (*EchoPayload) Descriptor() ([]byte, []int) {
return file_github_com_containerd_ttrpc_test_proto_rawDescGZIP(), []int{1}
}
func (x *EchoPayload) GetSeq() int64 {
if x != nil {
return x.Seq
}
return 0
}
func (x *EchoPayload) GetMsg() string {
if x != nil {
return x.Msg
}
return ""
}
var File_github_com_containerd_ttrpc_test_proto protoreflect.FileDescriptor
var file_github_com_containerd_ttrpc_test_proto_rawDesc = []byte{
0x0a, 0x26, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x6e,
0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2f, 0x74, 0x74, 0x72, 0x70, 0x63, 0x2f, 0x74, 0x65,
0x73, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x74, 0x74, 0x72, 0x70, 0x63, 0x22,
0x57, 0x0a, 0x0b, 0x54, 0x65, 0x73, 0x74, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x10,
0x0a, 0x03, 0x66, 0x6f, 0x6f, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x66, 0x6f, 0x6f,
0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x02, 0x20, 0x01,
0x28, 0x03, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x1a, 0x0a, 0x08,
0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08,
0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x22, 0x31, 0x0a, 0x0b, 0x45, 0x63, 0x68, 0x6f,
0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x73, 0x65, 0x71, 0x18, 0x01,
0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x73, 0x65, 0x71, 0x12, 0x10, 0x0a, 0x03, 0x6d, 0x73, 0x67,
0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6d, 0x73, 0x67, 0x42, 0x26, 0x5a, 0x24, 0x67,
0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69,
0x6e, 0x65, 0x72, 0x64, 0x2f, 0x74, 0x74, 0x72, 0x70, 0x63, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72,
0x6e, 0x61, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_github_com_containerd_ttrpc_test_proto_rawDescOnce sync.Once
file_github_com_containerd_ttrpc_test_proto_rawDescData = file_github_com_containerd_ttrpc_test_proto_rawDesc
)
func file_github_com_containerd_ttrpc_test_proto_rawDescGZIP() []byte {
file_github_com_containerd_ttrpc_test_proto_rawDescOnce.Do(func() {
file_github_com_containerd_ttrpc_test_proto_rawDescData = protoimpl.X.CompressGZIP(file_github_com_containerd_ttrpc_test_proto_rawDescData)
})
return file_github_com_containerd_ttrpc_test_proto_rawDescData
}
var file_github_com_containerd_ttrpc_test_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_github_com_containerd_ttrpc_test_proto_goTypes = []interface{}{
(*TestPayload)(nil), // 0: ttrpc.TestPayload
(*EchoPayload)(nil), // 1: ttrpc.EchoPayload
}
var file_github_com_containerd_ttrpc_test_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_github_com_containerd_ttrpc_test_proto_init() }
func file_github_com_containerd_ttrpc_test_proto_init() {
if File_github_com_containerd_ttrpc_test_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_github_com_containerd_ttrpc_test_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*TestPayload); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_github_com_containerd_ttrpc_test_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*EchoPayload); 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{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_github_com_containerd_ttrpc_test_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_github_com_containerd_ttrpc_test_proto_goTypes,
DependencyIndexes: file_github_com_containerd_ttrpc_test_proto_depIdxs,
MessageInfos: file_github_com_containerd_ttrpc_test_proto_msgTypes,
}.Build()
File_github_com_containerd_ttrpc_test_proto = out.File
file_github_com_containerd_ttrpc_test_proto_rawDesc = nil
file_github_com_containerd_ttrpc_test_proto_goTypes = nil
file_github_com_containerd_ttrpc_test_proto_depIdxs = nil
}

View File

@ -0,0 +1,16 @@
syntax = "proto3";
package ttrpc;
option go_package = "github.com/containerd/ttrpc/internal";
message TestPayload {
string foo = 1;
int64 deadline = 2;
string metadata = 3;
}
message EchoPayload {
int64 seq = 1;
string msg = 2;
}

View File

@ -0,0 +1,108 @@
/*
Copyright The containerd 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.
*/
/*
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 otelttrpc
import (
"context"
"github.com/containerd/ttrpc"
"go.opentelemetry.io/otel/propagation"
)
type metadataSupplier struct {
metadata *ttrpc.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
}
func inject(ctx context.Context, propagators propagation.TextMapPropagator, req *ttrpc.Request) context.Context {
md, ok := ttrpc.GetMetadata(ctx)
if !ok {
md = make(ttrpc.MD)
}
propagators.Inject(ctx, &metadataSupplier{
metadata: &md,
})
// keep non-conflicting metadata from req, update others from context
newMD := make([]*ttrpc.KeyValue, 0)
for _, kv := range req.Metadata {
if _, found := md.Get(kv.Key); !found {
newMD = append(newMD, kv)
}
}
for k, values := range md {
for _, v := range values {
newMD = append(newMD, &ttrpc.KeyValue{
Key: k,
Value: v,
})
}
}
req.Metadata = newMD
return ttrpc.WithMetadata(ctx, md)
}
func extract(ctx context.Context, propagators propagation.TextMapPropagator) context.Context {
md, ok := ttrpc.GetMetadata(ctx)
if !ok {
md = make(ttrpc.MD)
}
return propagators.Extract(ctx, &metadataSupplier{
metadata: &md,
})
}

60
vendor/github.com/containerd/otelttrpc/semconv.go generated vendored Normal file
View File

@ -0,0 +1,60 @@
/*
Copyright The containerd 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.
*/
/*
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 otelttrpc
import (
"go.opentelemetry.io/otel/attribute"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
)
// Semantic conventions for attribute keys for ttRPC.
const (
// Name of message transmitted or received.
RPCNameKey = attribute.Key("name")
// Type of message transmitted or received.
RPCMessageTypeKey = attribute.Key("message.type")
// Identifier of message transmitted or received.
RPCMessageIDKey = attribute.Key("message.id")
)
// Semantic conventions for common RPC attributes.
var (
// Semantic convention for ttRPC as the remoting system.
RPCSystemTTRPC = semconv.RPCSystemKey.String("ttrpc")
// Semantic conventions for RPC message types.
RPCMessageTypeSent = RPCMessageTypeKey.String("SENT")
RPCMessageTypeReceived = RPCMessageTypeKey.String("RECEIVED")
)

38
vendor/github.com/containerd/otelttrpc/version.go generated vendored Normal file
View File

@ -0,0 +1,38 @@
/*
Copyright The containerd 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.
*/
/*
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 otelttrpc
// Version is the current release version of the ttRPC instrumentation.
func Version() string {
return "0.0.0"
}

4
vendor/modules.txt vendored
View File

@ -174,6 +174,10 @@ github.com/containerd/nri/pkg/net/multiplex
github.com/containerd/nri/pkg/runtime-tools/generate github.com/containerd/nri/pkg/runtime-tools/generate
github.com/containerd/nri/pkg/stub github.com/containerd/nri/pkg/stub
github.com/containerd/nri/types/v1 github.com/containerd/nri/types/v1
# github.com/containerd/otelttrpc v0.0.0-20240305015340-ea5083fda723
## explicit; go 1.13
github.com/containerd/otelttrpc
github.com/containerd/otelttrpc/internal
# github.com/containerd/platforms v0.2.1 # github.com/containerd/platforms v0.2.1
## explicit; go 1.20 ## explicit; go 1.20
github.com/containerd/platforms github.com/containerd/platforms