1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
|
/*
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)
},
})
}
|