pax_global_header00006660000000000000000000000064147400202750014513gustar00rootroot0000000000000052 comment=fa91cafe17adf59a0edc10650135dfd1dfb761c2 otelttrpc-0.1.0/000077500000000000000000000000001474002027500135315ustar00rootroot00000000000000otelttrpc-0.1.0/.github/000077500000000000000000000000001474002027500150715ustar00rootroot00000000000000otelttrpc-0.1.0/.github/dependabot.yml000066400000000000000000000006721474002027500177260ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "gomod" directories: - "/" - "/example" schedule: interval: "weekly" open-pull-requests-limit: 5 groups: otel: patterns: - "go.opentelemetry.io/*" golang-x: patterns: - "golang.org/x/*" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" open-pull-requests-limit: 5 otelttrpc-0.1.0/.github/workflows/000077500000000000000000000000001474002027500171265ustar00rootroot00000000000000otelttrpc-0.1.0/.github/workflows/ci.yaml000066400000000000000000000052021474002027500204040ustar00rootroot00000000000000name: CI on: push: branches: - main pull_request: branches: - main - "release-*" env: GO_VERSION: "1.22.x" WORKDIR: src/github.com/containers/otelttrpc permissions: contents: read pull-requests: read jobs: # # Project checks # project: name: Project Checks runs-on: ubuntu-22.04 timeout-minutes: 5 steps: - uses: actions/setup-go@3041bf56c941b39c61721a86cd11f3bb1338122a # v5.2.0 with: go-version: ${{ env.GO_VERSION }} - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: path: ${{ env.WORKDIR }} fetch-depth: 25 - uses: containerd/project-checks@434a07157608eeaa1d5c8d4dd506154204cd9401 # v1.1.0 with: working-directory: ${{ env.WORKDIR }} # # Linters # linters: name: Linters runs-on: ${{ matrix.os }} timeout-minutes: 10 strategy: matrix: os: [ ubuntu-latest, macos-latest, windows-latest ] steps: - name: Checkout code uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: path: ${{ env.WORKDIR }} - name: Setup golang toolchain uses: actions/setup-go@3041bf56c941b39c61721a86cd11f3bb1338122a # v5.2.0 with: go-version: ${{ env.GO_VERSION }} - name: Run golangci-lint uses: golangci/golangci-lint-action@971e284b6050e8a5849b72094c50ab08da042db8 # v6.1.1 with: version: v1.60.3 args: --timeout=10m skip-cache: true working-directory: ${{ env.WORKDIR }} # # Tests and other checks # tests: strategy: fail-fast: false matrix: os: [ ubuntu-latest, macos-latest, windows-latest ] name: Tests and other checks runs-on: ${{ matrix.os }} steps: - name: Checkout code uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: path: ${{ env.WORKDIR }} - name: Setup golang toolchain uses: actions/setup-go@3041bf56c941b39c61721a86cd11f3bb1338122a # v5.2.0 with: go-version: ${{ env.GO_VERSION }} - name: Verify go modules working-directory: ${{ env.WORKDIR }} run: | make verify-vendor - name: Run tests working-directory: ${{ env.WORKDIR }} run: | make test - name: Test build examples working-directory: ${{ env.WORKDIR }} run: | cd example make - name: Coverage working-directory: ${{ env.WORKDIR }} run: | make coverage TESTFLAGS_RACE=-raceotelttrpc-0.1.0/.gitignore000066400000000000000000000003141474002027500155170ustar00rootroot00000000000000# 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 otelttrpc-0.1.0/LICENSE000066400000000000000000000261351474002027500145450ustar00rootroot00000000000000 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. otelttrpc-0.1.0/Makefile000066400000000000000000000070231474002027500151730ustar00rootroot00000000000000# 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 otelttrpc-0.1.0/README.md000066400000000000000000000040511474002027500150100ustar00rootroot00000000000000# 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. otelttrpc-0.1.0/config.go000066400000000000000000000115551474002027500153340ustar00rootroot00000000000000/* 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} } otelttrpc-0.1.0/doc.go000066400000000000000000000022401474002027500146230ustar00rootroot00000000000000/* 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 otelttrpc-0.1.0/example/000077500000000000000000000000001474002027500151645ustar00rootroot00000000000000otelttrpc-0.1.0/example/Makefile000066400000000000000000000051521474002027500166270ustar00rootroot00000000000000# 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. GO_CMD := go GO_BUILD := $(GO_CMD) build PROTO_SOURCES := $(shell find . -name '*.proto' | grep -v /vendor/) PROTO_GOFILES := $(patsubst %.proto,%.pb.go,$(PROTO_SOURCES)) \ $(patsubst %.proto,%_ttrpc.pb.go,$(PROTO_SOURCES)) PROTO_INCLUDE := -I$(PWD):/usr/local/include:/usr/include PROTO_OPTIONS := --proto_path=. $(PROTO_INCLUDE) \ --go_opt=paths=source_relative --go_out=. \ --go-ttrpc_opt=paths=source_relative --go-ttrpc_out=. PROTO_COMPILE := PATH=$(PATH):$(shell go env GOPATH)/bin; protoc $(PROTO_OPTIONS) INSTALL_PROTOC := https://github.com/containerd/containerd/blob/main/script/setup/install-protobuf PROTOC_DEPS := google.golang.org/protobuf/cmd/protoc-gen-go@v1.28.0 TTRPC_PLUGIN := github.com/containerd/ttrpc/cmd/protoc-gen-go-ttrpc@74421d10189e8c118870d294c9f7f62db2d33ec1 WGET := wget BINARIES := example-client example-server ifneq ($(V),1) Q := @ endif # # top-level targets # all: build ## build example build: $(BINARIES) clean: $(Q)rm -f $(BINARIES) protos: $(PROTO_GOFILES) ## generate example API ttrpc bindings # # binary compilation targets # example-client: $(wildcard api/*.go config/*.go client/*.go) ## build example client $(Q)echo "Building $@..."; \ $(GO_BUILD) -o $@ ./client example-server: $(wildcard api/*.go config/*.go server/*.go) ## build example-server $(Q)echo "Building $@..."; \ $(GO_BUILD) -o $@ ./server # # proto generation targets # %.pb.go: %.proto $(Q)echo "Generating $@..."; \ $(PROTO_COMPILE) $< # # targets for installing dependencies # install-protoc install-protobuf: ## install protobuf compiler $(Q)$(WGET) $(INSTALL_PROTOC) && chmod a+x install-protobuf && ./install-protobuf install-protoc-dependencies: ## install protobuf compiler dependencies $(Q)$(GO_INSTALL) -mod=mod $(PROTOC_DEPS) install-ttrpc-plugin: ## install protobuf compiler ttrcp plugin $(Q)$(GO_INSTALL) -mod=mod $(TTRPC_PLUGIN) help: ## this help @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST) | sort otelttrpc-0.1.0/example/README.md000066400000000000000000000011611474002027500164420ustar00rootroot00000000000000# ttRPC Tracing Example Traces unary client and server calls via interceptors. ### Compile Example Client and Server ```sh make ``` ### Run server ```sh ./example-server ``` ### Run client ```sh ./example-client ``` ### Generate Protobuf Go and ttRPC bindings If you modify the example protobuf definitions (`api/hello-service.proto`), you need to regenerate the corresponding golang/ttRPC bindings. ```sh # Install protoc and its dependencies if you don't have them yet. make install-protoc install-protoc-dependencies install-ttrpc-plugin # Regenerate golang/ttRPC bindings, recompile client and server. make ``` otelttrpc-0.1.0/example/api/000077500000000000000000000000001474002027500157355ustar00rootroot00000000000000otelttrpc-0.1.0/example/api/hello-service.pb.go000066400000000000000000000166031474002027500214330ustar00rootroot00000000000000// 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. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.28.1 // protoc v3.20.1 // source: api/hello-service.proto package api 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 HelloRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Greeting string `protobuf:"bytes,1,opt,name=greeting,proto3" json:"greeting,omitempty"` } func (x *HelloRequest) Reset() { *x = HelloRequest{} if protoimpl.UnsafeEnabled { mi := &file_api_hello_service_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *HelloRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*HelloRequest) ProtoMessage() {} func (x *HelloRequest) ProtoReflect() protoreflect.Message { mi := &file_api_hello_service_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 HelloRequest.ProtoReflect.Descriptor instead. func (*HelloRequest) Descriptor() ([]byte, []int) { return file_api_hello_service_proto_rawDescGZIP(), []int{0} } func (x *HelloRequest) GetGreeting() string { if x != nil { return x.Greeting } return "" } type HelloResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Reply string `protobuf:"bytes,1,opt,name=reply,proto3" json:"reply,omitempty"` } func (x *HelloResponse) Reset() { *x = HelloResponse{} if protoimpl.UnsafeEnabled { mi := &file_api_hello_service_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *HelloResponse) String() string { return protoimpl.X.MessageStringOf(x) } func (*HelloResponse) ProtoMessage() {} func (x *HelloResponse) ProtoReflect() protoreflect.Message { mi := &file_api_hello_service_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 HelloResponse.ProtoReflect.Descriptor instead. func (*HelloResponse) Descriptor() ([]byte, []int) { return file_api_hello_service_proto_rawDescGZIP(), []int{1} } func (x *HelloResponse) GetReply() string { if x != nil { return x.Reply } return "" } var File_api_hello_service_proto protoreflect.FileDescriptor var file_api_hello_service_proto_rawDesc = []byte{ 0x0a, 0x17, 0x61, 0x70, 0x69, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2d, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x03, 0x61, 0x70, 0x69, 0x22, 0x2a, 0x0a, 0x0c, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x67, 0x72, 0x65, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x67, 0x72, 0x65, 0x65, 0x74, 0x69, 0x6e, 0x67, 0x22, 0x25, 0x0a, 0x0d, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x72, 0x65, 0x70, 0x6c, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x72, 0x65, 0x70, 0x6c, 0x79, 0x32, 0x41, 0x0a, 0x0c, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x31, 0x0a, 0x08, 0x53, 0x61, 0x79, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x12, 0x11, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x12, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x31, 0x5a, 0x2f, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2f, 0x6f, 0x74, 0x65, 0x6c, 0x74, 0x74, 0x72, 0x70, 0x63, 0x2f, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x3b, 0x61, 0x70, 0x69, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_api_hello_service_proto_rawDescOnce sync.Once file_api_hello_service_proto_rawDescData = file_api_hello_service_proto_rawDesc ) func file_api_hello_service_proto_rawDescGZIP() []byte { file_api_hello_service_proto_rawDescOnce.Do(func() { file_api_hello_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_api_hello_service_proto_rawDescData) }) return file_api_hello_service_proto_rawDescData } var file_api_hello_service_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_api_hello_service_proto_goTypes = []interface{}{ (*HelloRequest)(nil), // 0: api.HelloRequest (*HelloResponse)(nil), // 1: api.HelloResponse } var file_api_hello_service_proto_depIdxs = []int32{ 0, // 0: api.HelloService.SayHello:input_type -> api.HelloRequest 1, // 1: api.HelloService.SayHello:output_type -> api.HelloResponse 1, // [1:2] is the sub-list for method output_type 0, // [0:1] 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_api_hello_service_proto_init() } func file_api_hello_service_proto_init() { if File_api_hello_service_proto != nil { return } if !protoimpl.UnsafeEnabled { file_api_hello_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*HelloRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } file_api_hello_service_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*HelloResponse); 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_api_hello_service_proto_rawDesc, NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 1, }, GoTypes: file_api_hello_service_proto_goTypes, DependencyIndexes: file_api_hello_service_proto_depIdxs, MessageInfos: file_api_hello_service_proto_msgTypes, }.Build() File_api_hello_service_proto = out.File file_api_hello_service_proto_rawDesc = nil file_api_hello_service_proto_goTypes = nil file_api_hello_service_proto_depIdxs = nil } otelttrpc-0.1.0/example/api/hello-service.proto000066400000000000000000000015571474002027500215730ustar00rootroot00000000000000// 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. syntax = "proto3"; package api; option go_package = "github.com/containerd/otelttrpc/example/api;api"; service HelloService { rpc SayHello (HelloRequest) returns (HelloResponse); } message HelloRequest { string greeting = 1; } message HelloResponse { string reply = 1; } otelttrpc-0.1.0/example/api/hello-service_ttrpc.pb.go000066400000000000000000000021651474002027500226450ustar00rootroot00000000000000// Code generated by protoc-gen-go-ttrpc. DO NOT EDIT. // source: api/hello-service.proto package api import ( context "context" ttrpc "github.com/containerd/ttrpc" ) type HelloServiceService interface { SayHello(context.Context, *HelloRequest) (*HelloResponse, error) } func RegisterHelloServiceService(srv *ttrpc.Server, svc HelloServiceService) { srv.RegisterService("api.HelloService", &ttrpc.ServiceDesc{ Methods: map[string]ttrpc.Method{ "SayHello": func(ctx context.Context, unmarshal func(interface{}) error) (interface{}, error) { var req HelloRequest if err := unmarshal(&req); err != nil { return nil, err } return svc.SayHello(ctx, &req) }, }, }) } type helloServiceClient struct { client *ttrpc.Client } func NewHelloServiceClient(client *ttrpc.Client) HelloServiceService { return &helloServiceClient{ client: client, } } func (c *helloServiceClient) SayHello(ctx context.Context, req *HelloRequest) (*HelloResponse, error) { var resp HelloResponse if err := c.client.Call(ctx, "api.HelloService", "SayHello", req, &resp); err != nil { return nil, err } return &resp, nil } otelttrpc-0.1.0/example/client/000077500000000000000000000000001474002027500164425ustar00rootroot00000000000000otelttrpc-0.1.0/example/client/main.go000066400000000000000000000051461474002027500177230ustar00rootroot00000000000000/* 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 main import ( "context" "fmt" "log" "net" "time" "github.com/containerd/otelttrpc" "github.com/containerd/otelttrpc/example/api" "github.com/containerd/otelttrpc/example/config" "github.com/containerd/ttrpc" // "google.golang.org/grpc/metadata" ) func main() { tp, err := config.Init() if err != nil { log.Fatal(err) } defer func() { if err := tp.Shutdown(context.Background()); err != nil { log.Printf("Error shutting down tracer provider: %v", err) } }() var conn net.Conn conn, err = net.Dial("tcp", ":7777") if err != nil { log.Fatalf("failed to dial/connect: %v", err) } defer func() { _ = conn.Close() }() client := ttrpc.NewClient(conn, ttrpc.WithUnaryClientInterceptor( otelttrpc.UnaryClientInterceptor(), ), ) c := api.NewHelloServiceClient(client) for i := 0; i < 10; i++ { if err := callSayHello(c); err != nil { log.Fatal(err) } time.Sleep(250 * time.Millisecond) } time.Sleep(10 * time.Millisecond) } func callSayHello(c api.HelloServiceService) error { md := ttrpc.MD{} md.Set("timestamp", time.Now().Format(time.StampNano)) md.Set("client-id", "web-api-client-us-east-1") md.Set("user-id", "some-test-user-id") ctx := ttrpc.WithMetadata(context.Background(), md) response, err := c.SayHello(ctx, &api.HelloRequest{Greeting: "World"}) if err != nil { return fmt.Errorf("calling SayHello: %w", err) } log.Printf("Response from server: %s", response.Reply) return nil } otelttrpc-0.1.0/example/config/000077500000000000000000000000001474002027500164315ustar00rootroot00000000000000otelttrpc-0.1.0/example/config/config.go000066400000000000000000000035471474002027500202360ustar00rootroot00000000000000/* 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 config import ( "go.opentelemetry.io/otel" stdout "go.opentelemetry.io/otel/exporters/stdout/stdouttrace" "go.opentelemetry.io/otel/propagation" sdktrace "go.opentelemetry.io/otel/sdk/trace" ) // Init configures an OpenTelemetry exporter and trace provider. func Init() (*sdktrace.TracerProvider, error) { exporter, err := stdout.New(stdout.WithPrettyPrint()) if err != nil { return nil, err } tp := sdktrace.NewTracerProvider( sdktrace.WithSampler(sdktrace.AlwaysSample()), sdktrace.WithBatcher(exporter), ) otel.SetTracerProvider(tp) otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{})) return tp, nil } otelttrpc-0.1.0/example/go.mod000066400000000000000000000016551474002027500163010ustar00rootroot00000000000000module github.com/containerd/otelttrpc/example go 1.21 require ( github.com/containerd/otelttrpc v0.0.0-20240305015340-ea5083fda723 github.com/containerd/ttrpc v1.2.7 go.opentelemetry.io/otel v1.29.0 go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.29.0 go.opentelemetry.io/otel/sdk v1.29.0 go.opentelemetry.io/otel/trace v1.29.0 google.golang.org/protobuf v1.33.0 ) require ( github.com/containerd/log v0.1.0 // indirect github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/google/uuid v1.6.0 // indirect github.com/sirupsen/logrus v1.9.3 // indirect go.opentelemetry.io/otel/metric v1.29.0 // indirect golang.org/x/sys v0.28.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20230731190214-cbb8c96f2d6d // indirect google.golang.org/grpc v1.57.1 // indirect ) replace github.com/containerd/otelttrpc => ../ otelttrpc-0.1.0/example/go.sum000066400000000000000000000123221474002027500163170ustar00rootroot00000000000000github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= github.com/containerd/ttrpc v1.2.7 h1:qIrroQvuOL9HQ1X6KHe2ohc7p+HP/0VE6XPU7elJRqQ= github.com/containerd/ttrpc v1.2.7/go.mod h1:YCXHsb32f+Sq5/72xHubdiJRQY9inL4a4ZQrAbN1q9o= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4= github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw= go.opentelemetry.io/otel v1.29.0/go.mod h1:N/WtXPs1CNCUEx+Agz5uouwCba+i+bJGFicT8SR4NP8= go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.29.0 h1:X3ZjNp36/WlkSYx0ul2jw4PtbNEDDeLskw3VPsrpYM0= go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.29.0/go.mod h1:2uL/xnOXh0CHOBFCWXz5u1A4GXLiW+0IQIzVbeOEQ0U= go.opentelemetry.io/otel/metric v1.29.0 h1:vPf/HFWTNkPu1aYeIsc98l4ktOQaL6LeSoeV2g+8YLc= go.opentelemetry.io/otel/metric v1.29.0/go.mod h1:auu/QWieFVWx+DmQOUMgj0F8LHWdgalxXqvp7BII/W8= go.opentelemetry.io/otel/sdk v1.29.0 h1:vkqKjk7gwhS8VaWb0POZKmIEDimRCMsopNYnriHyryo= go.opentelemetry.io/otel/sdk v1.29.0/go.mod h1:pM8Dx5WKnvxLCb+8lG1PRNIDxu9g9b9g59Qr7hfAAok= go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt39JTi4= go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ= golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/genproto/googleapis/rpc v0.0.0-20230731190214-cbb8c96f2d6d h1:pgIUhmqwKOUlnKna4r6amKdUngdL8DrkpFeV8+VBElY= google.golang.org/genproto/googleapis/rpc v0.0.0-20230731190214-cbb8c96f2d6d/go.mod h1:TUfxEVdsvPg18p6AslUXFoLdpED4oBnGwyqk3dV1XzM= google.golang.org/grpc v1.57.1 h1:upNTNqv0ES+2ZOOqACwVtS3Il8M12/+Hz41RCPzAjQg= google.golang.org/grpc v1.57.1/go.mod h1:Sd+9RMTACXwmub0zcNY2c4arhtrbBYD1AUHI/dt16Mo= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= otelttrpc-0.1.0/example/server/000077500000000000000000000000001474002027500164725ustar00rootroot00000000000000otelttrpc-0.1.0/example/server/main.go000066400000000000000000000055021474002027500177470ustar00rootroot00000000000000/* 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 main import ( "context" "log" "net" "time" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" "github.com/containerd/otelttrpc" "github.com/containerd/otelttrpc/example/api" "github.com/containerd/otelttrpc/example/config" "github.com/containerd/ttrpc" ) const ( port = ":7777" ) var tracer = otel.Tracer("ttrpc-example") // server is used to implement api.HelloServiceService. type server struct { api.HelloServiceService } // SayHello implements api.HelloServiceServer. func (s *server) SayHello(ctx context.Context, in *api.HelloRequest) (*api.HelloResponse, error) { log.Printf("Received: %v\n", in.GetGreeting()) s.workHard(ctx) time.Sleep(50 * time.Millisecond) return &api.HelloResponse{Reply: "Hello " + in.Greeting}, nil } func (s *server) workHard(ctx context.Context) { _, span := tracer.Start(ctx, "workHard", trace.WithAttributes(attribute.String("extra.key", "extra.value"))) defer span.End() time.Sleep(50 * time.Millisecond) } func main() { tp, err := config.Init() if err != nil { log.Fatal(err) } defer func() { if err := tp.Shutdown(context.Background()); err != nil { log.Printf("Error shutting down tracer provider: %v", err) } }() lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } s, err := ttrpc.NewServer( ttrpc.WithUnaryServerInterceptor(otelttrpc.UnaryServerInterceptor()), ) if err != nil { log.Fatalf("failed to create ttRPC server: %v", err) } api.RegisterHelloServiceService(s, &server{}) if err := s.Serve(context.Background(), lis); err != nil { log.Fatalf("failed to serve: %v", err) } } otelttrpc-0.1.0/example_interceptor_test.go000066400000000000000000000027731474002027500212010ustar00rootroot00000000000000/* 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 ( "net" "github.com/containerd/ttrpc" ) func ExampleUnaryClientInterceptor() { var c net.Conn _ = ttrpc.NewClient(c, ttrpc.WithUnaryClientInterceptor(UnaryClientInterceptor())) } func ExampleUnaryServerInterceptor() { _, _ = ttrpc.NewServer(ttrpc.WithUnaryServerInterceptor(UnaryServerInterceptor())) } otelttrpc-0.1.0/go.mod000066400000000000000000000016051474002027500146410ustar00rootroot00000000000000module github.com/containerd/otelttrpc go 1.21 require ( github.com/containerd/ttrpc v1.2.7 github.com/stretchr/testify v1.10.0 go.opentelemetry.io/otel v1.29.0 go.opentelemetry.io/otel/metric v1.29.0 go.opentelemetry.io/otel/sdk v1.29.0 go.opentelemetry.io/otel/trace v1.29.0 google.golang.org/grpc v1.57.1 google.golang.org/protobuf v1.33.0 ) require ( github.com/containerd/log v0.1.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/go-logr/logr v1.4.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/golang/protobuf v1.5.3 // indirect github.com/google/uuid v1.6.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/sirupsen/logrus v1.9.3 // indirect golang.org/x/sys v0.24.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20230731190214-cbb8c96f2d6d // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) otelttrpc-0.1.0/go.sum000066400000000000000000000121241474002027500146640ustar00rootroot00000000000000github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= github.com/containerd/ttrpc v1.2.7 h1:qIrroQvuOL9HQ1X6KHe2ohc7p+HP/0VE6XPU7elJRqQ= github.com/containerd/ttrpc v1.2.7/go.mod h1:YCXHsb32f+Sq5/72xHubdiJRQY9inL4a4ZQrAbN1q9o= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4= github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw= go.opentelemetry.io/otel v1.29.0/go.mod h1:N/WtXPs1CNCUEx+Agz5uouwCba+i+bJGFicT8SR4NP8= go.opentelemetry.io/otel/metric v1.29.0 h1:vPf/HFWTNkPu1aYeIsc98l4ktOQaL6LeSoeV2g+8YLc= go.opentelemetry.io/otel/metric v1.29.0/go.mod h1:auu/QWieFVWx+DmQOUMgj0F8LHWdgalxXqvp7BII/W8= go.opentelemetry.io/otel/sdk v1.29.0 h1:vkqKjk7gwhS8VaWb0POZKmIEDimRCMsopNYnriHyryo= go.opentelemetry.io/otel/sdk v1.29.0/go.mod h1:pM8Dx5WKnvxLCb+8lG1PRNIDxu9g9b9g59Qr7hfAAok= go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt39JTi4= go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ= golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/genproto/googleapis/rpc v0.0.0-20230731190214-cbb8c96f2d6d h1:pgIUhmqwKOUlnKna4r6amKdUngdL8DrkpFeV8+VBElY= google.golang.org/genproto/googleapis/rpc v0.0.0-20230731190214-cbb8c96f2d6d/go.mod h1:TUfxEVdsvPg18p6AslUXFoLdpED4oBnGwyqk3dV1XzM= google.golang.org/grpc v1.57.1 h1:upNTNqv0ES+2ZOOqACwVtS3Il8M12/+Hz41RCPzAjQg= google.golang.org/grpc v1.57.1/go.mod h1:Sd+9RMTACXwmub0zcNY2c4arhtrbBYD1AUHI/dt16Mo= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= otelttrpc-0.1.0/interceptor.go000066400000000000000000000160371474002027500164250ustar00rootroot00000000000000/* 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, "" } } otelttrpc-0.1.0/interceptor_test.go000066400000000000000000000165131474002027500174630ustar00rootroot00000000000000/* 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" "runtime" "strings" "sync" "testing" "github.com/containerd/otelttrpc/internal" "github.com/containerd/ttrpc" "github.com/stretchr/testify/assert" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/propagation" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/sdk/trace/tracetest" "go.opentelemetry.io/otel/trace" ) const serviceName = "testService" // testingService is our prototype service definition for use in testing the full model. // // Typically, this is generated. We define it here to ensure that that package // primitive has what is required for generated code. type testingService interface { Test(ctx context.Context, req *internal.TestPayload) (*internal.TestPayload, error) } type testingClient struct { client *ttrpc.Client } func newTestingClient(client *ttrpc.Client) *testingClient { return &testingClient{ client: client, } } func (tc *testingClient) Test(ctx context.Context, req *internal.TestPayload) (*internal.TestPayload, error) { var tp internal.TestPayload return &tp, tc.client.Call(ctx, serviceName, "Test", req, &tp) } // testingServer is what would be implemented by the user of this package. type testingServer struct{} func (s *testingServer) Test(ctx context.Context, req *internal.TestPayload) (*internal.TestPayload, error) { tp := &internal.TestPayload{Foo: strings.Repeat(req.Foo, 2)} if dl, ok := ctx.Deadline(); ok { tp.Deadline = dl.UnixNano() } if v, ok := ttrpc.GetMetadataValue(ctx, "foo"); ok { tp.Metadata = v } return tp, nil } func TestClientCallServerConcurrent(t *testing.T) { var ( ctx = ttrpc.WithMetadata(context.Background(), ttrpc.MD{"test-key": []string{"test-val"}}) exp, tp = newTracerProvider() server = mustServer(t)(newServerWithTTRPCInterceptor(tp)) testImpl = &testingServer{} addr, listener = newTestListener(t) payload = &internal.TestPayload{ Foo: "bar", } ) concurrency := 30 testClients := make([]*testingClient, 0, concurrency) for i := 0; i < concurrency; i++ { client, cleanup := newTestClient(t, addr, tp) testClients = append(testClients, newTestingClient(client)) defer cleanup() } defer listener.Close() defer func() { _ = tp.Shutdown(ctx) }() registerTestingService(server, testImpl) go func() { _ = server.Serve(ctx, listener) }() defer func() { _ = server.Shutdown(ctx) }() var wg sync.WaitGroup var errs []error var mu sync.Mutex for _, testClient := range testClients { wg.Add(1) go func(tc *testingClient) { defer wg.Done() if _, err := tc.Test(ctx, payload); err != nil { mu.Lock() defer mu.Unlock() errs = append(errs, err) } }(testClient) } wg.Wait() if len(errs) > 0 { t.Fatalf("unexpected errors: %v", errs) } // get exported spans snapshots := exp.GetSpans().Snapshots() // we should capture `concurrency * 2` spans, one each from client and server side // TODO: validate individual spans and their attributes assert.Equal(t, concurrency*2, len(snapshots), "Number of spans mismatched") } func TestClientCallServer(t *testing.T) { var ( ctx = ttrpc.WithMetadata(context.Background(), ttrpc.MD{"test-key": []string{"test-val"}}) exp, tp = newTracerProvider() server = mustServer(t)(newServerWithTTRPCInterceptor(tp)) testImpl = &testingServer{} addr, listener = newTestListener(t) client, cleanup = newTestClient(t, addr, tp) testClient = newTestingClient(client) payload = &internal.TestPayload{ Foo: "bar", } ) defer listener.Close() defer cleanup() defer func() { _ = tp.Shutdown(ctx) }() registerTestingService(server, testImpl) go func() { _ = server.Serve(ctx, listener) }() defer func() { _ = server.Shutdown(ctx) }() _, err := testClient.Test(ctx, payload) if err != nil { t.Fatal(err) } // get exported spans snapshots := exp.GetSpans().Snapshots() // we should capture 2 spans, one each from client and server side // TODO: validate individual spans and their attributes assert.Equal(t, 2, len(snapshots), "Number of spans mismatched") } func newServerWithTTRPCInterceptor(tp trace.TracerProvider) (*ttrpc.Server, error) { serverOpt := ttrpc.WithUnaryServerInterceptor(UnaryServerInterceptor(WithTracerProvider(tp))) return ttrpc.NewServer(serverOpt) } func mustServer(t testing.TB) func(server *ttrpc.Server, err error) *ttrpc.Server { return func(server *ttrpc.Server, err error) *ttrpc.Server { t.Helper() if err != nil { t.Fatal(err) } return server } } // newTracerProvider creates in memory exporter and tracer provider to be // used as tracing test func newTracerProvider() (*tracetest.InMemoryExporter, *sdktrace.TracerProvider) { //create in memory exporter exp := tracetest.NewInMemoryExporter() //create tracer provider tp := sdktrace.NewTracerProvider( sdktrace.WithSyncer(exp), ) otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{})) return exp, tp } func newTestListener(t testing.TB) (string, net.Listener) { var prefix string // Abstracts sockets are only available on Linux. if runtime.GOOS == "linux" { prefix = "\x00" } addr := prefix + t.Name() listener, err := net.Listen("unix", addr) if err != nil { t.Fatal(err) } return addr, listener } func newTestClient(t testing.TB, addr string, tp *sdktrace.TracerProvider) (*ttrpc.Client, func()) { conn, err := net.Dial("unix", addr) if err != nil { t.Fatal(err) } client := ttrpc.NewClient(conn, ttrpc.WithUnaryClientInterceptor(UnaryClientInterceptor(WithTracerProvider(tp)))) return client, func() { conn.Close() client.Close() } } // registerTestingService mocks more of what is generated code. Unlike grpc, we // register with a closure so that the descriptor is allocated only on // registration. func registerTestingService(server *ttrpc.Server, service testingService) { server.Register(serviceName, map[string]ttrpc.Method{ "Test": func(ctx context.Context, unmarshal func(interface{}) error) (interface{}, error) { var req internal.TestPayload if err := unmarshal(&req); err != nil { return nil, err } return service.Test(ctx, &req) }, }) } otelttrpc-0.1.0/internal/000077500000000000000000000000001474002027500153455ustar00rootroot00000000000000otelttrpc-0.1.0/internal/parse.go000066400000000000000000000037011474002027500170070ustar00rootroot00000000000000/* 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 } otelttrpc-0.1.0/internal/test.pb.go000066400000000000000000000171251474002027500172610ustar00rootroot00000000000000// 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 } otelttrpc-0.1.0/internal/test.proto000066400000000000000000000003571474002027500174160ustar00rootroot00000000000000syntax = "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; } otelttrpc-0.1.0/metadata_supplier.go000066400000000000000000000055061474002027500175710ustar00rootroot00000000000000/* 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) } else { // make a copy to avoid concurrent read/write panic md = md.Clone() } 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, }) } otelttrpc-0.1.0/semconv.go000066400000000000000000000037201474002027500155340ustar00rootroot00000000000000/* 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") ) otelttrpc-0.1.0/version.go000066400000000000000000000024571474002027500155550ustar00rootroot00000000000000/* 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" }