forked from aws/amazon-ecs-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
364 lines (321 loc) · 12 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
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
// Copyright 2014-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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 wsclient wraps the generated aws-sdk-go client to provide marshalling
// and unmarshalling of data over a websocket connection in the format expected
// by backend. It allows for bidirectional communication and acts as both a
// client-and-server in terms of requests, but only as a client in terms of
// connecting.
package wsclient
import (
"bufio"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"reflect"
"strings"
"time"
"github.com/aws/amazon-ecs-agent/agent/utils"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
"github.com/cihub/seelog"
"github.com/gorilla/websocket"
)
const (
// ServiceName defines the service name for the agent. This is used to sign messages
// that are sent to the backend.
ServiceName = "ecs"
// wsConnectTimeout specifies the default connection timeout to the backend.
wsConnectTimeout = 30 * time.Second
// readBufSize is the size of the read buffer for the ws connection.
readBufSize = 4096
// writeBufSize is the size of the write buffer for the ws connection.
writeBufSize = 32768
)
// ReceivedMessage is the intermediate message used to unmarshal a
// message from backend
type ReceivedMessage struct {
Type string `json:"type"`
Message json.RawMessage `json:"message"`
}
// RequestMessage is the intermediate message marshalled to send to backend.
type RequestMessage struct {
Type string `json:"type"`
Message json.RawMessage `json:"message"`
}
// WebsocketConn specifies the subset of gorilla/websocket's
// connection's methods that this client uses.
type WebsocketConn interface {
WriteMessage(messageType int, data []byte) error
ReadMessage() (messageType int, data []byte, err error)
Close() error
}
// RequestHandler would be func(*ecsacs.T for T in ecsacs.*) to be more proper, but it needs
// to be interface{} to properly capture that
type RequestHandler interface{}
// ClientServer is a combined client and server for the backend websocket connection
type ClientServer interface {
AddRequestHandler(RequestHandler)
// SetAnyRequestHandler takes a function with the signature 'func(i
// interface{})' and calls it with every message the server passes down.
// Only a single 'AnyRequestHandler' will be active at a given time for a
// ClientServer
SetAnyRequestHandler(RequestHandler)
MakeRequest(input interface{}) error
Connect() error
Disconnect(...interface{}) error
Serve() error
io.Closer
}
//go:generate mockgen.sh github.com/aws/amazon-ecs-agent/agent/wsclient ClientServer mock/$GOFILE
// ClientServerImpl wraps commonly used methods defined in ClientServer interface.
type ClientServerImpl struct {
AcceptInvalidCert bool
Conn WebsocketConn
CredentialProvider *credentials.Credentials
Region string
// RequestHandlers is a map from message types to handler functions of the
// form:
// "FooMessage": func(message *ecsacs.FooMessage)
RequestHandlers map[string]RequestHandler
// AnyRequestHandler is a request handler that, if set, is called on every
// message with said message. It will be called before a RequestHandler is
// called. It must take a single interface{} argument.
AnyRequestHandler RequestHandler
// URL is the full url to the backend, including path, querystring, and so on.
URL string
ClientServer
ServiceError
TypeDecoder
}
// Connect opens a connection to the backend and upgrades it to a websocket. Calls to
// 'MakeRequest' can be made after calling this, but responss will not be
// receivable until 'Serve' is also called.
func (cs *ClientServerImpl) Connect() error {
parsedURL, err := url.Parse(cs.URL)
if err != nil {
return err
}
// NewRequest never returns an error if the url parses and we just verified
// it did above
request, _ := http.NewRequest("GET", cs.URL, nil)
// Sign the request; we'll send its headers via the websocket client which includes the signature
utils.SignHTTPRequest(request, cs.Region, ServiceName, cs.CredentialProvider, nil)
wsConn, err := cs.websocketConn(parsedURL, request)
if err != nil {
return err
}
websocketConn, httpResponse, err := websocket.NewClient(wsConn, parsedURL, request.Header, readBufSize, writeBufSize)
if httpResponse != nil {
defer httpResponse.Body.Close()
}
if err != nil {
defer wsConn.Close()
var resp []byte
if httpResponse != nil {
var readErr error
resp, readErr = ioutil.ReadAll(httpResponse.Body)
if readErr != nil {
return fmt.Errorf("Unable to read websocket connection: " + readErr.Error() + ", " + err.Error())
}
// If there's a response, we can try to unmarshal it into one of the
// modeled error types
possibleError, _, decodeErr := DecodeData(resp, cs.TypeDecoder)
if decodeErr == nil {
return cs.NewError(possibleError)
}
}
seelog.Warnf("Error creating a websocket client: %v", err)
return fmt.Errorf(string(resp) + ", " + err.Error())
}
cs.Conn = websocketConn
return nil
}
// Disconnect disconnects the connection
func (cs *ClientServerImpl) Disconnect(...interface{}) error {
if cs.Conn != nil {
return cs.Conn.Close()
}
return fmt.Errorf("No Connection to close")
}
// AddRequestHandler adds a request handler to this client.
// A request handler *must* be a function taking a single argument, and that
// argument *must* be a pointer to a recognized 'ecsacs' struct.
// E.g. if you desired to handle messages from acs of type 'FooMessage', you
// would pass the following handler in:
// func(message *ecsacs.FooMessage)
// This function will panic if the passed in function does not have one pointer
// argument or the argument is not a recognized type.
// Additionally, the request handler will block processing of further messages
// on this connection so it's important that it return quickly.
func (cs *ClientServerImpl) AddRequestHandler(f RequestHandler) {
firstArg := reflect.TypeOf(f).In(0)
firstArgTypeStr := firstArg.Elem().Name()
recognizedTypes := cs.GetRecognizedTypes()
_, ok := recognizedTypes[firstArgTypeStr]
if !ok {
panic("AddRequestHandler called with invalid function; argument type not recognized: " + firstArgTypeStr)
}
cs.RequestHandlers[firstArgTypeStr] = f
}
func (cs *ClientServerImpl) SetAnyRequestHandler(f RequestHandler) {
cs.AnyRequestHandler = f
}
// MakeRequest makes a request using the given input. Note, the input *MUST* be
// a pointer to a valid backend type that this client recognises
func (cs *ClientServerImpl) MakeRequest(input interface{}) error {
send, err := cs.CreateRequestMessage(input)
if err != nil {
return err
}
// Over the wire we send something like
// {"type":"AckRequest","message":{"messageId":"xyz"}}
return cs.Conn.WriteMessage(websocket.TextMessage, send)
}
// ConsumeMessages reads messages from the websocket connection and handles read
// messages from an active connection.
func (cs *ClientServerImpl) ConsumeMessages() error {
var err error
for {
messageType, message, cerr := cs.Conn.ReadMessage()
err = cerr
if err != nil {
if err != io.EOF && err != io.ErrUnexpectedEOF {
if message != nil {
seelog.Errorf("Error getting message from ws backend: %v, message: %v", err, string(message))
} else {
seelog.Errorf("Error getting message from ws backend: %v", err)
}
}
break
}
if messageType != websocket.TextMessage {
seelog.Errorf("Unexpected messageType: %s", messageType)
// maybe not fatal though, we'll try to process it anyways
}
seelog.Debug("Got a message from websocket")
cs.handleMessage(message)
}
return err
}
// CreateRequestMessage creates the request json message using the given input.
// Note, the input *MUST* be a pointer to a valid backend type that this
// client recognises.
func (cs *ClientServerImpl) CreateRequestMessage(input interface{}) ([]byte, error) {
msg := &RequestMessage{}
recognizedTypes := cs.GetRecognizedTypes()
for typeStr, typeVal := range recognizedTypes {
if reflect.TypeOf(input) == reflect.PtrTo(typeVal) {
msg.Type = typeStr
break
}
}
if msg.Type == "" {
return nil, &UnrecognizedWSRequestType{reflect.TypeOf(input).String()}
}
messageData, err := jsonutil.BuildJSON(input)
if err != nil {
return nil, &NotMarshallableWSRequest{msg.Type, err}
}
msg.Message = json.RawMessage(messageData)
send, err := json.Marshal(msg)
if err != nil {
return nil, &NotMarshallableWSRequest{msg.Type, err}
}
return send, nil
}
// handleMessage dispatches a message to the correct 'requestHandler' for its
// type. If no request handler is found, the message is discarded.
func (cs *ClientServerImpl) handleMessage(data []byte) {
typedMessage, typeStr, err := DecodeData(data, cs.TypeDecoder)
if err != nil {
seelog.Warnf("Unable to handle message from backend: %v", err)
return
}
seelog.Debugf("Received message of type: %s", typeStr)
if cs.AnyRequestHandler != nil {
reflect.ValueOf(cs.AnyRequestHandler).Call([]reflect.Value{reflect.ValueOf(typedMessage)})
}
if handler, ok := cs.RequestHandlers[typeStr]; ok {
reflect.ValueOf(handler).Call([]reflect.Value{reflect.ValueOf(typedMessage)})
} else {
seelog.Infof("No handler for message type: %s", typeStr)
}
}
// websocketConn establishes a connection to the given URL, respecting any proxy configuration in the environment.
// A standard proxying setup involves setting the following environment variables
// (may be listed in /etc/ecs/ecs.config if using ecs-init):
// HTTP_PROXY=http://<your-proxy>/ # HTTPS_PROXY may be set instead or additionally
// NO_PROXY=169.254.169.254,/var/run/docker.sock # Directly connect to metadata service and docker socket
func (cs *ClientServerImpl) websocketConn(parsedURL *url.URL, request *http.Request) (net.Conn, error) {
proxyURL, err := http.ProxyFromEnvironment(request)
if err != nil {
return nil, err
}
// url.Host might not have the port, but tls.Dial needs it
targetHost := parsedURL.Host
if !strings.Contains(targetHost, ":") {
targetHost += ":443"
}
targetHostname, _, err := net.SplitHostPort(targetHost)
if err != nil {
return nil, err
}
tlsConfig := tls.Config{ServerName: targetHostname, InsecureSkipVerify: cs.AcceptInvalidCert}
timeoutDialer := &net.Dialer{Timeout: wsConnectTimeout}
if proxyURL == nil {
// directly connect
seelog.Infof("Creating poll dialer, host: %s", parsedURL.Host)
return tls.DialWithDialer(timeoutDialer, "tcp", targetHost, &tlsConfig)
}
// connect via proxy
seelog.Infof("Creating poll dialer, proxy: %s", proxyURL.Host)
plainConn, err := timeoutDialer.Dial("tcp", proxyURL.Host)
if err != nil {
return nil, err
}
// TLS over an HTTP proxy via CONNECT taken from: https://golang.org/src/net/http/transport.go
connectReq := &http.Request{
Method: "CONNECT",
URL: &url.URL{Opaque: targetHost},
Host: targetHost,
Header: make(http.Header),
}
if proxyUser := proxyURL.User; proxyUser != nil {
username := proxyUser.Username()
password, _ := proxyUser.Password()
auth := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
connectReq.Header.Set("Proxy-Authorization", "Basic "+auth)
}
connectReq.Write(plainConn)
// Read response.
// Okay to use and discard buffered reader here, because
// TLS server will not speak until spoken to.
br := bufio.NewReader(plainConn)
resp, err := http.ReadResponse(br, connectReq)
if err != nil {
plainConn.Close()
return nil, err
}
if resp.StatusCode != 200 {
plainConn.Close()
return nil, fmt.Errorf(resp.Status)
}
tlsConn := tls.Client(plainConn, &tlsConfig)
return tlsConn, nil
}