-
Notifications
You must be signed in to change notification settings - Fork 250
/
client.go
275 lines (241 loc) · 6.79 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package client
import (
"net"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
"github.com/taskcluster/taskcluster/v59/tools/websocktunnel/util"
"github.com/taskcluster/taskcluster/v59/tools/websocktunnel/wsmux"
)
type clientState int
const (
stateRunning = iota
stateBroken
stateClosed
)
// Config contains the configuration for a Client. This is generated by
// a Configurer.
type Config struct {
// The client ID to register
ID string
// The address of the websocktunnel server (https:// or wss://)
TunnelAddr string
// The JWT to authenticate to the websocktunnel server. This should be
// a "fresh" token for each call to the Configurer.
Token string
// Configuration for retrying connections to the server
Retry RetryConfig
// A Logger for logging status updates; default is no logging
Logger util.Logger
}
// Configurer is a function which can generate a Config object to be used by
// the client. This is called whenever a reconnection is made, and should
// return a Config with a "fresh" token at that time.
type Configurer func() (Config, error)
// Client is used to connect to a websocktunnel instance and serve content over
// the tunnel. Client implements net.Listener.
type Client struct {
m sync.Mutex
id string
tunnelAddr string
token string
url atomic.Value
retry RetryConfig
logger util.Logger
configurer Configurer
session *wsmux.Session
state clientState
closed chan struct{}
acceptErr net.Error
}
// New creates a new Client instance.
func New(configurer Configurer) (*Client, error) {
config, err := configurer()
if err != nil {
return nil, err
}
cl := &Client{configurer: configurer}
cl.setConfig(config)
cl.closed = make(chan struct{}, 1)
conn, url, err := cl.connectWithRetry()
if err != nil {
return nil, err
}
cl.url.Store(url)
cl.session = wsmux.Client(conn, wsmux.Config{})
return cl, nil
}
// URL returns the url at which the websocktunnel server serves the client's
// endpoints. Users should use this value to create URLs (by appending) for
// viewers to access the client.
func (c *Client) URL() string {
return c.url.Load().(string)
}
// Accept is used to accept multiplexed streams from the tunnel as a net.Conn
// implementer.
//
// This is a net.Listener interface method.
func (c *Client) Accept() (net.Conn, error) {
select {
case <-c.closed:
return nil, ErrClientClosed
default:
}
c.m.Lock()
defer c.m.Unlock()
if c.state == stateBroken || c.state == stateClosed {
return nil, c.acceptErr
}
// c.session.Accept() will block until c.session.Close() is called
// c.session.Close() is called when c.Close() is called, but
// c.Close() also locks c.m, so we need to unlock c.m before calling
// c.session.Accept() to avoid the deadlock
//
// The deadlock was first observed in go1.19 due to
// https://go-review.googlesource.com/c/go/+/409537.
// This started enforcing that listeners are closed before
// active connections are cleaned up after a server shutdown.
// Prior to this, we unknowingly leaked deadlocked goroutines.
c.m.Unlock()
stream, err := c.session.Accept()
c.m.Lock()
if err != nil {
c.state = stateBroken
c.acceptErr = ErrClientReconnecting
go c.reconnect()
return nil, c.acceptErr
}
return stream, nil
}
// Addr returns the net.Addr of the underlying wsmux session
//
// This is a net.Listener method. Its return value in this case is
// not especially useful.
func (c *Client) Addr() net.Addr {
return c.session.Addr()
}
// Close connection to the tunnel.
//
// This is a net.Listener method.
func (c *Client) Close() error {
select {
case <-c.closed:
return nil
default:
close(c.closed)
go func() {
c.m.Lock()
defer c.m.Unlock()
c.acceptErr = ErrClientClosed
_ = c.session.Close()
}()
}
return nil
}
func (c *Client) setConfig(config Config) {
c.id = config.ID
c.tunnelAddr = util.MakeWsURL(config.TunnelAddr)
c.token = config.Token
c.retry = config.Retry.withDefaultValues()
c.logger = config.Logger
if c.logger == nil {
c.logger = &util.NilLogger{}
}
}
// connectWithRetry returns a websocket connection to the tunnel
func (c *Client) connectWithRetry() (*websocket.Conn, string, error) {
// if token is expired or not usable, get a new token from the authorizer
if !util.IsTokenUsable(c.token) {
config, err := c.configurer()
if err != nil {
return nil, "", err
}
c.setConfig(config)
}
header := make(http.Header)
header.Set("Authorization", "Bearer "+c.token)
header.Set("x-websocktunnel-id", c.id)
currentDelay := c.retry.InitialDelay
maxTimer := time.After(c.retry.MaxElapsedTime)
backoff := time.After(currentDelay)
for {
c.logger.Printf("trying to connect to %s", c.tunnelAddr)
conn, res, err := websocket.DefaultDialer.Dial(c.tunnelAddr, header)
if err == nil {
c.logger.Printf("connected to %s ", c.tunnelAddr)
url := res.Header.Get("x-websocktunnel-client-url")
return conn, url, err
}
if !shouldRetry(res) {
c.logger.Printf("connection failed with error:%v, response:%v", err, res)
if isAuthError(res) {
return nil, "", ErrAuthFailed
}
return nil, "", ErrRetryFailed
}
c.logger.Printf("connection to %s failed -- retrying.", c.tunnelAddr)
// wait for the next time to try connecting
select {
case <-maxTimer:
return nil, "", ErrRetryTimedOut
case <-backoff:
c.logger.Printf("trying to connect to %s", c.tunnelAddr)
conn, res, err := websocket.DefaultDialer.Dial(c.tunnelAddr, header)
if err == nil {
url := res.Header.Get("x-websocktunnel-client-url")
return conn, url, nil
}
if !shouldRetry(res) {
c.logger.Printf("connection to %s failed. could not connect", c.tunnelAddr)
return nil, "", ErrRetryFailed
}
currentDelay = c.retry.nextDelay(currentDelay)
backoff = time.After(currentDelay)
}
}
}
// reconnect is used to repair broken connections
func (c *Client) reconnect() {
c.m.Lock()
defer c.m.Unlock()
conn, url, err := c.connectWithRetry()
if err != nil {
// set error and return
c.logger.Printf("unable to reconnect to %s", c.tunnelAddr)
c.acceptErr = ErrRetryFailed
return
}
if c.session != nil {
_ = c.session.Close()
c.session = nil
}
sessionConfig := wsmux.Config{
// Log: c.logger,
StreamBufferSize: 4 * 1024,
}
c.session = wsmux.Client(conn, sessionConfig)
c.url.Store(url)
c.state = stateRunning
c.logger.Printf("state: running")
c.acceptErr = nil
}
// simple utility to check if client should retry connection
func shouldRetry(r *http.Response) bool {
// retry on connection failures (e.g., server down)
if r == nil {
return true
}
// retry on anything but 4xx or 2xx responses
if r.StatusCode/100 != 4 && r.StatusCode/100 != 2 {
return true
}
return false
}
func isAuthError(r *http.Response) bool {
if r == nil {
return false
}
return r.StatusCode == 401
}