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
package main

import (
	"context"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"

	"go.opentelemetry.io/otel/trace"
)

// TestOTLPJSONShape drives a real tracer provider through the exporter and
// checks the bytes that go on the wire.
//
// This is the test that justifies hand-writing the exporter instead of pulling
// in otlptracehttp (and with it grpc, genproto and grpc-gateway): if the JSON
// shape is right, the dependency is unnecessary.
func TestOTLPJSONShape(t *testing.T) {
	var captured []byte
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if got := r.Header.Get("Content-Type"); got != "application/json" {
			t.Errorf("Content-Type = %q, want application/json", got)
		}
		b, _ := io.ReadAll(r.Body)
		captured = b
		w.WriteHeader(http.StatusOK)
	}))
	defer srv.Close()

	t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", srv.URL)
	t.Setenv("OTEL_SERVICE_NAME", "whatcd-resolver-test")
	os.Unsetenv("WHATCD_RESOLVER_DISABLE_TRACING")

	ctx := context.Background()
	shutdown, err := initTracing(ctx)
	if err != nil {
		t.Fatal(err)
	}

	err = inSpan(ctx, "outer", func(ctx context.Context, span trace.Span) error {
		attr(span, "artist-redacted-id", 2785)
		attr(span, "artist.name", "Kirinji")
		event(span, "did a thing")
		return inSpan(ctx, "inner", func(ctx context.Context, span trace.Span) error {
			attr(span, "nested", true)
			return nil
		})
	})
	if err != nil {
		t.Fatal(err)
	}

	// Flush.
	if err := shutdown(ctx); err != nil {
		t.Fatal(err)
	}
	if captured == nil {
		t.Fatal("exporter never posted anything")
	}

	// Optionally dump the exact wire bytes so they can be replayed against a
	// real collector (see the manpage, section TRACING).
	if dst := os.Getenv("WHATCD_RESOLVER_OTLP_DUMP"); dst != "" {
		if err := os.WriteFile(dst, captured, 0o644); err != nil {
			t.Fatal(err)
		}
	}

	var payload otlpPayload
	if err := json.Unmarshal(captured, &payload); err != nil {
		t.Fatalf("payload is not valid JSON: %v\n%s", err, captured)
	}
	if len(payload.ResourceSpans) != 1 {
		t.Fatalf("got %d resourceSpans, want 1", len(payload.ResourceSpans))
	}
	rs := payload.ResourceSpans[0]

	// service.name must be on the resource, otherwise Jaeger files the trace
	// under "unknown_service".
	var svc string
	for _, a := range rs.Resource.Attributes {
		if a.Key == "service.name" && a.Value.StringValue != nil {
			svc = *a.Value.StringValue
		}
	}
	if svc != "whatcd-resolver-test" {
		t.Errorf("service.name = %q, want whatcd-resolver-test", svc)
	}

	spans := map[string]otlpSpan{}
	for _, ss := range rs.ScopeSpans {
		for _, s := range ss.Spans {
			spans[s.Name] = s
		}
	}
	outer, ok := spans["outer"]
	if !ok {
		t.Fatalf("no span named outer, got %v", spans)
	}
	inner, ok := spans["inner"]
	if !ok {
		t.Fatalf("no span named inner, got %v", spans)
	}

	// IDs must be hex of the right length, timestamps decimal strings.
	if len(outer.TraceID) != 32 {
		t.Errorf("traceId = %q, want 32 hex chars", outer.TraceID)
	}
	if len(outer.SpanID) != 16 {
		t.Errorf("spanId = %q, want 16 hex chars", outer.SpanID)
	}
	if outer.StartTimeUnixNano == "" || outer.EndTimeUnixNano == "" {
		t.Error("timestamps must be set")
	}

	// Parent/child linkage is what makes the trace a tree in the UI.
	if inner.ParentSpanID != outer.SpanID {
		t.Errorf("inner.parentSpanId = %q, want outer.spanId %q", inner.ParentSpanID, outer.SpanID)
	}
	if inner.TraceID != outer.TraceID {
		t.Error("inner and outer must share a traceId")
	}

	// Attributes keep the "_." prefix the Haskell version used.
	attrs := map[string]otlpValue{}
	for _, a := range outer.Attributes {
		attrs[a.Key] = a.Value
	}
	if v, ok := attrs["_.artist-redacted-id"]; !ok {
		t.Errorf("missing _.artist-redacted-id, have %v", attrs)
	} else if v.IntValue == nil || *v.IntValue != "2785" {
		// int64 must be a *string* in OTLP JSON, not a number.
		t.Errorf("_.artist-redacted-id = %+v, want intValue \"2785\"", v)
	}
	if v, ok := attrs["_.artist.name"]; !ok || v.StringValue == nil || *v.StringValue != "Kirinji" {
		t.Errorf("_.artist.name = %+v, want stringValue Kirinji", v)
	}
	if len(outer.Events) != 1 || outer.Events[0].Name != "did a thing" {
		t.Errorf("events = %+v, want one named 'did a thing'", outer.Events)
	}
}

// TestOTLPErrorStatus checks that a failing operation is marked as an error, so
// it shows up red in Jaeger like the Haskell recordError did.
func TestOTLPErrorStatus(t *testing.T) {
	var captured []byte
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		b, _ := io.ReadAll(r.Body)
		captured = b
		w.WriteHeader(http.StatusOK)
	}))
	defer srv.Close()

	t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", srv.URL)
	ctx := context.Background()
	shutdown, err := initTracing(ctx)
	if err != nil {
		t.Fatal(err)
	}
	_ = inSpan(ctx, "failing", func(ctx context.Context, span trace.Span) error {
		return io.ErrUnexpectedEOF
	})
	if err := shutdown(ctx); err != nil {
		t.Fatal(err)
	}

	var payload otlpPayload
	if err := json.Unmarshal(captured, &payload); err != nil {
		t.Fatal(err)
	}
	s := payload.ResourceSpans[0].ScopeSpans[0].Spans[0]
	if s.Status.Code != 2 {
		t.Errorf("status.code = %d, want 2 (ERROR)", s.Status.Code)
	}
	if s.Status.Message == "" {
		t.Error("status.message should carry the error text")
	}
	// An exception event is recorded by RecordError.
	found := false
	for _, ev := range s.Events {
		if ev.Name == "exception" {
			found = true
		}
	}
	if !found {
		t.Errorf("expected an 'exception' event, got %+v", s.Events)
	}
}

// TestTracingDisabled makes sure the kill switch works and that spans are still
// safe to use when tracing is off.
func TestTracingDisabled(t *testing.T) {
	t.Setenv("WHATCD_RESOLVER_DISABLE_TRACING", "1")
	ctx := context.Background()
	shutdown, err := initTracing(ctx)
	if err != nil {
		t.Fatal(err)
	}
	if err := inSpan(ctx, "noop", func(ctx context.Context, span trace.Span) error {
		attr(span, "x", 1)
		return nil
	}); err != nil {
		t.Fatal(err)
	}
	if err := shutdown(ctx); err != nil {
		t.Fatal(err)
	}
}