forked from cloudfoundry/noaa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
consumer.go
465 lines (374 loc) · 13.9 KB
/
consumer.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
package noaa
import (
"bufio"
"bytes"
"crypto/tls"
"errors"
"fmt"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"time"
noaa_errors "github.com/cloudfoundry/noaa/errors"
"github.com/cloudfoundry/noaa/events"
"github.com/gogo/protobuf/proto"
"github.com/gorilla/websocket"
)
var (
// KeepAlive sets the interval between keep-alive messages sent by the client to loggregator.
KeepAlive = 25 * time.Second
reconnectTimeout = 500 * time.Millisecond
boundaryRegexp = regexp.MustCompile("boundary=(.*)")
ErrNotOK = errors.New("unknown issue when making HTTP request to Loggregator")
ErrNotFound = ErrNotOK // NotFound isn't an accurate description of how this is used; please use ErrNotOK instead
ErrBadResponse = errors.New("bad server response")
ErrBadRequest = errors.New("bad client request")
ErrLostConnection = errors.New("remote server terminated connection unexpectedly")
)
// Consumer represents the actions that can be performed against traffic controller.
type Consumer struct {
trafficControllerUrl string
tlsConfig *tls.Config
ws *websocket.Conn
callback func()
proxy func(*http.Request) (*url.URL, error)
debugPrinter DebugPrinter
sync.RWMutex
}
// NewConsumer creates a new consumer to a traffic controller.
func NewConsumer(trafficControllerUrl string, tlsConfig *tls.Config, proxy func(*http.Request) (*url.URL, error)) *Consumer {
return &Consumer{trafficControllerUrl: trafficControllerUrl, tlsConfig: tlsConfig, proxy: proxy, debugPrinter: nullDebugPrinter{}}
}
// TailingLogs behaves exactly as TailingLogsWithoutReconnect, except that it retries 5 times if the connection
// to the remote server is lost and returns all errors from each attempt on errorChan.
func (cnsmr *Consumer) TailingLogs(appGuid string, authToken string, outputChan chan<- *events.LogMessage, errorChan chan<- error, stopChan chan struct{}) {
action := func() error {
return cnsmr.TailingLogsWithoutReconnect(appGuid, authToken, outputChan)
}
cnsmr.retryAction(action, errorChan, stopChan)
}
// TailingLogsWithoutReconnect listens indefinitely for log messages only; other event types are dropped.
//
// If you wish to be able to terminate the listen early, run TailingLogsWithoutReconnect in a Goroutine and
// call Close() when you are finished listening.
//
// Messages are presented in the order received from the loggregator server. Chronological or
// other ordering is not guaranteed. It is the responsibility of the consumer of these channels
// to provide any desired sorting mechanism.
func (cnsmr *Consumer) TailingLogsWithoutReconnect(appGuid string, authToken string, outputChan chan<- *events.LogMessage) error {
allEvents := make(chan *events.Envelope)
streamPath := fmt.Sprintf("/apps/%s/stream", appGuid)
errChan := make(chan error)
go func() {
err := cnsmr.stream(streamPath, authToken, allEvents)
errChan <- err
close(errChan)
}()
go func() {
defer close(allEvents)
for event := range allEvents {
if *event.EventType == events.Envelope_LogMessage {
outputChan <- event.GetLogMessage()
}
}
}()
return <-errChan
}
// Stream behaves exactly as StreamWithoutReconnect, except that it retries 5 times if the connection
// to the remote server is lost.
func (cnsmr *Consumer) Stream(appGuid string, authToken string, outputChan chan<- *events.Envelope, errorChan chan<- error, stopChan chan struct{}) {
action := func() error {
return cnsmr.StreamWithoutReconnect(appGuid, authToken, outputChan)
}
cnsmr.retryAction(action, errorChan, stopChan)
}
// StreamWithoutReconnect listens indefinitely for all log and event messages.
//
// If you wish to be able to terminate the listen early, run StreamWithoutReconnect in a Goroutine and
// call Close() when you are finished listening.
//
// Messages are presented in the order received from the loggregator server. Chronological or other ordering
// is not guaranteed. It is the responsibility of the consumer of these channels to provide any desired sorting
// mechanism.
func (cnsmr *Consumer) StreamWithoutReconnect(appGuid string, authToken string, outputChan chan<- *events.Envelope) error {
streamPath := fmt.Sprintf("/apps/%s/stream", appGuid)
return cnsmr.stream(streamPath, authToken, outputChan)
}
// Firehose behaves exactly as FirehoseWithoutReconnect, except that it retries 5 times if the connection
// to the remote server is lost.
func (cnsmr *Consumer) Firehose(subscriptionId string, authToken string, outputChan chan<- *events.Envelope, errorChan chan<- error, stopChan chan struct{}) {
action := func() error {
return cnsmr.FirehoseWithoutReconnect(subscriptionId, authToken, outputChan)
}
cnsmr.retryAction(action, errorChan, stopChan)
}
// FirehoseWithoutReconnect streams all data. All clients with the same subscriptionId will receive a proportionate share of the
// message stream. Each pool of clients will receive the entire stream.
//
// If you wish to be able to terminate the listen early, run FirehoseWithoutReconnect in a Goroutine and
// call Close() when you are finished listening.
//
// Messages are presented in the order received from the loggregator server. Chronological or other ordering
// is not guaranteed. It is the responsibility of the consumer of these channels to provide any desired sorting
// mechanism.
func (cnsmr *Consumer) FirehoseWithoutReconnect(subscriptionId string, authToken string, outputChan chan<- *events.Envelope) error {
streamPath := "/firehose/" + subscriptionId
return cnsmr.stream(streamPath, authToken, outputChan)
}
func (cnsmr *Consumer) stream(streamPath string, authToken string, outputChan chan<- *events.Envelope) error {
var err error
cnsmr.Lock()
cnsmr.ws, err = cnsmr.establishWebsocketConnection(streamPath, authToken)
cnsmr.Unlock()
if err != nil {
return err
}
return cnsmr.listenForMessages(outputChan)
}
func makeError(err error, code int32) *events.Envelope {
return &events.Envelope{
EventType: events.Envelope_Error.Enum(),
Error: &events.Error{
Source: proto.String("NOAA"),
Code: &code,
Message: proto.String(err.Error()),
},
}
}
// RecentLogs connects to traffic controller via its 'recentlogs' http(s) endpoint and returns a slice of recent messages.
// It does not guarantee any order of the messages; they are in the order returned by traffic controller.
//
// The SortRecent method is provided to sort the data returned by this method.
func (cnsmr *Consumer) RecentLogs(appGuid string, authToken string) ([]*events.LogMessage, error) {
envelopes, err := cnsmr.readEnvelopesFromTrafficController(appGuid, authToken, "recentlogs")
if err != nil {
return nil, err
}
messages := make([]*events.LogMessage, 0, 200)
for _, envelope := range envelopes {
messages = append(messages, envelope.GetLogMessage())
}
return messages, err
}
// ContainerMetrics connects to traffic controller via its 'containermetrics' http(s) endpoint and returns the most recent messages for an app.
// The returned metrics will be sorted by InstanceIndex.
func (cnsmr *Consumer) ContainerMetrics(appGuid string, authToken string) ([]*events.ContainerMetric, error) {
envelopes, err := cnsmr.readEnvelopesFromTrafficController(appGuid, authToken, "containermetrics")
if err != nil {
return nil, err
}
messages := make([]*events.ContainerMetric, 0, 200)
for _, envelope := range envelopes {
if envelope.GetEventType() == events.Envelope_LogMessage {
return []*events.ContainerMetric{}, errors.New(fmt.Sprintf("Upstream error: %s", envelope.GetLogMessage().GetMessage()))
}
messages = append(messages, envelope.GetContainerMetric())
}
SortContainerMetrics(messages)
return messages, err
}
func (cnsmr *Consumer) readEnvelopesFromTrafficController(appGuid string, authToken string, endpoint string) ([]*events.Envelope, error) {
trafficControllerUrl, err := url.ParseRequestURI(cnsmr.trafficControllerUrl)
if err != nil {
return nil, err
}
scheme := "https"
if trafficControllerUrl.Scheme == "ws" {
scheme = "http"
}
recentPath := fmt.Sprintf("%s://%s/apps/%s/%s", scheme, trafficControllerUrl.Host, appGuid, endpoint)
transport := &http.Transport{Proxy: cnsmr.proxy, TLSClientConfig: cnsmr.tlsConfig}
client := &http.Client{Transport: transport}
req, _ := http.NewRequest("GET", recentPath, nil)
req.Header.Set("Authorization", authToken)
resp, err := client.Do(req)
if err != nil {
return nil, errors.New(fmt.Sprintf("Error dialing traffic controller server: %s.\nPlease ask your Cloud Foundry Operator to check the platform configuration (traffic controller endpoint is %s).", err.Error(), cnsmr.trafficControllerUrl))
}
defer resp.Body.Close()
err = checkForErrors(resp)
if err != nil {
return nil, err
}
reader, err := getMultipartReader(resp)
if err != nil {
return nil, err
}
var envelopes []*events.Envelope
var buffer bytes.Buffer
for part, loopErr := reader.NextPart(); loopErr == nil; part, loopErr = reader.NextPart() {
buffer.Reset()
_, err := buffer.ReadFrom(part)
if err != nil {
break
}
envelope := new(events.Envelope)
proto.Unmarshal(buffer.Bytes(), envelope)
envelopes = append(envelopes, envelope)
}
return envelopes, nil
}
func checkForErrors(resp *http.Response) error {
if resp.StatusCode == http.StatusUnauthorized {
data, _ := ioutil.ReadAll(resp.Body)
return noaa_errors.NewUnauthorizedError(string(data))
}
if resp.StatusCode == http.StatusBadRequest {
return ErrBadRequest
}
if resp.StatusCode != http.StatusOK {
return ErrNotOK
}
return nil
}
func getMultipartReader(resp *http.Response) (*multipart.Reader, error) {
contentType := resp.Header.Get("Content-Type")
if len(strings.TrimSpace(contentType)) == 0 {
return nil, ErrBadResponse
}
matches := boundaryRegexp.FindStringSubmatch(contentType)
if len(matches) != 2 || len(strings.TrimSpace(matches[1])) == 0 {
return nil, ErrBadResponse
}
reader := multipart.NewReader(resp.Body, matches[1])
return reader, nil
}
// Close terminates the websocket connection to traffic controller.
func (cnsmr *Consumer) Close() error {
cnsmr.Lock()
defer cnsmr.Unlock()
if cnsmr.ws == nil {
return errors.New("connection does not exist")
}
cnsmr.ws.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Time{})
return cnsmr.ws.Close()
}
// SetOnConnectCallback sets a callback function to be called with the websocket connection is established.
func (cnsmr *Consumer) SetOnConnectCallback(cb func()) {
cnsmr.callback = cb
}
// SetDebugPrinter enables logging of the websocket handshake.
func (cnsmr *Consumer) SetDebugPrinter(debugPrinter DebugPrinter) {
cnsmr.debugPrinter = debugPrinter
}
func (cnsmr *Consumer) listenForMessages(msgChan chan<- *events.Envelope) error {
defer cnsmr.ws.Close()
for {
_, data, err := cnsmr.ws.ReadMessage()
if err != nil {
return err
}
envelope := &events.Envelope{}
err = proto.Unmarshal(data, envelope)
if err != nil {
continue
}
msgChan <- envelope
}
}
func headersString(header http.Header) string {
var result string
for name, values := range header {
result += name + ": " + strings.Join(values, ", ") + "\n"
}
return result
}
func (cnsmr *Consumer) establishWebsocketConnection(path string, authToken string) (*websocket.Conn, error) {
header := http.Header{"Origin": []string{"http://localhost"}, "Authorization": []string{authToken}}
dialer := websocket.Dialer{NetDial: cnsmr.proxyDial, TLSClientConfig: cnsmr.tlsConfig}
url := cnsmr.trafficControllerUrl + path
cnsmr.debugPrinter.Print("WEBSOCKET REQUEST:",
"GET "+path+" HTTP/1.1\n"+
"Host: "+cnsmr.trafficControllerUrl+"\n"+
"Upgrade: websocket\nConnection: Upgrade\nSec-WebSocket-Version: 13\nSec-WebSocket-Key: [HIDDEN]\n"+
headersString(header))
ws, resp, err := dialer.Dial(url, header)
if resp != nil {
cnsmr.debugPrinter.Print("WEBSOCKET RESPONSE:",
resp.Proto+" "+resp.Status+"\n"+
headersString(resp.Header))
}
if resp != nil && resp.StatusCode == http.StatusUnauthorized {
bodyData, _ := ioutil.ReadAll(resp.Body)
err = noaa_errors.NewUnauthorizedError(string(bodyData))
return ws, err
}
if err == nil && cnsmr.callback != nil {
cnsmr.callback()
}
if err != nil {
return nil, errors.New(fmt.Sprintf("Error dialing traffic controller server: %s.\nPlease ask your Cloud Foundry Operator to check the platform configuration (traffic controller is %s).", err.Error(), cnsmr.trafficControllerUrl))
}
return ws, err
}
func (cnsmr *Consumer) proxyDial(network, addr string) (net.Conn, error) {
targetUrl, err := url.Parse("http://" + addr)
if err != nil {
return nil, err
}
proxy := cnsmr.proxy
if proxy == nil {
proxy = http.ProxyFromEnvironment
}
proxyUrl, err := proxy(&http.Request{URL: targetUrl})
if err != nil {
return nil, err
}
if proxyUrl == nil {
return net.Dial(network, addr)
}
proxyConn, err := net.Dial(network, proxyUrl.Host)
if err != nil {
return nil, err
}
connectReq := &http.Request{
Method: "CONNECT",
URL: targetUrl,
Host: targetUrl.Host,
Header: make(http.Header),
}
connectReq.Write(proxyConn)
connectResp, err := http.ReadResponse(bufio.NewReader(proxyConn), connectReq)
if err != nil {
proxyConn.Close()
return nil, err
}
if connectResp.StatusCode != http.StatusOK {
f := strings.SplitN(connectResp.Status, " ", 2)
proxyConn.Close()
return nil, errors.New(f[1])
}
return proxyConn, nil
}
func (cnsmr *Consumer) retryAction(action func() error, errorChan chan<- error, stopChan chan struct{}) {
reconnectAttempts := 0
oldConnectCallback := cnsmr.callback
defer func() { cnsmr.callback = oldConnectCallback }()
defer close(errorChan)
cnsmr.callback = func() {
reconnectAttempts = 0
if oldConnectCallback != nil {
oldConnectCallback()
}
}
for ; reconnectAttempts < 5; reconnectAttempts++ {
errChan := make(chan error)
select {
case <-stopChan:
cnsmr.Close()
return
default:
}
go func() {
errChan <- action()
}()
err := <-errChan
errorChan <- err
time.Sleep(reconnectTimeout)
}
}