-
Notifications
You must be signed in to change notification settings - Fork 522
/
trace_receiver.go
462 lines (385 loc) · 12.5 KB
/
trace_receiver.go
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// Copyright 2019, OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jaegerreceiver
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"net/http"
"sync"
"github.com/gorilla/mux"
agentapp "github.com/jaegertracing/jaeger/cmd/agent/app"
"github.com/jaegertracing/jaeger/cmd/agent/app/configmanager"
"github.com/jaegertracing/jaeger/cmd/agent/app/reporter"
"github.com/jaegertracing/jaeger/cmd/collector/app"
"github.com/jaegertracing/jaeger/proto-gen/api_v2"
"github.com/jaegertracing/jaeger/thrift-gen/baggage"
"github.com/jaegertracing/jaeger/thrift-gen/jaeger"
"github.com/jaegertracing/jaeger/thrift-gen/sampling"
"github.com/jaegertracing/jaeger/thrift-gen/zipkincore"
"github.com/uber/jaeger-lib/metrics"
"github.com/uber/tchannel-go"
"github.com/uber/tchannel-go/thrift"
"go.uber.org/zap"
"google.golang.org/grpc"
"github.com/open-telemetry/opentelemetry-collector/consumer"
"github.com/open-telemetry/opentelemetry-collector/observability"
"github.com/open-telemetry/opentelemetry-collector/oterr"
"github.com/open-telemetry/opentelemetry-collector/receiver"
jaegertranslator "github.com/open-telemetry/opentelemetry-collector/translator/trace/jaeger"
)
// Configuration defines the behavior and the ports that
// the Jaeger receiver will use.
type Configuration struct {
CollectorThriftPort int
CollectorHTTPPort int
CollectorGRPCPort int
CollectorGRPCOptions []grpc.ServerOption
AgentPort int
AgentCompactThriftPort int
AgentBinaryThriftPort int
}
// Receiver type is used to receive spans that were originally intended to be sent to Jaeger.
// This receiver is basically a Jaeger collector.
type jReceiver struct {
// mu protects the fields of this type
mu sync.Mutex
nextConsumer consumer.TraceConsumer
startOnce sync.Once
stopOnce sync.Once
config *Configuration
agent *agentapp.Agent
grpc *grpc.Server
tchanServer *jTchannelReceiver
collectorServer *http.Server
defaultAgentCtx context.Context
}
type jTchannelReceiver struct {
nextConsumer consumer.TraceConsumer
tchannel *tchannel.Channel
}
const (
// As per https://www.jaegertracing.io/docs/1.13/deployment/
// By default, the port used by jaeger-agent to send spans in model.proto format
defaultGRPCPort = 14250
// By default, the port used by jaeger-agent to send spans in jaeger.thrift format
defaultTChannelPort = 14267
// By default, can accept spans directly from clients in jaeger.thrift format over binary thrift protocol
defaultCollectorHTTPPort = 14268
// As per https://www.jaegertracing.io/docs/1.7/deployment/#agent
// 5775 UDP accept zipkin.thrift over compact thrift protocol
// 6831 UDP accept jaeger.thrift over compact thrift protocol
// 6832 UDP accept jaeger.thrift over binary thrift protocol
defaultCompactThriftUDPPort = 6831
defaultBinaryThriftUDPPort = 6832
traceSource string = "Jaeger"
)
// New creates a TraceReceiver that receives traffic as a collector with both Thrift and HTTP transports.
func New(ctx context.Context, config *Configuration, nextConsumer consumer.TraceConsumer) (receiver.TraceReceiver, error) {
return &jReceiver{
config: config,
defaultAgentCtx: observability.ContextWithReceiverName(context.Background(), "jaeger-agent"),
nextConsumer: nextConsumer,
tchanServer: &jTchannelReceiver{
nextConsumer: nextConsumer,
},
}, nil
}
var _ receiver.TraceReceiver = (*jReceiver)(nil)
func (jr *jReceiver) collectorAddr() string {
var port int
if jr.config != nil {
port = jr.config.CollectorHTTPPort
}
if port <= 0 {
port = defaultCollectorHTTPPort
}
return fmt.Sprintf(":%d", port)
}
const defaultAgentPort = 5778
func (jr *jReceiver) agentAddress() string {
var port int
if jr.config != nil {
port = jr.config.AgentPort
}
if port <= 0 {
port = defaultAgentPort
}
return fmt.Sprintf(":%d", port)
}
// TODO https:/open-telemetry/opentelemetry-collector/issues/267
// Remove ThriftTChannel support.
func (jr *jReceiver) tchannelAddr() string {
var port int
if jr.config != nil {
port = jr.config.CollectorThriftPort
}
if port <= 0 {
port = defaultTChannelPort
}
return fmt.Sprintf(":%d", port)
}
func (jr *jReceiver) grpcAddr() string {
var port int
if jr.config != nil {
port = jr.config.CollectorGRPCPort
}
if port <= 0 {
port = defaultGRPCPort
}
return fmt.Sprintf(":%d", port)
}
func (jr *jReceiver) agentCompactThriftAddr() string {
var port int
if jr.config != nil {
port = jr.config.AgentCompactThriftPort
}
if port <= 0 {
port = defaultCompactThriftUDPPort
}
return fmt.Sprintf(":%d", port)
}
func (jr *jReceiver) agentBinaryThriftAddr() string {
var port int
if jr.config != nil {
port = jr.config.AgentBinaryThriftPort
}
if port <= 0 {
port = defaultBinaryThriftUDPPort
}
return fmt.Sprintf(":%d", port)
}
func (jr *jReceiver) TraceSource() string {
return traceSource
}
func (jr *jReceiver) StartTraceReception(host receiver.Host) error {
jr.mu.Lock()
defer jr.mu.Unlock()
var err = oterr.ErrAlreadyStarted
jr.startOnce.Do(func() {
//TODO(simi): remove patch once
// https:/open-telemetry/opentelemetry-collector/pull/434 has landed
//if err = jr.startAgent(host); err != nil && err != oterr.ErrAlreadyStarted {
// jr.stopTraceReceptionLocked()
// return
//}
if err = jr.startCollector(host); err != nil && err != oterr.ErrAlreadyStarted {
jr.stopTraceReceptionLocked()
return
}
err = nil
})
return err
}
func (jr *jReceiver) StopTraceReception() error {
jr.mu.Lock()
defer jr.mu.Unlock()
return jr.stopTraceReceptionLocked()
}
func (jr *jReceiver) stopTraceReceptionLocked() error {
var err = oterr.ErrAlreadyStopped
jr.stopOnce.Do(func() {
var errs []error
if jr.agent != nil {
jr.agent.Stop()
jr.agent = nil
}
if jr.collectorServer != nil {
if cerr := jr.collectorServer.Close(); cerr != nil {
errs = append(errs, cerr)
}
jr.collectorServer = nil
}
if jr.tchanServer.tchannel != nil {
jr.tchanServer.tchannel.Close()
jr.tchanServer.tchannel = nil
}
if jr.grpc != nil {
jr.grpc.Stop()
jr.grpc = nil
}
if len(errs) == 0 {
err = nil
return
}
// Otherwise combine all these errors
buf := new(bytes.Buffer)
for _, err := range errs {
fmt.Fprintf(buf, "%s\n", err.Error())
}
err = errors.New(buf.String())
})
return err
}
const collectorReceiverTagValue = "jaeger-collector"
const tchannelCollectorReceiverTagValue = "jaeger-tchannel-collector"
func consumeTraceData(ctx context.Context, batches []*jaeger.Batch, consumer consumer.TraceConsumer) ([]*jaeger.BatchSubmitResponse, error) {
jbsr := make([]*jaeger.BatchSubmitResponse, 0, len(batches))
for _, batch := range batches {
td, err := jaegertranslator.ThriftBatchToOCProto(batch)
// TODO: (@odeke-em) add this error for Jaeger observability
ok := false
if err == nil {
ok = true
td.SourceFormat = "jaeger"
consumer.ConsumeTraceData(ctx, td)
// We MUST unconditionally record metrics from this reception.
observability.RecordMetricsForTraceReceiver(ctx, len(batch.Spans), len(batch.Spans)-len(td.Spans))
}
jbsr = append(jbsr, &jaeger.BatchSubmitResponse{
Ok: ok,
})
}
return jbsr, nil
}
func (jr *jReceiver) SubmitBatches(batches []*jaeger.Batch, options app.SubmitBatchOptions) ([]*jaeger.BatchSubmitResponse, error) {
ctx := context.Background()
ctxWithReceiverName := observability.ContextWithReceiverName(ctx, collectorReceiverTagValue)
return consumeTraceData(ctxWithReceiverName, batches, jr.nextConsumer)
}
func (jtr *jTchannelReceiver) SubmitBatches(ctx thrift.Context, batches []*jaeger.Batch) ([]*jaeger.BatchSubmitResponse, error) {
ctxWithReceiverName := observability.ContextWithReceiverName(ctx, tchannelCollectorReceiverTagValue)
return consumeTraceData(ctxWithReceiverName, batches, jtr.nextConsumer)
}
var _ reporter.Reporter = (*jReceiver)(nil)
var _ agentapp.CollectorProxy = (*jReceiver)(nil)
var _ api_v2.CollectorServiceServer = (*jReceiver)(nil)
// EmitZipkinBatch implements cmd/agent/reporter.Reporter and it forwards
// Zipkin spans received by the Jaeger agent processor.
func (jr *jReceiver) EmitZipkinBatch(spans []*zipkincore.Span) error {
return nil
}
// EmitBatch implements cmd/agent/reporter.Reporter and it forwards
// Jaeger spans received by the Jaeger agent processor.
func (jr *jReceiver) EmitBatch(batch *jaeger.Batch) error {
td, err := jaegertranslator.ThriftBatchToOCProto(batch)
if err != nil {
observability.RecordMetricsForTraceReceiver(jr.defaultAgentCtx, len(batch.Spans), len(batch.Spans))
return err
}
err = jr.nextConsumer.ConsumeTraceData(jr.defaultAgentCtx, td)
observability.RecordMetricsForTraceReceiver(jr.defaultAgentCtx, len(batch.Spans), len(batch.Spans)-len(td.Spans))
return err
}
func (jr *jReceiver) GetReporter() reporter.Reporter {
return jr
}
func (jr *jReceiver) GetManager() configmanager.ClientConfigManager {
return jr
}
func (jr *jReceiver) GetSamplingStrategy(serviceName string) (*sampling.SamplingStrategyResponse, error) {
return &sampling.SamplingStrategyResponse{}, nil
}
func (jr *jReceiver) GetBaggageRestrictions(serviceName string) ([]*baggage.BaggageRestriction, error) {
return nil, nil
}
func (jr *jReceiver) PostSpans(ctx context.Context, r *api_v2.PostSpansRequest) (*api_v2.PostSpansResponse, error) {
ctxWithReceiverName := observability.ContextWithReceiverName(ctx, collectorReceiverTagValue)
td, err := jaegertranslator.ProtoBatchToOCProto(r.Batch)
td.SourceFormat = "jaeger"
if err != nil {
observability.RecordMetricsForTraceReceiver(ctxWithReceiverName, len(r.Batch.Spans), len(r.Batch.Spans))
return nil, err
}
err = jr.nextConsumer.ConsumeTraceData(ctx, td)
observability.RecordMetricsForTraceReceiver(ctxWithReceiverName, len(r.Batch.Spans), len(r.Batch.Spans)-len(td.Spans))
if err != nil {
return nil, err
}
return &api_v2.PostSpansResponse{}, err
}
func (jr *jReceiver) startAgent(_ receiver.Host) error {
processorConfigs := []agentapp.ProcessorConfiguration{
{
// Compact Thrift running by default on 6831.
Model: "jaeger",
Protocol: "compact",
Server: agentapp.ServerConfiguration{
HostPort: jr.agentCompactThriftAddr(),
},
},
{
// Binary Thrift running by default on 6832.
Model: "jaeger",
Protocol: "binary",
Server: agentapp.ServerConfiguration{
HostPort: jr.agentBinaryThriftAddr(),
},
},
}
builder := agentapp.Builder{
Processors: processorConfigs,
HTTPServer: agentapp.HTTPServerConfiguration{
HostPort: jr.agentAddress(),
},
}
agent, err := builder.CreateAgent(jr, zap.NewNop(), metrics.NullFactory)
if err != nil {
return err
}
if err := agent.Run(); err != nil {
return err
}
// Otherwise no error was encountered,
jr.agent = agent
return nil
}
func (jr *jReceiver) startCollector(host receiver.Host) error {
tch, terr := tchannel.NewChannel("jaeger-collector", new(tchannel.ChannelOptions))
if terr != nil {
return fmt.Errorf("failed to create NewTChannel: %v", terr)
}
server := thrift.NewServer(tch)
server.Register(jaeger.NewTChanCollectorServer(jr.tchanServer))
taddr := jr.tchannelAddr()
tln, terr := net.Listen("tcp", taddr)
if terr != nil {
return fmt.Errorf("failed to bind to TChannel address %q: %v", taddr, terr)
}
tch.Serve(tln)
jr.tchanServer.tchannel = tch
// Now the collector that runs over HTTP
caddr := jr.collectorAddr()
cln, cerr := net.Listen("tcp", caddr)
if cerr != nil {
// Abort and close tch
tch.Close()
return fmt.Errorf("failed to bind to Collector address %q: %v", caddr, cerr)
}
nr := mux.NewRouter()
apiHandler := app.NewAPIHandler(jr)
apiHandler.RegisterRoutes(nr)
jr.collectorServer = &http.Server{Handler: nr}
go func() {
_ = jr.collectorServer.Serve(cln)
}()
jr.grpc = grpc.NewServer(jr.config.CollectorGRPCOptions...)
gaddr := jr.grpcAddr()
gln, gerr := net.Listen("tcp", gaddr)
if gerr != nil {
// Abort and close tch, cln
tch.Close()
cln.Close()
return fmt.Errorf("failed to bind to gRPC address %q: %v", gaddr, gerr)
}
api_v2.RegisterCollectorServiceServer(jr.grpc, jr)
go func() {
if err := jr.grpc.Serve(gln); err != nil {
host.ReportFatalError(err)
}
}()
return nil
}