forked from rancher/pkg
/
connection.go
325 lines (271 loc) · 8.53 KB
/
connection.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
/*
Copyright 2019 The Knative 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 websocket
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
"io"
"io/ioutil"
"sync"
"time"
"go.uber.org/zap"
"k8s.io/apimachinery/pkg/util/wait"
"github.com/gorilla/websocket"
)
var (
// ErrConnectionNotEstablished is returned by methods that need a connection
// but no connection is already created.
ErrConnectionNotEstablished = errors.New("connection has not yet been established")
// errShuttingDown is returned internally once the shutdown signal has been sent.
errShuttingDown = errors.New("shutdown in progress")
// pongTimeout defines the amount of time allowed between two pongs to arrive
// before the connection is considered broken.
pongTimeout = 10 * time.Second
)
// RawConnection is an interface defining the methods needed
// from a websocket connection
type rawConnection interface {
WriteMessage(messageType int, data []byte) error
NextReader() (int, io.Reader, error)
Close() error
SetReadDeadline(deadline time.Time) error
SetPongHandler(func(string) error)
}
// ManagedConnection represents a websocket connection.
type ManagedConnection struct {
connection rawConnection
connectionFactory func() (rawConnection, error)
closeChan chan struct{}
closeOnce sync.Once
// Used to capture asynchronous processes to be waited
// on when shutting the connection down.
processingWg sync.WaitGroup
// If set, messages will be forwarded to this channel
messageChan chan []byte
// This mutex controls access to the connection reference
// itself.
connectionLock sync.RWMutex
// Gorilla's documentation states, that one reader and
// one writer are allowed concurrently.
readerLock sync.Mutex
writerLock sync.Mutex
// Used for the exponential backoff when connecting
connectionBackoff wait.Backoff
}
// NewDurableSendingConnection creates a new websocket connection
// that can only send messages to the endpoint it connects to.
// The connection will continuously be kept alive and reconnected
// in case of a loss of connectivity.
func NewDurableSendingConnection(target string, logger *zap.SugaredLogger) *ManagedConnection {
return NewDurableConnection(target, nil, logger)
}
// NewDurableConnection creates a new websocket connection, that
// passes incoming messages to the given message channel. It can also
// send messages to the endpoint it connects to.
// The connection will continuously be kept alive and reconnected
// in case of a loss of connectivity.
//
// Note: The given channel needs to be drained after calling `Shutdown`
// to not cause any deadlocks. If the channel's buffer is likely to be
// filled, this needs to happen in separate goroutines, i.e.
//
// go func() {conn.Shutdown(); close(messageChan)}
// go func() {for range messageChan {}}
func NewDurableConnection(target string, messageChan chan []byte, logger *zap.SugaredLogger) *ManagedConnection {
websocketConnectionFactory := func() (rawConnection, error) {
dialer := &websocket.Dialer{
HandshakeTimeout: 3 * time.Second,
}
conn, _, err := dialer.Dial(target, nil)
return conn, err
}
c := newConnection(websocketConnectionFactory, messageChan)
// Keep the connection alive asynchronously and reconnect on
// connection failure.
c.processingWg.Add(1)
go func() {
defer c.processingWg.Done()
for {
select {
default:
logger.Infof("Connecting to %q", target)
if err := c.connect(); err != nil {
logger.Errorw(fmt.Sprintf("Connecting to %q failed", target), zap.Error(err))
continue
}
logger.Infof("Connected to %q", target)
if err := c.keepalive(); err != nil {
logger.Errorw(fmt.Sprintf("Connection to %q broke down, reconnecting...", target), zap.Error(err))
}
if err := c.closeConnection(); err != nil {
logger.Errorw("Failed to close the connection after crashing", zap.Error(err))
}
case <-c.closeChan:
logger.Infof("Connection to %q is being shutdown", target)
return
}
}
}()
// Keep sending pings 3 times per pongTimeout interval.
c.processingWg.Add(1)
go func() {
defer c.processingWg.Done()
ticker := time.NewTicker(pongTimeout / 3)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := c.write(websocket.PingMessage, []byte{}); err != nil {
logger.Errorw("Failed to send ping message", zap.Error(err))
}
case <-c.closeChan:
return
}
}
}()
return c
}
// newConnection creates a new connection primitive.
func newConnection(connFactory func() (rawConnection, error), messageChan chan []byte) *ManagedConnection {
conn := &ManagedConnection{
connectionFactory: connFactory,
closeChan: make(chan struct{}),
messageChan: messageChan,
connectionBackoff: wait.Backoff{
Duration: 100 * time.Millisecond,
Factor: 1.3,
Steps: 20,
Jitter: 0.5,
},
}
return conn
}
// connect tries to establish a websocket connection.
func (c *ManagedConnection) connect() error {
var err error
wait.ExponentialBackoff(c.connectionBackoff, func() (bool, error) {
select {
default:
var conn rawConnection
conn, err = c.connectionFactory()
if err != nil {
return false, nil
}
// Setting the read deadline will cause NextReader in read
// to fail if it is exceeded. This deadline is reset each
// time we receive a pong message so we know the connection
// is still intact.
conn.SetReadDeadline(time.Now().Add(pongTimeout))
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(pongTimeout))
return nil
})
c.connectionLock.Lock()
defer c.connectionLock.Unlock()
c.connection = conn
return true, nil
case <-c.closeChan:
err = errShuttingDown
return false, err
}
})
return err
}
// keepalive keeps the connection open.
func (c *ManagedConnection) keepalive() error {
for {
select {
default:
if err := c.read(); err != nil {
return err
}
case <-c.closeChan:
return errShuttingDown
}
}
}
// closeConnection closes the underlying websocket connection.
func (c *ManagedConnection) closeConnection() error {
c.connectionLock.Lock()
defer c.connectionLock.Unlock()
if c.connection != nil {
err := c.connection.Close()
c.connection = nil
return err
}
return nil
}
// read reads the next message from the connection.
// If a messageChan is supplied and the current message type is not
// a control message, the message is sent to that channel.
func (c *ManagedConnection) read() error {
c.connectionLock.RLock()
defer c.connectionLock.RUnlock()
if c.connection == nil {
return ErrConnectionNotEstablished
}
c.readerLock.Lock()
defer c.readerLock.Unlock()
messageType, reader, err := c.connection.NextReader()
if err != nil {
return err
}
// Send the message to the channel if its an application level message
// and if that channel is set.
// TODO(markusthoemmes): Return the messageType along with the payload.
if c.messageChan != nil && (messageType == websocket.TextMessage || messageType == websocket.BinaryMessage) {
if message, _ := ioutil.ReadAll(reader); message != nil {
c.messageChan <- message
}
}
return nil
}
func (c *ManagedConnection) write(messageType int, body []byte) error {
c.connectionLock.RLock()
defer c.connectionLock.RUnlock()
if c.connection == nil {
return ErrConnectionNotEstablished
}
c.writerLock.Lock()
defer c.writerLock.Unlock()
return c.connection.WriteMessage(messageType, body)
}
// Status checks the connection status of the webhook.
func (c *ManagedConnection) Status() error {
c.connectionLock.RLock()
defer c.connectionLock.RUnlock()
if c.connection == nil {
return ErrConnectionNotEstablished
}
return nil
}
// Send sends an encodable message over the websocket connection.
func (c *ManagedConnection) Send(msg interface{}) error {
var b bytes.Buffer
enc := gob.NewEncoder(&b)
if err := enc.Encode(msg); err != nil {
return err
}
return c.write(websocket.BinaryMessage, b.Bytes())
}
// Shutdown closes the websocket connection.
func (c *ManagedConnection) Shutdown() error {
c.closeOnce.Do(func() {
close(c.closeChan)
})
err := c.closeConnection()
c.processingWg.Wait()
return err
}