Debian Codegraph @

api/v0/messenger/http_transporter.go

raw symbols SCIP
1 /**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package messenger
20
21 import (
22 "bytes"
23 "crypto/tls"
24 "encoding/hex"
25 "errors"
26 "fmt"
27 "io"
28 "io/ioutil"
29 "net"
30 "net/http"
31 "os"
32 "strings"
33 "sync"
34 "time"
35
36 log "github.com/golang/glog"
37 "github.com/mesos/mesos-go/api/v0/upid"
38 "golang.org/x/net/context"
39 )
40
41 const (
42 DefaultReadTimeout = 10 * time.Second
43 DefaultWriteTimeout = 10 * time.Second
44 )
45
46 var (
47 ReadTimeout = DefaultReadTimeout
48 WriteTimeout = DefaultWriteTimeout
49
50 discardOnStopError = fmt.Errorf("discarding message because transport is shutting down")
51 errNotStarted = errors.New("HTTP transport has not been started")
52 errTerminal = errors.New("HTTP transport is terminated")
53 errAlreadyRunning = errors.New("HTTP transport is already running")
54
55 httpTransport = http.Transport{
56 Dial: (&net.Dialer{
57 Timeout: 10 * time.Second,
58 KeepAlive: 30 * time.Second,
59 }).Dial,
60 TLSHandshakeTimeout: 10 * time.Second,
61 ResponseHeaderTimeout: DefaultReadTimeout,
62 }
63
64 // HttpClient is used for sending messages to remote processes
65 HttpClient = http.Client{
66 Timeout: DefaultReadTimeout,
67 }
68 )
69
70 // httpTransporter is a subset of the Transporter interface
71 type httpTransporter interface {
72 Send(ctx context.Context, msg *Message) error
73 Recv() (*Message, error)
74 Install(messageName string)
75 Start() (upid.UPID, <-chan error)
76 Stop(graceful bool) error
77 }
78
79 type notStartedState struct {
80 h *HTTPTransporter
81 }
82
83 type stoppedState struct{}
84
85 type runningState struct {
86 *notStartedState
87 }
88
89 /* -- not-started state */
90
91 func (s *notStartedState) Send(ctx context.Context, msg *Message) error { return errNotStarted }
92 func (s *notStartedState) Recv() (*Message, error) { return nil, errNotStarted }
93 func (s *notStartedState) Stop(graceful bool) error { return errNotStarted }
94 func (s *notStartedState) Install(messageName string) { s.h.install(messageName) }
95 func (s *notStartedState) Start() (upid.UPID, <-chan error) {
96 s.h.state = &runningState{s}
97 return s.h.start()
98 }
99
100 /* -- stopped state */
101
102 func (s *stoppedState) Send(ctx context.Context, msg *Message) error { return errTerminal }
103 func (s *stoppedState) Recv() (*Message, error) { return nil, errTerminal }
104 func (s *stoppedState) Stop(graceful bool) error { return errTerminal }
105 func (s *stoppedState) Install(messageName string) {}
106 func (s *stoppedState) Start() (upid.UPID, <-chan error) {
107 ch := make(chan error, 1)
108 ch <- errTerminal
109 return upid.UPID{}, ch
110 }
111
112 /* -- running state */
113
114 func (s *runningState) Send(ctx context.Context, msg *Message) error { return s.h.send(ctx, msg) }
115 func (s *runningState) Recv() (*Message, error) { return s.h.recv() }
116 func (s *runningState) Stop(graceful bool) error {
117 s.h.state = &stoppedState{}
118 return s.h.stop(graceful)
119 }
120 func (s *runningState) Start() (upid.UPID, <-chan error) {
121 ch := make(chan error, 1)
122 ch <- errAlreadyRunning
123 return upid.UPID{}, ch
124 }
125
126 // httpOpt is a functional option type
127 type httpOpt func(*HTTPTransporter)
128
129 // HTTPTransporter implements the interfaces of the Transporter.
130 type HTTPTransporter struct {
131 // If the host is empty("") then it will listen on localhost.
132 // If the port is empty("") then it will listen on random port.
133 upid upid.UPID
134 listener net.Listener // TODO(yifan): Change to TCPListener.
135 mux *http.ServeMux
136 tr *http.Transport
137 client *http.Client
138 messageQueue chan *Message
139 address net.IP // optional binding address
140 shouldQuit chan struct{}
141 stateLock sync.RWMutex // protect lifecycle (start/stop) funcs
142 state httpTransporter
143 server *http.Server
144 }
145
146 // NewHTTPTransporter creates a new http transporter with an optional binding address.
147 func NewHTTPTransporter(upid upid.UPID, address net.IP, opts ...httpOpt) *HTTPTransporter {
148 transport := httpTransport
149 client := HttpClient
150 client.Transport = &transport
151 mux := http.NewServeMux()
152
153 result := &HTTPTransporter{
154 upid: upid,
155 messageQueue: make(chan *Message, defaultQueueSize),
156 mux: mux,
157 client: &client,
158 tr: &transport,
159 address: address,
160 shouldQuit: make(chan struct{}),
161 server: &http.Server{
162 ReadTimeout: ReadTimeout,
163 WriteTimeout: WriteTimeout,
164 Handler: mux,
165 },
166 }
167 for _, f := range opts {
168 f(result)
169 }
170 result.state = &notStartedState{result}
171 return result
172 }
173
174 func ServerTLSConfig(config *tls.Config, nextProto map[string]func(*http.Server, *tls.Conn, http.Handler)) httpOpt {
175 return func(transport *HTTPTransporter) {
176 transport.server.TLSConfig = config
177 transport.server.TLSNextProto = nextProto
178 }
179 }
180
181 func ClientTLSConfig(config *tls.Config, handshakeTimeout time.Duration) httpOpt {
182 return func(transport *HTTPTransporter) {
183 transport.tr.TLSClientConfig = config
184 transport.tr.TLSHandshakeTimeout = handshakeTimeout
185 }
186 }
187
188 func (t *HTTPTransporter) getState() httpTransporter {
189 t.stateLock.RLock()
190 defer t.stateLock.RUnlock()
191 return t.state
192 }
193
194 // Send sends the message to its specified upid.
195 func (t *HTTPTransporter) Send(ctx context.Context, msg *Message) (sendError error) {
196 return t.getState().Send(ctx, msg)
197 }
198
199 type mesosError struct {
200 errorCode int
201 upid string
202 uri string
203 status string
204 }
205
206 func (e *mesosError) Error() string {
207 return fmt.Sprintf("master %s rejected %s, returned status %q",
208 e.upid, e.uri, e.status)
209 }
210
211 type networkError struct {
212 cause error
213 }
214
215 func (e *networkError) Error() string {
216 return e.cause.Error()
217 }
218
219 // send delivers a message to a mesos component via HTTP, returns a mesosError if the
220 // communication with the remote process was successful but rejected. A networkError
221 // error indicates that communication with the remote process failed at the network layer.
222 func (t *HTTPTransporter) send(ctx context.Context, msg *Message) (sendError error) {
223 log.V(2).Infof("Sending message to %v via http\n", msg.UPID)
224 req, err := t.makeLibprocessRequest(msg)
225 if err != nil {
226 return err
227 }
228
229 return t.httpDo(ctx, req, func(resp *http.Response, err error) error {
230 if err != nil {
231 log.V(1).Infof("Failed to POST: %v\n", err)
232 return &networkError{err}
233 }
234 defer resp.Body.Close()
235
236 // ensure master acknowledgement.
237 if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusAccepted) {
238 return &mesosError{
239 errorCode: resp.StatusCode,
240 upid: msg.UPID.String(),
241 uri: msg.RequestURI(),
242 status: resp.Status,
243 }
244 }
245 return nil
246 })
247 }
248
249 func (t *HTTPTransporter) httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error {
250 select {
251 case <-ctx.Done():
252 return ctx.Err()
253 case <-t.shouldQuit:
254 return discardOnStopError
255 default: // continue
256 }
257
258 c := make(chan error, 1)
259 go func() { c <- f(t.client.Do(req)) }()
260 select {
261 case <-ctx.Done():
262 t.tr.CancelRequest(req)
263 <-c // Wait for f to return.
264 return ctx.Err()
265 case err := <-c:
266 return err
267 case <-t.shouldQuit:
268 t.tr.CancelRequest(req)
269 <-c // Wait for f to return.
270 return discardOnStopError
271 }
272 }
273
274 // Recv returns the message, one at a time.
275 func (t *HTTPTransporter) Recv() (*Message, error) {
276 return t.getState().Recv()
277 }
278
279 func (t *HTTPTransporter) recv() (*Message, error) {
280 select {
281 default:
282 select {
283 case msg := <-t.messageQueue:
284 return msg, nil
285 case <-t.shouldQuit:
286 }
287 case <-t.shouldQuit:
288 }
289 return nil, discardOnStopError
290 }
291
292 // Install the request URI according to the message's name.
293 func (t *HTTPTransporter) Install(msgName string) {
294 t.getState().Install(msgName)
295 }
296
297 func (t *HTTPTransporter) install(msgName string) {
298 requestURI := fmt.Sprintf("/%s/%s", t.upid.ID, msgName)
299 t.mux.HandleFunc(requestURI, t.messageDecoder)
300 }
301
302 type loggedListener struct {
303 delegate net.Listener
304 done <-chan struct{}
305 }
306
307 func (l *loggedListener) Accept() (c net.Conn, err error) {
308 c, err = l.delegate.Accept()
309 if c != nil {
310 log.Infoln("accepted connection from", c.RemoteAddr())
311 c = logConnection(c)
312 } else if err != nil {
313 select {
314 case <-l.done:
315 default:
316 log.Errorln("failed to accept connection:", err.Error())
317 }
318 }
319 return
320 }
321
322 func (l *loggedListener) Close() (err error) {
323 err = l.delegate.Close()
324 if err != nil {
325 select {
326 case <-l.done:
327 default:
328 log.Errorln("error closing listener:", err.Error())
329 }
330 } else {
331 log.Infoln("closed listener")
332 }
333 return
334 }
335
336 func (l *loggedListener) Addr() net.Addr { return l.delegate.Addr() }
337
338 func logConnection(c net.Conn) net.Conn {
339 w := hex.Dumper(os.Stdout)
340 r := io.TeeReader(c, w)
341 return &loggedConnection{
342 Conn: c,
343 reader: r,
344 }
345 }
346
347 type loggedConnection struct {
348 net.Conn
349 reader io.Reader
350 }
351
352 func (c *loggedConnection) Read(b []byte) (int, error) {
353 return c.reader.Read(b)
354 }
355
356 // Listen starts listen on UPID. If UPID is empty, the transporter
357 // will listen on a random port, and then fill the UPID with the
358 // host:port it is listening.
359 func (t *HTTPTransporter) listen() error {
360 var host string
361 if t.address != nil {
362 host = t.address.String()
363 } else {
364 host = t.upid.Host
365 }
366
367 var port string
368 if t.upid.Port != "" {
369 port = t.upid.Port
370 } else {
371 port = "0"
372 }
373
374 // NOTE: Explicitly specifies IPv4 because Libprocess
375 // only supports IPv4 for now.
376 ln, err := net.Listen("tcp4", net.JoinHostPort(host, port))
377 if err != nil {
378 log.Errorf("HTTPTransporter failed to listen: %v\n", err)
379 return err
380 }
381 // Save the host:port in case they are not specified in upid.
382 host, port, _ = net.SplitHostPort(ln.Addr().String())
383 log.Infoln("listening on", host, "port", port)
384
385 if len(t.upid.Host) == 0 {
386 t.upid.Host = host
387 }
388
389 if len(t.upid.Port) == 0 || t.upid.Port == "0" {
390 t.upid.Port = port
391 }
392
393 if log.V(3) {
394 t.listener = &loggedListener{delegate: ln, done: t.shouldQuit}
395 } else {
396 t.listener = ln
397 }
398 return nil
399 }
400
401 // Start starts the http transporter
402 func (t *HTTPTransporter) Start() (upid.UPID, <-chan error) {
403 t.stateLock.Lock()
404 defer t.stateLock.Unlock()
405 return t.state.Start()
406 }
407
408 // start expects to be guarded by stateLock
409 func (t *HTTPTransporter) start() (upid.UPID, <-chan error) {
410 ch := make(chan error, 1)
411 if err := t.listen(); err != nil {
412 ch <- err
413 return upid.UPID{}, ch
414 }
415
416 // TODO(yifan): Set read/write deadline.
417 go func() {
418 err := t.server.Serve(t.listener)
419 select {
420 case <-t.shouldQuit:
421 log.V(1).Infof("HTTP server stopped because of shutdown")
422 ch <- nil
423 default:
424 if err != nil && log.V(1) {
425 log.Errorln("HTTP server stopped with error", err.Error())
426 } else {
427 log.V(1).Infof("HTTP server stopped")
428 }
429 ch <- err
430 t.Stop(false)
431 }
432 }()
433 return t.upid, ch
434 }
435
436 // Stop stops the http transporter by closing the listener.
437 func (t *HTTPTransporter) Stop(graceful bool) error {
438 t.stateLock.Lock()
439 defer t.stateLock.Unlock()
440 return t.state.Stop(graceful)
441 }
442
443 // stop expects to be guarded by stateLock
444 func (t *HTTPTransporter) stop(graceful bool) error {
445 close(t.shouldQuit)
446
447 log.Info("stopping HTTP transport")
448
449 //TODO(jdef) if graceful, wait for pending requests to terminate
450
451 err := t.listener.Close()
452 return err
453 }
454
455 // UPID returns the upid of the transporter.
456 func (t *HTTPTransporter) UPID() upid.UPID {
457 t.stateLock.Lock()
458 defer t.stateLock.Unlock()
459 return t.upid
460 }
461
462 func (t *HTTPTransporter) messageDecoder(w http.ResponseWriter, r *http.Request) {
463 // Verify it's a libprocess request.
464 from, err := getLibprocessFrom(r)
465 if err != nil {
466 log.Errorf("Ignoring the request, because it's not a libprocess request: %v\n", err)
467 w.WriteHeader(http.StatusBadRequest)
468 return
469 }
470 decoder := DecodeHTTP(w, r)
471 defer decoder.Cancel(true)
472
473 t.processRequests(from, decoder.Requests())
474
475 // log an error if there's one waiting, otherwise move on
476 select {
477 case err, ok := <-decoder.Err():
478 if ok {
479 log.Errorf("failed to decode HTTP message: %v", err)
480 }
481 default:
482 }
483 }
484
485 func (t *HTTPTransporter) processRequests(from *upid.UPID, incoming <-chan *Request) {
486 for {
487 select {
488 case r, ok := <-incoming:
489 if !ok || !t.processOneRequest(from, r) {
490 return
491 }
492 case <-t.shouldQuit:
493 return
494 }
495 }
496 }
497
498 func (t *HTTPTransporter) processOneRequest(from *upid.UPID, request *Request) (keepGoing bool) {
499 // regardless of whether we write a Response we must close this chan
500 defer close(request.response)
501 keepGoing = true
502
503 //TODO(jdef) this is probably inefficient given the current implementation of the
504 // decoder: no need to make another copy of data that's already competely buffered
505 data, err := ioutil.ReadAll(request.Body)
506 if err != nil {
507 // this is unlikely given the current implementation of the decoder:
508 // the body has been completely buffered in memory already
509 log.Errorf("failed to read HTTP body: %v", err)
510 return
511 }
512 log.V(2).Infof("Receiving %q %v from %v, length %v", request.Method, request.URL, from, len(data))
513 m := &Message{
514 UPID: from,
515 Name: extractNameFromRequestURI(request.RequestURI),
516 Bytes: data,
517 }
518
519 // deterministic behavior and output..
520 select {
521 case <-t.shouldQuit:
522 keepGoing = false
523 select {
524 case t.messageQueue <- m:
525 default:
526 }
527 case t.messageQueue <- m:
528 select {
529 case <-t.shouldQuit:
530 keepGoing = false
531 default:
532 }
533 }
534
535 // Only send back an HTTP response if this isn't from libprocess
536 // (which we determine by looking at the User-Agent). This is
537 // necessary because older versions of libprocess would try and
538 // recv the data and parse it as an HTTP request which would
539 // fail thus causing the socket to get closed (but now
540 // libprocess will ignore responses, see ignore_data).
541 // see https://github.com/apache/mesos/blob/adecbfa6a216815bd7dc7d26e721c4c87e465c30/3rdparty/libprocess/src/process.cpp#L2192
542 if _, ok := parseLibprocessAgent(request.Header); !ok {
543 log.V(2).Infof("not libprocess agent, sending a 202")
544 request.response <- Response{
545 code: 202,
546 reason: "Accepted",
547 } // should never block
548 }
549 return
550 }
551
552 func (t *HTTPTransporter) makeLibprocessRequest(msg *Message) (*http.Request, error) {
553 if msg.UPID == nil {
554 panic(fmt.Sprintf("message is missing UPID: %+v", msg))
555 }
556 hostport := net.JoinHostPort(msg.UPID.Host, msg.UPID.Port)
557 targetURL := fmt.Sprintf("http://%s%s", hostport, msg.RequestURI())
558 log.V(2).Infof("libproc target URL %s", targetURL)
559 req, err := http.NewRequest("POST", targetURL, bytes.NewReader(msg.Bytes))
560 if err != nil {
561 log.V(1).Infof("Failed to create request: %v\n", err)
562 return nil, err
563 }
564 if !msg.isV1API() {
565 req.Header.Add("Libprocess-From", t.upid.String())
566 req.Header.Add("Connection", "Keep-Alive")
567 }
568 req.Header.Add("Content-Type", "application/x-protobuf")
569
570 return req, nil
571 }
572
573 func getLibprocessFrom(r *http.Request) (*upid.UPID, error) {
574 if r.Method != "POST" {
575 return nil, fmt.Errorf("Not a POST request")
576 }
577 if agent, ok := parseLibprocessAgent(r.Header); ok {
578 return upid.Parse(agent)
579 }
580 lf, ok := r.Header["Libprocess-From"]
581 if ok {
582 // TODO(yifan): Just take the first field for now.
583 return upid.Parse(lf[0])
584 }
585 return nil, fmt.Errorf("Cannot find 'User-Agent' or 'Libprocess-From'")
586 }
587
588 func parseLibprocessAgent(h http.Header) (string, bool) {
589 const prefix = "libprocess/"
590 if ua, ok := h["User-Agent"]; ok {
591 for _, agent := range ua {
592 if strings.HasPrefix(agent, prefix) {
593 return agent[len(prefix):], true
594 }
595 }
596 }
597 return "", false
598 }