Debian Codegraph @

api/v1/lib/httpcli/http.go

raw symbols SCIP
1 package httpcli
2
3 import (
4 "bytes"
5 "context"
6 "crypto/tls"
7 "fmt"
8 "io"
9 "io/ioutil"
10 "net"
11 "net/http"
12 "sync"
13 "time"
14
15 "github.com/mesos/mesos-go/api/v1/lib"
16 "github.com/mesos/mesos-go/api/v1/lib/client"
17 logger "github.com/mesos/mesos-go/api/v1/lib/debug"
18 "github.com/mesos/mesos-go/api/v1/lib/encoding"
19 "github.com/mesos/mesos-go/api/v1/lib/encoding/codecs"
20 "github.com/mesos/mesos-go/api/v1/lib/encoding/framing"
21 "github.com/mesos/mesos-go/api/v1/lib/httpcli/apierrors"
22 "github.com/mesos/mesos-go/api/v1/lib/recordio"
23 )
24
25 func noRedirect(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }
26
27 // ProtocolError is returned when we receive a response from Mesos that is outside of the HTTP API specification.
28 // Receipt of the following will yield protocol errors:
29 // - any unexpected non-error HTTP response codes (e.g. 199)
30 // - any unexpected Content-Type
31 type ProtocolError string
32
33 // Error implements error interface
34 func (pe ProtocolError) Error() string { return string(pe) }
35
36 const (
37 debug = logger.Logger(false)
38 mediaTypeRecordIO = encoding.MediaType("application/recordio")
39 )
40
41 // DoFunc sends an HTTP request and returns an HTTP response.
42 //
43 // An error is returned if caused by client policy (such as
44 // http.Client.CheckRedirect), or if there was an HTTP protocol error. A
45 // non-2xx response doesn't cause an error.
46 //
47 // When err is nil, resp always contains a non-nil resp.Body.
48 //
49 // Callers should close resp.Body when done reading from it. If resp.Body is
50 // not closed, an underlying RoundTripper (typically Transport) may not be able
51 // to re-use a persistent TCP connection to the server for a subsequent
52 // "keep-alive" request.
53 //
54 // The request Body, if non-nil, will be closed by an underlying Transport,
55 // even on errors.
56 type DoFunc func(*http.Request) (*http.Response, error)
57
58 // Response captures the output of a Mesos HTTP API operation. Callers are responsible for invoking
59 // Close when they're finished processing the response otherwise there may be connection leaks.
60 type Response struct {
61 io.Closer
62 encoding.Decoder
63 Header http.Header
64 }
65
66 // ErrorMapperFunc generates an error for the given response.
67 type ErrorMapperFunc func(*http.Response) error
68
69 // ResponseHandler is invoked to process an HTTP response. Callers SHALL invoke Close for
70 // a non-nil Response, even when errors are returned.
71 type ResponseHandler func(*http.Response, client.ResponseClass, error) (mesos.Response, error)
72
73 // A Client is a Mesos HTTP APIs client.
74 type Client struct {
75 url string
76 do DoFunc
77 header http.Header
78 codec encoding.Codec
79 errorMapper ErrorMapperFunc
80 requestOpts []RequestOpt
81 buildRequestFunc func(client.Request, client.ResponseClass, ...RequestOpt) (*http.Request, error)
82 handleResponse ResponseHandler
83 }
84
85 var (
86 DefaultCodec = codecs.ByMediaType[codecs.MediaTypeProtobuf]
87 DefaultHeaders = http.Header{}
88
89 // DefaultConfigOpt represents the default client config options.
90 DefaultConfigOpt = []ConfigOpt{
91 Transport(func(t *http.Transport) {
92 // all calls should be ack'd by the server within this interval.
93 t.ResponseHeaderTimeout = 15 * time.Second
94 t.MaxIdleConnsPerHost = 2 // don't depend on go's default
95 }),
96 }
97
98 DefaultErrorMapper = ErrorMapperFunc(apierrors.FromResponse)
99 )
100
101 // New returns a new Client with the given Opts applied.
102 // Callers are expected to configure the URL, Do, and Codec options prior to
103 // invoking Do.
104 func New(opts ...Opt) *Client {
105 c := &Client{
106 codec: DefaultCodec,
107 do: With(DefaultConfigOpt...),
108 header: DefaultHeaders,
109 errorMapper: DefaultErrorMapper,
110 }
111 c.buildRequestFunc = c.buildRequest
112 c.handleResponse = c.HandleResponse
113 c.With(opts...)
114 return c
115 }
116
117 // Endpoint returns the current Mesos API endpoint URL that the caller is set to invoke
118 func (c *Client) Endpoint() string {
119 return c.url
120 }
121
122 // RequestOpt defines a functional option for an http.Request.
123 type RequestOpt func(*http.Request)
124
125 // RequestOpts is a convenience type
126 type RequestOpts []RequestOpt
127
128 // Apply this set of request options to the given HTTP request.
129 func (opts RequestOpts) Apply(req *http.Request) {
130 // apply per-request options
131 for _, o := range opts {
132 if o != nil {
133 o(req)
134 }
135 }
136 }
137
138 // With applies the given Opts to a Client and returns itself.
139 func (c *Client) With(opts ...Opt) Opt {
140 return Opts(opts).Merged().Apply(c)
141 }
142
143 // WithTemporary configures the Client with the temporary option and returns the results of
144 // invoking f(). Changes made to the Client by the temporary option are reverted before this
145 // func returns.
146 func (c *Client) WithTemporary(opt Opt, f func() error) error {
147 if opt != nil {
148 undo := c.With(opt)
149 defer c.With(undo)
150 }
151 return f()
152 }
153
154 // Mesos returns a mesos.Client variant backed by this implementation.
155 // Deprecated.
156 func (c *Client) Mesos(opts ...RequestOpt) mesos.Client {
157 return mesos.ClientFunc(func(m encoding.Marshaler) (mesos.Response, error) {
158 return c.Do(m, opts...)
159 })
160 }
161
162 func prepareForResponse(rc client.ResponseClass, codec encoding.Codec) (RequestOpts, error) {
163 // We need to tell Mesos both the content-type and message-content-type that we're expecting, otherwise
164 // the server may give us validation problems, or else send back a vague content-type (w/o a
165 // message-content-type). In order to communicate these things we need to understand the desired response
166 // type from the perspective of the caller --> client.ResponseClass.
167 var accept RequestOpts
168 switch rc {
169 case client.ResponseClassSingleton, client.ResponseClassAuto, client.ResponseClassNoData:
170 accept = append(accept, Header("Accept", codec.Type.ContentType()))
171 case client.ResponseClassStreaming:
172 accept = append(accept, Header("Accept", mediaTypeRecordIO.ContentType()))
173 accept = append(accept, Header("Message-Accept", codec.Type.ContentType()))
174 default:
175 return nil, ProtocolError(fmt.Sprintf("illegal response class requested: %v", rc))
176 }
177 return accept, nil
178 }
179
180 // buildRequest is a factory func that generates and returns an http.Request for the
181 // given marshaler and request options.
182 func (c *Client) buildRequest(cr client.Request, rc client.ResponseClass, opt ...RequestOpt) (*http.Request, error) {
183 if crs, ok := cr.(client.RequestStreaming); ok {
184 return c.buildRequestStream(crs.Marshaler, rc, opt...)
185 }
186 accept, err := prepareForResponse(rc, c.codec)
187 if err != nil {
188 return nil, err
189 }
190
191 //TODO(jdef): use a pool to allocate these (and reduce garbage)?
192 // .. or else, use a pipe (like streaming does) to avoid the intermediate buffer?
193 var body bytes.Buffer
194 if err := c.codec.NewEncoder(encoding.SinkWriter(&body)).Encode(cr.Marshaler()); err != nil {
195 return nil, err
196 }
197
198 req, err := http.NewRequest("POST", c.url, &body)
199 if err != nil {
200 return nil, err
201 }
202
203 helper := HTTPRequestHelper{req}
204 return helper.
205 withOptions(c.requestOpts, opt).
206 withHeaders(c.header).
207 withHeader("Content-Type", c.codec.Type.ContentType()).
208 withHeader("Accept", c.codec.Type.ContentType()).
209 withOptions(accept).
210 Request, nil
211 }
212
213 func (c *Client) buildRequestStream(f func() encoding.Marshaler, rc client.ResponseClass, opt ...RequestOpt) (*http.Request, error) {
214 accept, err := prepareForResponse(rc, c.codec)
215 if err != nil {
216 return nil, err
217 }
218
219 var (
220 pr, pw = io.Pipe()
221 enc = c.codec.NewEncoder(func() framing.Writer { return recordio.NewWriter(pw) })
222 )
223 req, err := http.NewRequest("POST", c.url, pr)
224 if err != nil {
225 pw.Close() // ignore error
226 return nil, err
227 }
228
229 go func() {
230 var closeOnce sync.Once
231 defer closeOnce.Do(func() {
232 pw.Close()
233 })
234 for {
235 m := f()
236 if m == nil {
237 // no more messages to send; end of the stream
238 break
239 }
240 err := enc.Encode(m)
241 if err != nil {
242 closeOnce.Do(func() {
243 pw.CloseWithError(err)
244 })
245 break
246 }
247 }
248 }()
249
250 helper := HTTPRequestHelper{req}
251 return helper.
252 withOptions(c.requestOpts, opt).
253 withHeaders(c.header).
254 withHeader("Content-Type", mediaTypeRecordIO.ContentType()).
255 withHeader("Message-Content-Type", c.codec.Type.ContentType()).
256 withOptions(accept).
257 Request, nil
258 }
259
260 func validateSuccessfulResponse(codec encoding.Codec, res *http.Response, rc client.ResponseClass) error {
261 switch res.StatusCode {
262 case http.StatusOK:
263 ct := res.Header.Get("Content-Type")
264 switch rc {
265 case client.ResponseClassNoData:
266 if ct != "" {
267 return ProtocolError(fmt.Sprintf("unexpected content type: %q", ct))
268 }
269 case client.ResponseClassSingleton, client.ResponseClassAuto:
270 if ct != codec.Type.ContentType() {
271 return ProtocolError(fmt.Sprintf("unexpected content type: %q", ct))
272 }
273 case client.ResponseClassStreaming:
274 if ct != mediaTypeRecordIO.ContentType() {
275 return ProtocolError(fmt.Sprintf("unexpected content type: %q", ct))
276 }
277 ct = res.Header.Get("Message-Content-Type")
278 if ct != codec.Type.ContentType() {
279 return ProtocolError(fmt.Sprintf("unexpected message content type: %q", ct))
280 }
281 default:
282 return ProtocolError(fmt.Sprintf("unsupported response-class: %q", rc))
283 }
284
285 case http.StatusAccepted:
286 // nothing to validate, we're not expecting any response entity in this case.
287 // TODO(jdef) perhaps check Content-Length == 0 here?
288 }
289 return nil
290 }
291
292 func newSourceFactory(rc client.ResponseClass) encoding.SourceFactoryFunc {
293 switch rc {
294 case client.ResponseClassNoData:
295 return nil
296 case client.ResponseClassSingleton:
297 return encoding.SourceReader
298 case client.ResponseClassStreaming, client.ResponseClassAuto:
299 return recordIOSourceFactory
300 default:
301 panic(fmt.Sprintf("unsupported response-class: %q", rc))
302 }
303 }
304
305 func recordIOSourceFactory(r io.Reader) encoding.Source {
306 return func() framing.Reader { return recordio.NewReader(r) }
307 }
308
309 // HandleResponse parses an HTTP response from a Mesos service endpoint, transforming the
310 // raw HTTP response into a mesos.Response.
311 func (c *Client) HandleResponse(res *http.Response, rc client.ResponseClass, err error) (mesos.Response, error) {
312 if err != nil {
313 if res != nil && res.Body != nil {
314 res.Body.Close()
315 }
316 return nil, err
317 }
318
319 result := &Response{
320 Closer: res.Body,
321 Header: res.Header,
322 }
323 if err = c.errorMapper(res); err != nil {
324 return result, err
325 }
326
327 err = validateSuccessfulResponse(c.codec, res, rc)
328 if err != nil {
329 res.Body.Close()
330 return nil, err
331 }
332
333 switch res.StatusCode {
334 case http.StatusOK:
335 debug.Log("request OK, decoding response")
336
337 sf := newSourceFactory(rc)
338 if sf == nil {
339 if rc != client.ResponseClassNoData {
340 panic("nil Source for response that expected data")
341 }
342 // we don't expect any data. drain the response body and close it (compliant with golang's expectations
343 // for http/1.1 keepalive support.
344 defer res.Body.Close()
345 _, err = io.Copy(ioutil.Discard, res.Body)
346 return nil, err
347 }
348
349 result.Decoder = c.codec.NewDecoder(sf.NewSource(res.Body))
350
351 case http.StatusAccepted:
352 debug.Log("request Accepted")
353
354 // noop; no decoder for these types of calls
355 defer res.Body.Close()
356 _, err = io.Copy(ioutil.Discard, res.Body)
357 return nil, err
358
359 default:
360 debug.Log("unexpected HTTP status", res.StatusCode)
361
362 defer res.Body.Close()
363 io.Copy(ioutil.Discard, res.Body) // intentionally discard any error here
364 return nil, ProtocolError(fmt.Sprintf("unexpected mesos HTTP response code: %d", res.StatusCode))
365 }
366
367 return result, nil
368 }
369
370 // Do is deprecated in favor of Send.
371 func (c *Client) Do(m encoding.Marshaler, opt ...RequestOpt) (res mesos.Response, err error) {
372 return c.Send(client.RequestSingleton(m), client.ResponseClassAuto, opt...)
373 }
374
375 // Send sends a Call and returns (a) a Response (should be closed when finished) that
376 // contains a either a streaming or non-streaming Decoder from which callers can read
377 // objects from, and; (b) an error in case of failure. Callers are expected to *always*
378 // close a non-nil Response if one is returned. For operations which are successful but
379 // also for which there are no expected result objects the embedded Decoder will be nil.
380 // The provided ResponseClass determines whether the client implementation will attempt
381 // to decode a result as a single obeject or as an object stream. When working with
382 // versions of Mesos prior to v1.2.x callers MUST use ResponseClassAuto.
383 func (c *Client) Send(cr client.Request, rc client.ResponseClass, opt ...RequestOpt) (res mesos.Response, err error) {
384 var (
385 hreq *http.Request
386 hres *http.Response
387 )
388 hreq, err = c.buildRequestFunc(cr, rc, opt...)
389 if err == nil {
390 hres, err = c.do(hreq)
391 res, err = c.handleResponse(hres, rc, err)
392 }
393 return
394 }
395
396 // ErrorMapper returns am Opt that overrides the existing error mapping behavior of the client.
397 func ErrorMapper(em ErrorMapperFunc) Opt {
398 return func(c *Client) Opt {
399 old := c.errorMapper
400 c.errorMapper = em
401 return ErrorMapper(old)
402 }
403 }
404
405 // Endpoint returns an Opt that sets a Client's URL.
406 func Endpoint(rawurl string) Opt {
407 return func(c *Client) Opt {
408 old := c.url
409 c.url = rawurl
410 return Endpoint(old)
411 }
412 }
413
414 // WrapDoer returns an Opt that decorates a Client's DoFunc
415 func WrapDoer(f func(DoFunc) DoFunc) Opt {
416 return func(c *Client) Opt {
417 old := c.do
418 c.do = f(c.do)
419 return Do(old)
420 }
421 }
422
423 // Do returns an Opt that sets a Client's DoFunc
424 func Do(do DoFunc) Opt {
425 return func(c *Client) Opt {
426 old := c.do
427 c.do = do
428 return Do(old)
429 }
430 }
431
432 // Codec returns an Opt that sets a Client's Codec.
433 func Codec(codec encoding.Codec) Opt {
434 return func(c *Client) Opt {
435 old := c.codec
436 c.codec = codec
437 return Codec(old)
438 }
439 }
440
441 // DefaultHeader returns an Opt that adds a header to an Client's headers.
442 func DefaultHeader(k, v string) Opt {
443 return func(c *Client) Opt {
444 old, found := c.header[k]
445 old = append([]string{}, old...) // clone
446 c.header.Add(k, v)
447 return func(c *Client) Opt {
448 if found {
449 c.header[k] = old
450 } else {
451 c.header.Del(k)
452 }
453 return DefaultHeader(k, v)
454 }
455 }
456 }
457
458 // HandleResponse returns a functional config option to set the HTTP response handler of the client.
459 func HandleResponse(f ResponseHandler) Opt {
460 return func(c *Client) Opt {
461 old := c.handleResponse
462 c.handleResponse = f
463 return HandleResponse(old)
464 }
465 }
466
467 // RequestOptions returns an Opt that applies the given set of options to every Client request.
468 func RequestOptions(opts ...RequestOpt) Opt {
469 if len(opts) == 0 {
470 return nil
471 }
472 return func(c *Client) Opt {
473 old := append([]RequestOpt{}, c.requestOpts...)
474 c.requestOpts = opts
475 return RequestOptions(old...)
476 }
477 }
478
479 // Header returns an RequestOpt that adds a header value to an HTTP requests's header.
480 func Header(k, v string) RequestOpt { return func(r *http.Request) { r.Header.Add(k, v) } }
481
482 // Close returns a RequestOpt that determines whether to close the underlying connection after sending the request.
483 func Close(b bool) RequestOpt { return func(r *http.Request) { r.Close = b } }
484
485 // Context returns a RequestOpt that sets the request's Context (ctx must be non-nil)
486 func Context(ctx context.Context) RequestOpt {
487 return func(r *http.Request) {
488 r2 := r.WithContext(ctx)
489 *r = *r2
490 }
491 }
492
493 type Config struct {
494 client *http.Client
495 dialer *net.Dialer
496 transport *http.Transport
497 }
498
499 type ConfigOpt func(*Config)
500
501 // With returns a DoFunc that executes HTTP round-trips.
502 // The default implementation provides reasonable defaults for timeouts:
503 // keep-alive, connection, request/response read/write, and TLS handshake.
504 // Callers can customize configuration by specifying one or more ConfigOpt's.
505 func With(opt ...ConfigOpt) DoFunc {
506 var (
507 dialer = &net.Dialer{
508 LocalAddr: &net.TCPAddr{IP: net.IPv4zero},
509 KeepAlive: 30 * time.Second,
510 Timeout: 5 * time.Second,
511 }
512 transport = &http.Transport{
513 Proxy: http.ProxyFromEnvironment,
514 Dial: dialer.Dial,
515 ResponseHeaderTimeout: 5 * time.Second,
516 TLSClientConfig: &tls.Config{InsecureSkipVerify: false},
517 TLSHandshakeTimeout: 5 * time.Second,
518 }
519 config = &Config{
520 dialer: dialer,
521 transport: transport,
522 client: &http.Client{
523 Transport: transport,
524 CheckRedirect: noRedirect, // so we can actually see the 307 redirects
525 },
526 }
527 )
528 for _, o := range opt {
529 if o != nil {
530 o(config)
531 }
532 }
533 return config.client.Do
534 }
535
536 // Timeout returns an ConfigOpt that sets a Config's response header timeout, tls handshake timeout,
537 // and dialer timeout.
538 func Timeout(d time.Duration) ConfigOpt {
539 return func(c *Config) {
540 c.transport.ResponseHeaderTimeout = d
541 c.transport.TLSHandshakeTimeout = d
542 c.dialer.Timeout = d
543 }
544 }
545
546 // RoundTripper returns a ConfigOpt that sets a Config's round-tripper.
547 func RoundTripper(rt http.RoundTripper) ConfigOpt {
548 return func(c *Config) {
549 c.client.Transport = rt
550 }
551 }
552
553 // TLSConfig returns a ConfigOpt that sets a Config's TLS configuration.
554 func TLSConfig(tc *tls.Config) ConfigOpt {
555 return func(c *Config) {
556 c.transport.TLSClientConfig = tc
557 }
558 }
559
560 // Transport returns a ConfigOpt that allows tweaks of the default Config's http.Transport
561 func Transport(modifyTransport func(*http.Transport)) ConfigOpt {
562 return func(c *Config) {
563 if modifyTransport != nil {
564 modifyTransport(c.transport)
565 }
566 }
567 }
568
569 // WrapRoundTripper allows a caller to customize a configuration's HTTP exchanger. Useful
570 // for authentication protocols that operate over stock HTTP.
571 func WrapRoundTripper(f func(http.RoundTripper) http.RoundTripper) ConfigOpt {
572 return func(c *Config) {
573 if f != nil {
574 if rt := f(c.client.Transport); rt != nil {
575 c.client.Transport = rt
576 }
577 }
578 }
579 }
580
581 // HTTPRequestHelper wraps an http.Request and provides utility funcs to simplify code elsewhere
582 type HTTPRequestHelper struct {
583 *http.Request
584 }
585
586 func (r *HTTPRequestHelper) withOptions(optsets ...RequestOpts) *HTTPRequestHelper {
587 for _, opts := range optsets {
588 opts.Apply(r.Request)
589 }
590 return r
591 }
592
593 func (r *HTTPRequestHelper) withHeaders(hh http.Header) *HTTPRequestHelper {
594 for k, v := range hh {
595 r.Header[k] = v
596 debug.Log("request header " + k + ": " + v[0])
597 }
598 return r
599 }
600
601 func (r *HTTPRequestHelper) withHeader(key, value string) *HTTPRequestHelper {
602 r.Header.Set(key, value)
603 return r
604 }