-
Notifications
You must be signed in to change notification settings - Fork 67
/
client.go
260 lines (208 loc) 路 5.72 KB
/
client.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
package client
import (
"context"
"errors"
"fmt"
"io"
"log"
"os"
"strings"
"sync"
"time"
retry "github.com/avast/retry-go"
"github.com/kubeshop/tracetest/agent/proto"
"go.uber.org/zap"
"google.golang.org/grpc"
"go.opentelemetry.io/otel/trace"
)
const (
ReconnectRetryAttempts = 6
ReconnectRetryAttemptDelay = 1 * time.Second
defaultPingPeriod = 30 * time.Second
)
type Config struct {
APIKey string
AgentName string
PingPeriod time.Duration
}
type SessionConfig struct {
BatchTimeout time.Duration
AgentIdentification *proto.AgentIdentification
}
type Client struct {
mutex sync.Mutex
endpoint string
conn *grpc.ClientConn
config Config
sessionConfig *SessionConfig
done chan bool
logger *zap.Logger
tracer trace.Tracer
stopListener func(context.Context, *proto.StopRequest) error
triggerListener func(context.Context, *proto.TriggerRequest) error
pollListener func(context.Context, *proto.PollingRequest) error
shutdownListener func(context.Context, *proto.ShutdownRequest) error
dataStoreConnectionListener func(context.Context, *proto.DataStoreConnectionTestRequest) error
otlpConnectionTestListener func(context.Context, *proto.OTLPConnectionTestRequest) error
}
func (c *Client) Start(ctx context.Context) error {
err := c.startup(ctx)
if err != nil {
return err
}
c.done = make(chan bool)
ctx, cancel := context.WithCancel(ctx)
go func() {
<-c.done
// We cannot `defer cancel()` in this case because the start listener functions
// start one goroutine each and don't block the execution of this function.
// Thus, if we cancel the context, all those goroutines will fail.
cancel()
}()
err = c.startStopListener(ctx)
if err != nil {
return err
}
err = c.startTriggerListener(ctx)
if err != nil {
return err
}
err = c.startPollerListener(ctx)
if err != nil {
return err
}
err = c.startShutdownListener(ctx)
if err != nil {
return err
}
err = c.startDataStoreConnectionTestListener(ctx)
if err != nil {
return err
}
err = c.startOTLPConnectionTestListener(ctx)
if err != nil {
return err
}
err = c.startHeartBeat(ctx)
if err != nil {
return err
}
return nil
}
func (c *Client) WaitUntilDisconnected() {
<-c.done
}
func (c *Client) SessionConfiguration() *SessionConfig {
if c.sessionConfig == nil {
return nil
}
deferredPtr := *c.sessionConfig
return &deferredPtr
}
func (c *Client) Close() error {
c.done <- true
return c.conn.Close()
}
func (c *Client) OnStopRequest(listener func(context.Context, *proto.StopRequest) error) {
c.stopListener = listener
}
func (c *Client) OnTriggerRequest(listener func(context.Context, *proto.TriggerRequest) error) {
c.triggerListener = listener
}
func (c *Client) OnDataStoreTestConnectionRequest(listener func(context.Context, *proto.DataStoreConnectionTestRequest) error) {
c.dataStoreConnectionListener = listener
}
func (c *Client) OnPollingRequest(listener func(context.Context, *proto.PollingRequest) error) {
c.pollListener = listener
}
func (c *Client) OnOTLPConnectionTest(listener func(context.Context, *proto.OTLPConnectionTestRequest) error) {
c.otlpConnectionTestListener = listener
}
func (c *Client) OnConnectionClosed(listener func(context.Context, *proto.ShutdownRequest) error) {
c.shutdownListener = listener
}
func (c *Client) getConnectionRequest() (*proto.ConnectRequest, error) {
name, err := c.getName()
if err != nil {
return nil, err
}
request := proto.ConnectRequest{
ApiKey: c.config.APIKey,
Name: name,
}
return &request, nil
}
// getName retrieves the name of the agent. By default, it is the host name, however,
// it can be overwritten with an environment variable, or a flag.
func (c *Client) getName() (string, error) {
if name := c.config.AgentName; name != "" {
return name, nil
}
if name := os.Getenv("TRACETEST_AGENT_NAME"); name != "" {
return name, nil
}
hostname, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("could not get hostname: %w", err)
}
return hostname, nil
}
func isCancelledError(err error) bool {
return err != nil && strings.Contains(err.Error(), "context canceled")
}
func (c *Client) reconnect() error {
if c.conn != nil {
c.conn.Close()
}
// connection is not working. We need to reconnect
err := retry.Do(func() error {
return c.connect(context.Background())
}, retry.Attempts(ReconnectRetryAttempts), retry.Delay(ReconnectRetryAttemptDelay))
if err != nil {
return fmt.Errorf("could not reconnect to server: %w", err)
}
return c.Start(context.Background())
}
func (c *Client) handleDisconnectionError(inputErr error) (bool, error) {
if !isConnectionError(inputErr) {
// if it's nil or any error other than the one we care about, return it and let the caller handle it
return false, inputErr
}
log.Printf("Reconnecting agent due to error: %s", inputErr.Error())
err := retry.Do(func() error {
return c.reconnect()
})
if err != nil {
log.Fatal(err)
}
return true, nil
}
func isConnectionError(err error) bool {
if err == nil {
return false
}
possibleErrors := []string{
"connection refused",
"server closed",
"token is expired",
// From time to time, the server can start sending those errors to the
// agent. This mitigates the risk of an agent getting stuck in an error state
"unexpected HTTP status code received from server: 500",
"the client connection is closing",
}
for _, possibleErr := range possibleErrors {
if strings.Contains(err.Error(), possibleErr) {
return true
}
}
return false
}
func isEndOfFileError(err error) bool {
if err == nil {
return false
}
if isEof := errors.Is(err, io.EOF); isEof {
return true
}
return strings.Contains(err.Error(), "EOF")
}