/
cds_api.go
391 lines (326 loc) · 10.5 KB
/
cds_api.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
//go:generate go run github.com/deepmap/oapi-codegen/v2/cmd/oapi-codegen --config=cfg.yaml ../api/stunner_openapi.yaml
package client
import (
"context"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
stnrv1 "github.com/l7mp/stunner/pkg/apis/v1"
"github.com/l7mp/stunner/pkg/config/client/api"
"github.com/pion/logging"
)
const (
ConfigNamespaceNameAPIEndpoint = "/api/v1/configs/%s/%s"
ConfigsNamespaceAPIEndpoint = "/api/v1/configs/%s"
AllConfigsAPIEndpoint = "/api/v1/configs"
)
type ConfigList struct {
Version string `json:"version"`
Items []*stnrv1.StunnerConfig `json:"items"`
}
type ClientOption = api.ClientOption
type HttpRequestDoer = api.HttpRequestDoer
type CdsApi interface {
// Endpoint returns the address of the server plus the WebSocket API endpoint.
Endpoint() (string, string)
// Get loads the config(s) from the API endpoint.
Get(ctx context.Context) ([]*stnrv1.StunnerConfig, error)
// Watch watches config(s) from the API endpoint of a CDS server. If the server is not
// available watch will retry, and if the connection goes away it will create a new one.
Watch(ctx context.Context, ch chan<- *stnrv1.StunnerConfig) error
// Poll creates a one-shot config watcher without the retry mechanincs of Watch.
Poll(ctx context.Context, ch chan<- *stnrv1.StunnerConfig) error
logging.LeveledLogger
}
func WithHTTPClient(doer HttpRequestDoer) ClientOption { return api.WithHTTPClient(doer) }
// AllConfigsAPI is the API for listing all configs in a namespace.
type AllConfigsAPI struct {
addr, httpURI, wsURI string
client *api.ClientWithResponses
logging.LeveledLogger
}
func NewAllConfigsAPI(addr string, logger logging.LeveledLogger, opts ...ClientOption) (CdsApi, error) {
httpuri, err := getURI(addr)
if err != nil {
return nil, err
}
wsuri, err := wsURI(addr, AllConfigsAPIEndpoint)
if err != nil {
return nil, err
}
client, err := api.NewClientWithResponses(httpuri.String(), opts...)
if err != nil {
return nil, err
}
return &AllConfigsAPI{
addr: addr,
httpURI: httpuri.String(),
wsURI: wsuri,
client: client,
LeveledLogger: logger,
}, nil
}
func (a *AllConfigsAPI) Endpoint() (string, string) {
return a.addr, a.wsURI
}
func (a *AllConfigsAPI) Get(ctx context.Context) ([]*stnrv1.StunnerConfig, error) {
a.Debugf("GET: loading all configs from CDS server %s", a.addr)
r, err := a.client.ListV1ConfigsWithResponse(ctx, nil)
if err != nil {
return []*stnrv1.StunnerConfig{}, err
}
if r.HTTPResponse.StatusCode != http.StatusOK {
body := strings.TrimSpace(string(r.Body))
return []*stnrv1.StunnerConfig{}, fmt.Errorf("HTTP error (status: %s): %s",
r.HTTPResponse.Status, body)
}
return decodeConfigList(r.Body)
}
func (a *AllConfigsAPI) Watch(ctx context.Context, ch chan<- *stnrv1.StunnerConfig) error {
a.Debugf("WATCH: watching all configs from CDS server %s", a.wsURI)
return watch(ctx, a, ch)
}
func (a *AllConfigsAPI) Poll(ctx context.Context, ch chan<- *stnrv1.StunnerConfig) error {
a.Debugf("POLL: polling all configs from CDS server %s", a.wsURI)
return poll(ctx, a, ch)
}
// ConfigsNamespaceAPI is the API for listing all configs in a namespace.
type ConfigsNamespaceAPI struct {
addr, namespace, httpURI, wsURI string
client *api.ClientWithResponses
logging.LeveledLogger
}
func NewConfigsNamespaceAPI(addr, namespace string, logger logging.LeveledLogger, opts ...ClientOption) (CdsApi, error) {
httpuri, err := getURI(addr)
if err != nil {
return nil, err
}
wsuri, err := wsURI(addr, fmt.Sprintf(ConfigsNamespaceAPIEndpoint, namespace))
if err != nil {
return nil, err
}
client, err := api.NewClientWithResponses(httpuri.String(), opts...)
if err != nil {
return nil, err
}
return &ConfigsNamespaceAPI{
addr: addr,
namespace: namespace,
httpURI: httpuri.String(),
wsURI: wsuri,
client: client,
LeveledLogger: logger,
}, nil
}
func (a *ConfigsNamespaceAPI) Endpoint() (string, string) {
return a.addr, a.wsURI
}
func (a *ConfigsNamespaceAPI) Get(ctx context.Context) ([]*stnrv1.StunnerConfig, error) {
a.Debugf("GET: loading all configs in namespace %s from CDS server %s",
a.namespace, a.addr)
r, err := a.client.ListV1ConfigsNamespaceWithResponse(ctx, a.namespace, nil)
if err != nil {
return []*stnrv1.StunnerConfig{}, err
}
if r.HTTPResponse.StatusCode != http.StatusOK {
body := strings.TrimSpace(string(r.Body))
return []*stnrv1.StunnerConfig{}, fmt.Errorf("HTTP error (status: %s): %s",
r.HTTPResponse.Status, body)
}
return decodeConfigList(r.Body)
}
func (a *ConfigsNamespaceAPI) Watch(ctx context.Context, ch chan<- *stnrv1.StunnerConfig) error {
a.Debugf("WATCH: watching all configs in namespace %s from CDS server %s",
a.namespace, a.wsURI)
return watch(ctx, a, ch)
}
func (a *ConfigsNamespaceAPI) Poll(ctx context.Context, ch chan<- *stnrv1.StunnerConfig) error {
a.Debugf("POLL: polling all configs in namespace %s from CDS server %s",
a.namespace, a.wsURI)
return poll(ctx, a, ch)
}
type ConfigNamespaceNameAPI struct {
addr, namespace, name, httpURI, wsURI string
client *api.ClientWithResponses
logging.LeveledLogger
}
func NewConfigNamespaceNameAPI(addr, namespace, name string, logger logging.LeveledLogger, opts ...ClientOption) (CdsApi, error) {
httpuri, err := getURI(addr)
if err != nil {
return nil, err
}
wsuri, err := wsURI(addr, fmt.Sprintf(ConfigNamespaceNameAPIEndpoint, namespace, name))
if err != nil {
return nil, err
}
client, err := api.NewClientWithResponses(httpuri.String(), opts...)
if err != nil {
return nil, err
}
return &ConfigNamespaceNameAPI{
addr: addr,
namespace: namespace,
name: name,
httpURI: httpuri.String(),
wsURI: wsuri,
client: client,
LeveledLogger: logger,
}, nil
}
func (a *ConfigNamespaceNameAPI) Endpoint() (string, string) {
return a.addr, a.wsURI
}
func (a *ConfigNamespaceNameAPI) Get(ctx context.Context) ([]*stnrv1.StunnerConfig, error) {
a.Debugf("GET: loading config for gateway %s/%s from CDS server %s",
a.namespace, a.name, a.addr)
var params *api.GetV1ConfigNamespaceNameParams
r, err := a.client.GetV1ConfigNamespaceNameWithResponse(ctx, a.namespace, a.name, params)
if err != nil {
return []*stnrv1.StunnerConfig{}, err
}
if r.HTTPResponse.StatusCode != http.StatusOK {
body := strings.TrimSpace(string(r.Body))
return []*stnrv1.StunnerConfig{}, fmt.Errorf("HTTP error (status: %s): %s",
r.HTTPResponse.Status, body)
}
return decodeConfig(r.Body)
}
func (a *ConfigNamespaceNameAPI) Watch(ctx context.Context, ch chan<- *stnrv1.StunnerConfig) error {
a.Debugf("WATCH: watching config for gateway %s/%s from CDS server %s",
a.namespace, a.name, a.wsURI)
return watch(ctx, a, ch)
}
func (a *ConfigNamespaceNameAPI) Poll(ctx context.Context, ch chan<- *stnrv1.StunnerConfig) error {
a.Debugf("POLL: polling config for gateway %s/%s from CDS server %s",
a.namespace, a.name, a.wsURI)
return poll(ctx, a, ch)
}
func watch(ctx context.Context, a CdsApi, ch chan<- *stnrv1.StunnerConfig) error {
go func() {
for {
if err := poll(ctx, a, ch); err != nil {
_, wsuri := a.Endpoint()
a.Errorf("failed to init CDS watcher (url: %s): %s", wsuri, err.Error())
} else {
// context got cancelled
return
}
// wait between each attempt
time.Sleep(RetryPeriod)
}
}()
return nil
}
// ////////////
// API workers
// ////////////
func poll(ctx context.Context, a CdsApi, ch chan<- *stnrv1.StunnerConfig) error {
_, url := a.Endpoint()
a.Tracef("poll: trying to open connection to CDS server at %s", url)
conn, _, err := websocket.DefaultDialer.DialContext(ctx, url, makeHeader(url))
if err != nil {
return err
}
defer conn.Close() // this will close the poller goroutine
a.Infof("connection successfully opened to config discovery server at %s", url)
pingTicker := time.NewTicker(PingPeriod)
closePinger := make(chan any)
defer close(closePinger)
// wait until all threads are closed and we can remove the error channel
errCh := make(chan error, 1)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer pingTicker.Stop()
defer wg.Done()
for {
select {
case <-pingTicker.C:
// p.log.Tracef("++++ PING ++++ for CDS server %q at client %q", location, p.id)
conn.SetWriteDeadline(time.Now().Add(WriteWait)) //nolint:errcheck
if err := conn.WriteMessage(websocket.PingMessage, []byte("keepalive")); err != nil {
errCh <- fmt.Errorf("could not ping CDS server at %q: %w",
conn.RemoteAddr(), err)
return
}
case <-closePinger:
a.Tracef("closing ping handler to config discovery server at %q", url)
return
}
}
}()
// poller
go func() {
defer wg.Done()
// the next pong must arrive within the PongWait period
conn.SetReadDeadline(time.Now().Add(PongWait)) //nolint:errcheck
// reinit the deadline when we get a pong
conn.SetPongHandler(func(string) error {
// a.Tracef("Got PONG from server %q", url)
conn.SetReadDeadline(time.Now().Add(PongWait)) //nolint:errcheck
return nil
})
for {
// ping-pong deadline misses will end up being caught here as a read beyond
// the deadline
msgType, msg, err := conn.ReadMessage()
if err != nil {
errCh <- err
return
}
if msgType != websocket.TextMessage {
errCh <- fmt.Errorf("unexpected message type (code: %d) from client %q",
msgType, conn.RemoteAddr().String())
return
}
if len(msg) == 0 {
a.Warn("ignoring zero-length config")
continue
}
c, err := ParseConfig(msg)
if err != nil {
// assume it is a YAML/JSON syntax error: report and ignore
a.Warnf("could not parse config: %s", err.Error())
continue
}
if err := c.Validate(); err != nil {
a.Warnf("invalid config: %s", err.Error())
continue
}
a.Debugf("new config received from %q: %q", url, c.String())
ch <- c
}
}()
// wait fo cancel
for {
defer func() {
a.Infof("closing connection for client %s", conn.RemoteAddr().String())
conn.WriteMessage(websocket.CloseMessage, []byte{}) //nolint:errcheck
conn.Close()
closePinger <- struct{}{}
wg.Wait()
close(errCh)
}()
select {
case <-ctx.Done():
// cancel: normal return
return nil
case err := <-errCh:
// error: return it
return err
}
}
}
// creates an origin header
func makeHeader(uri string) http.Header {
header := http.Header{}
url, _ := getURI(uri) //nolint:errcheck
origin := *url
origin.Scheme = "http"
origin.Path = ""
header.Set("origin", origin.String())
return header
}