This repository has been archived by the owner on Jul 25, 2023. It is now read-only.
forked from jaegertracing/jaeger-client-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mock_agent.go
179 lines (156 loc) · 5.45 KB
/
mock_agent.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
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package testutils
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"github.com/uber/jaeger-client-go/thrift-gen/agent"
"github.com/uber/jaeger-client-go/thrift-gen/sampling"
"github.com/uber/jaeger-client-go/thrift-gen/zipkincore"
"github.com/uber/jaeger-client-go/utils"
"github.com/apache/thrift/lib/go/thrift"
)
// StartMockAgent runs a mock representation of jaeger-agent.
// This function returns a started server.
func StartMockAgent() (*MockAgent, error) {
transport, err := NewTUDPServerTransport("127.0.0.1:0")
if err != nil {
return nil, err
}
samplingManager := newSamplingManager()
samplingHandler := &samplingHandler{manager: samplingManager}
samplingServer := httptest.NewServer(samplingHandler)
agent := &MockAgent{
transport: transport,
samplingMgr: samplingManager,
samplingSrv: samplingServer,
}
var started sync.WaitGroup
started.Add(1)
go agent.serve(&started)
started.Wait()
return agent, nil
}
// Close stops the serving of traffic
func (s *MockAgent) Close() {
atomic.StoreUint32(&s.serving, 0)
s.transport.Close()
s.samplingSrv.Close()
}
// MockAgent is a mock representation of Jaeger Agent.
// It receives spans over UDP, and has an HTTP endpoint for sampling strategies.
type MockAgent struct {
transport *TUDPTransport
zipkinSpans []*zipkincore.Span
mutex sync.Mutex
serving uint32
samplingMgr *samplingManager
samplingSrv *httptest.Server
}
// SpanServerAddr returns the UDP host:port where MockAgent listens for spans
func (s *MockAgent) SpanServerAddr() string {
return s.transport.Addr().String()
}
// SpanServerClient returns a UDP client that can be used to send spans to the MockAgent
func (s *MockAgent) SpanServerClient() (agent.Agent, error) {
return utils.NewAgentClientUDP(s.SpanServerAddr(), 0)
}
// SamplingServerAddr returns the host:port of HTTP server exposing sampling strategy endpoint
func (s *MockAgent) SamplingServerAddr() string {
return s.samplingSrv.Listener.Addr().String()
}
func (s *MockAgent) serve(started *sync.WaitGroup) {
handler := agent.NewAgentProcessor(s)
protocolFact := thrift.NewTCompactProtocolFactory()
buf := make([]byte, utils.UDPPacketMaxLength, utils.UDPPacketMaxLength)
trans := thrift.NewTMemoryBufferLen(utils.UDPPacketMaxLength)
atomic.StoreUint32(&s.serving, 1)
started.Done()
for s.IsServing() {
n, err := s.transport.Read(buf)
if err == nil {
trans.Write(buf[:n])
protocol := protocolFact.GetProtocol(trans)
handler.Process(protocol, protocol)
}
}
}
// EmitZipkinBatch implements EmitZipkinBatch() of TChanSamplingManagerServer
func (s *MockAgent) EmitZipkinBatch(spans []*zipkincore.Span) (err error) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.zipkinSpans = append(s.zipkinSpans, spans...)
return err
}
// IsServing indicates whether the server is currently serving traffic
func (s *MockAgent) IsServing() bool {
return atomic.LoadUint32(&s.serving) == 1
}
// AddSamplingStrategy registers a sampling strategy for a service
func (s *MockAgent) AddSamplingStrategy(service string, strategy *sampling.SamplingStrategyResponse) {
s.samplingMgr.AddSamplingStrategy(service, strategy)
}
// GetZipkinSpans returns accumulated Zipkin spans
func (s *MockAgent) GetZipkinSpans() []*zipkincore.Span {
s.mutex.Lock()
defer s.mutex.Unlock()
n := len(s.zipkinSpans)
spans := make([]*zipkincore.Span, n, n)
copy(spans, s.zipkinSpans)
return spans
}
// ResetZipkinSpans discards accumulated Zipkin spans
func (s *MockAgent) ResetZipkinSpans() {
s.mutex.Lock()
defer s.mutex.Unlock()
s.zipkinSpans = nil
}
type samplingHandler struct {
manager *samplingManager
}
func (h *samplingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
services := r.URL.Query()["service"]
if len(services) == 0 {
http.Error(w, "'service' parameter is empty", http.StatusBadRequest)
return
}
if len(services) > 1 {
http.Error(w, "'service' parameter must occur only once", http.StatusBadRequest)
return
}
resp, err := h.manager.GetSamplingStrategy(services[0])
if err != nil {
http.Error(w, fmt.Sprintf("Error retrieving strategy: %+v", err), http.StatusInternalServerError)
return
}
json, err := json.Marshal(resp)
if err != nil {
http.Error(w, "Cannot marshall Thrift to JSON", http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
if _, err := w.Write(json); err != nil {
return
}
}