| 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 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
type ProtocolError string |
| 32 |
|
| 33 |
|
| 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 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
type DoFunc func(*http.Request) (*http.Response, error) |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
type Response struct { |
| 61 |
io.Closer |
| 62 |
encoding.Decoder |
| 63 |
Header http.Header |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
type ErrorMapperFunc func(*http.Response) error |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
type ResponseHandler func(*http.Response, client.ResponseClass, error) (mesos.Response, error) |
| 72 |
|
| 73 |
|
| 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 |
|
| 90 |
DefaultConfigOpt = []ConfigOpt{ |
| 91 |
Transport(func(t *http.Transport) { |
| 92 |
|
| 93 |
t.ResponseHeaderTimeout = 15 * time.Second |
| 94 |
t.MaxIdleConnsPerHost = 2 |
| 95 |
}), |
| 96 |
} |
| 97 |
|
| 98 |
DefaultErrorMapper = ErrorMapperFunc(apierrors.FromResponse) |
| 99 |
) |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 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 |
|
| 118 |
func (c *Client) Endpoint() string { |
| 119 |
return c.url |
| 120 |
} |
| 121 |
|
| 122 |
|
| 123 |
type RequestOpt func(*http.Request) |
| 124 |
|
| 125 |
|
| 126 |
type RequestOpts []RequestOpt |
| 127 |
|
| 128 |
|
| 129 |
func (opts RequestOpts) Apply(req *http.Request) { |
| 130 |
|
| 131 |
for _, o := range opts { |
| 132 |
if o != nil { |
| 133 |
o(req) |
| 134 |
} |
| 135 |
} |
| 136 |
} |
| 137 |
|
| 138 |
|
| 139 |
func (c *Client) With(opts ...Opt) Opt { |
| 140 |
return Opts(opts).Merged().Apply(c) |
| 141 |
} |
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 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 |
|
| 155 |
|
| 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 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 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 |
|
| 181 |
|
| 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 |
|
| 192 |
|
| 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() |
| 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 |
|
| 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 |
|
| 287 |
|
| 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 |
|
| 310 |
|
| 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 |
|
| 343 |
|
| 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 |
|
| 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) |
| 364 |
return nil, ProtocolError(fmt.Sprintf("unexpected mesos HTTP response code: %d", res.StatusCode)) |
| 365 |
} |
| 366 |
|
| 367 |
return result, nil |
| 368 |
} |
| 369 |
|
| 370 |
|
| 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 |
|
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 442 |
func DefaultHeader(k, v string) Opt { |
| 443 |
return func(c *Client) Opt { |
| 444 |
old, found := c.header[k] |
| 445 |
old = append([]string{}, old...) |
| 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 |
|
| 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 |
|
| 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 |
|
| 480 |
func Header(k, v string) RequestOpt { return func(r *http.Request) { r.Header.Add(k, v) } } |
| 481 |
|
| 482 |
|
| 483 |
func Close(b bool) RequestOpt { return func(r *http.Request) { r.Close = b } } |
| 484 |
|
| 485 |
|
| 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 |
|
| 502 |
|
| 503 |
|
| 504 |
|
| 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, |
| 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 |
|
| 537 |
|
| 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 |
|
| 547 |
func RoundTripper(rt http.RoundTripper) ConfigOpt { |
| 548 |
return func(c *Config) { |
| 549 |
c.client.Transport = rt |
| 550 |
} |
| 551 |
} |
| 552 |
|
| 553 |
|
| 554 |
func TLSConfig(tc *tls.Config) ConfigOpt { |
| 555 |
return func(c *Config) { |
| 556 |
c.transport.TLSClientConfig = tc |
| 557 |
} |
| 558 |
} |
| 559 |
|
| 560 |
|
| 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 |
|
| 570 |
|
| 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 |
|
| 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 |
} |