forked from open-telemetry/opamp-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwsclient.go
305 lines (251 loc) · 8.37 KB
/
wsclient.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
package client
import (
"context"
"errors"
"net/http"
"net/url"
"sync"
"sync/atomic"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/gorilla/websocket"
"github.com/open-telemetry/opamp-go/client/internal"
"github.com/open-telemetry/opamp-go/client/types"
sharedinternal "github.com/open-telemetry/opamp-go/internal"
"github.com/open-telemetry/opamp-go/protobufs"
)
// wsClient is an OpAMP Client implementation for WebSocket transport.
// See specification: https://github.com/open-telemetry/opamp-spec/blob/main/specification.md#websocket-transport
type wsClient struct {
common internal.ClientCommon
// OpAMP Server URL.
url *url.URL
// HTTP request headers to use when connecting to OpAMP Server.
requestHeader http.Header
// Websocket dialer and connection.
dialer websocket.Dialer
conn *websocket.Conn
connMutex sync.RWMutex
// The sender is responsible for sending portion of the OpAMP protocol.
sender *internal.WSSender
// last non-nil internal error that was encountered in the conn retry loop,
// currently used only for testing.
lastInternalErr atomic.Pointer[error]
}
// NewWebSocket creates a new OpAMP Client that uses WebSocket transport.
func NewWebSocket(logger types.Logger) *wsClient {
if logger == nil {
logger = &sharedinternal.NopLogger{}
}
sender := internal.NewSender(logger)
w := &wsClient{
common: internal.NewClientCommon(logger, sender),
sender: sender,
}
return w
}
func (c *wsClient) Start(ctx context.Context, settings types.StartSettings) error {
if err := c.common.PrepareStart(ctx, settings); err != nil {
return err
}
// Prepare connection settings.
c.dialer = *websocket.DefaultDialer
var err error
c.url, err = url.Parse(settings.OpAMPServerURL)
if err != nil {
return err
}
c.dialer.EnableCompression = settings.EnableCompression
if settings.TLSConfig != nil {
c.url.Scheme = "wss"
}
c.dialer.TLSClientConfig = settings.TLSConfig
c.requestHeader = settings.Header
c.common.StartConnectAndRun(c.runUntilStopped)
return nil
}
func (c *wsClient) Stop(ctx context.Context) error {
// Close connection if any.
c.connMutex.RLock()
conn := c.conn
c.connMutex.RUnlock()
if conn != nil {
_ = conn.Close()
}
return c.common.Stop(ctx)
}
func (c *wsClient) AgentDescription() *protobufs.AgentDescription {
return c.common.AgentDescription()
}
func (c *wsClient) SetAgentDescription(descr *protobufs.AgentDescription) error {
return c.common.SetAgentDescription(descr)
}
func (c *wsClient) RequestConnectionSettings(request *protobufs.ConnectionSettingsRequest) error {
return c.common.RequestConnectionSettings(request)
}
func (c *wsClient) SetHealth(health *protobufs.ComponentHealth) error {
return c.common.SetHealth(health)
}
func (c *wsClient) UpdateEffectiveConfig(ctx context.Context) error {
return c.common.UpdateEffectiveConfig(ctx)
}
func (c *wsClient) SetRemoteConfigStatus(status *protobufs.RemoteConfigStatus) error {
return c.common.SetRemoteConfigStatus(status)
}
func (c *wsClient) SetPackageStatuses(statuses *protobufs.PackageStatuses) error {
return c.common.SetPackageStatuses(statuses)
}
func (c *wsClient) SetCustomCapabilities(customCapabilities *protobufs.CustomCapabilities) error {
return c.common.SetCustomCapabilities(customCapabilities)
}
func (c *wsClient) SendCustomMessage(message *protobufs.CustomMessage) (messageSendingChannel chan struct{}, err error) {
return c.common.SendCustomMessage(message)
}
// Try to connect once. Returns an error if connection fails and optional retryAfter
// duration to indicate to the caller to retry after the specified time as instructed
// by the Server.
func (c *wsClient) tryConnectOnce(ctx context.Context) (retryAfter sharedinternal.OptionalDuration, err error) {
var resp *http.Response
conn, resp, err := c.dialer.DialContext(ctx, c.url.String(), c.requestHeader)
if err != nil {
if c.common.Callbacks != nil && !c.common.IsStopping() {
c.common.Callbacks.OnConnectFailed(ctx, err)
}
if resp != nil {
duration := sharedinternal.ExtractRetryAfterHeader(resp)
if resp.StatusCode >= 300 && resp.StatusCode < 400 {
// very liberal handling of 3xx that largely ignores HTTP semantics
redirect, err := resp.Location()
if err != nil {
c.common.Logger.Errorf(ctx, "%d redirect, but no valid location: %s", resp.StatusCode, err)
return duration, err
}
// rewrite the scheme for the sake of tolerance
if redirect.Scheme == "http" {
redirect.Scheme = "ws"
} else if redirect.Scheme == "https" {
redirect.Scheme = "wss"
}
c.common.Logger.Debugf(ctx, "%d redirect to %s", resp.StatusCode, redirect)
// Set the URL to the redirect, so that it connects to it on the
// next cycle.
c.url = redirect
} else {
c.common.Logger.Errorf(ctx, "Server responded with status=%v", resp.Status)
}
return duration, err
}
return sharedinternal.OptionalDuration{Defined: false}, err
}
// Successfully connected.
c.connMutex.Lock()
c.conn = conn
c.connMutex.Unlock()
if c.common.Callbacks != nil {
c.common.Callbacks.OnConnect(ctx)
}
return sharedinternal.OptionalDuration{Defined: false}, nil
}
// Continuously try until connected. Will return nil when successfully
// connected. Will return error if it is cancelled via context.
func (c *wsClient) ensureConnected(ctx context.Context) error {
infiniteBackoff := backoff.NewExponentialBackOff()
// Make ticker run forever.
infiniteBackoff.MaxElapsedTime = 0
interval := time.Duration(0)
for {
timer := time.NewTimer(interval)
interval = infiniteBackoff.NextBackOff()
select {
case <-timer.C:
{
if retryAfter, err := c.tryConnectOnce(ctx); err != nil {
c.lastInternalErr.Store(&err)
if errors.Is(err, context.Canceled) {
c.common.Logger.Debugf(ctx, "Client is stopped, will not try anymore.")
return err
} else {
c.common.Logger.Errorf(ctx, "Connection failed (%v), will retry.", err)
}
// Retry again a bit later.
if retryAfter.Defined && retryAfter.Duration > interval {
// If the Server suggested connecting later than our interval
// then honour Server's request, otherwise wait at least
// as much as we calculated.
interval = retryAfter.Duration
}
continue
}
// Connected successfully.
return nil
}
case <-ctx.Done():
c.common.Logger.Debugf(ctx, "Client is stopped, will not try anymore.")
timer.Stop()
return ctx.Err()
}
}
}
// runOneCycle performs the following actions:
// 1. connect (try until succeeds).
// 2. send first status report.
// 3. receive and process messages until error happens.
//
// If it encounters an error it closes the connection and returns.
// Will stop and return if Stop() is called (ctx is cancelled, isStopping is set).
func (c *wsClient) runOneCycle(ctx context.Context) {
if err := c.ensureConnected(ctx); err != nil {
// Can't connect, so can't move forward. This currently happens when we
// are being stopped.
return
}
if c.common.IsStopping() {
_ = c.conn.Close()
return
}
// Prepare the first status report.
err := c.common.PrepareFirstMessage(ctx)
if err != nil {
c.common.Logger.Errorf(ctx, "cannot prepare the first message:%v", err)
return
}
// Create a cancellable context for background processors.
procCtx, procCancel := context.WithCancel(ctx)
// Connected successfully. Start the sender. This will also send the first
// status report.
if err := c.sender.Start(procCtx, c.conn); err != nil {
c.common.Logger.Errorf(procCtx, "Failed to send first status report: %v", err)
// We could not send the report, the only thing we can do is start over.
_ = c.conn.Close()
procCancel()
return
}
// First status report sent. Now loop to receive and process messages.
r := internal.NewWSReceiver(
c.common.Logger,
c.common.Callbacks,
c.conn,
c.sender,
&c.common.ClientSyncedState,
c.common.PackagesStateProvider,
c.common.Capabilities,
)
r.ReceiverLoop(ctx)
// Stop the background processors.
procCancel()
// If we exited receiverLoop it means there is a connection error, we cannot
// read messages anymore. We need to start over.
// Close the connection to unblock the WSSender as well.
_ = c.conn.Close()
// Wait for WSSender to stop.
c.sender.WaitToStop()
}
func (c *wsClient) runUntilStopped(ctx context.Context) {
// Iterates until we detect that the client is stopping.
for {
if c.common.IsStopping() {
return
}
c.runOneCycle(ctx)
}
}