Debian Codegraph @

api/v1/lib/httpcli/httpsched/httpsched.go

raw symbols SCIP
1 package httpsched
2
3 import (
4 "context"
5 "log"
6 "net/http"
7 "net/url"
8 "time"
9
10 "github.com/mesos/mesos-go/api/v1/lib"
11 "github.com/mesos/mesos-go/api/v1/lib/backoff"
12 mesosclient "github.com/mesos/mesos-go/api/v1/lib/client"
13 "github.com/mesos/mesos-go/api/v1/lib/encoding"
14 "github.com/mesos/mesos-go/api/v1/lib/httpcli"
15 "github.com/mesos/mesos-go/api/v1/lib/httpcli/apierrors"
16 "github.com/mesos/mesos-go/api/v1/lib/scheduler"
17 "github.com/mesos/mesos-go/api/v1/lib/scheduler/calls"
18 )
19
20 var (
21 errNotHTTPCli = httpcli.ProtocolError("expected an httpcli.Response object, found something else instead")
22 errBadLocation = httpcli.ProtocolError("failed to build new Mesos service endpoint URL from Location header")
23
24 DefaultRedirectSettings = RedirectSettings{
25 MaxAttempts: 9,
26 MaxBackoffPeriod: 13 * time.Second,
27 MinBackoffPeriod: 500 * time.Millisecond,
28 }
29 )
30
31 type (
32 RedirectSettings struct {
33 MaxAttempts int // per httpDo invocation
34 MaxBackoffPeriod time.Duration // should be more than minBackoffPeriod
35 MinBackoffPeriod time.Duration // should be less than maxBackoffPeriod
36 }
37
38 client struct {
39 *httpcli.Client
40 redirect RedirectSettings
41 allowReconnect bool // feature flag
42 }
43
44 // Caller is the public interface a framework scheduler's should consume
45 Caller interface {
46 calls.Caller
47 // httpDo is intentionally package-private; clients of this package may extend a Caller
48 // generated by this package by overriding the Call func but may not customize httpDo.
49 httpDo(context.Context, encoding.Marshaler, ...httpcli.RequestOpt) (mesos.Response, error)
50 }
51
52 callerInternal interface {
53 Caller
54 // WithTemporary configures the Client with the temporary option and returns the results of
55 // invoking f(). Changes made to the Client by the temporary option are reverted before this
56 // func returns.
57 WithTemporary(opt httpcli.Opt, f func() error) error
58 }
59
60 // Option is a functional configuration option type
61 Option func(*client) Option
62
63 callerTemporary struct {
64 callerInternal // delegate actually does the work
65 requestOpts []httpcli.RequestOpt // requestOpts are temporary per-request options
66 opt httpcli.Opt // opt is a temporary client option
67 }
68 )
69
70 func (ct *callerTemporary) httpDo(ctx context.Context, m encoding.Marshaler, opt ...httpcli.RequestOpt) (resp mesos.Response, err error) {
71 ct.callerInternal.WithTemporary(ct.opt, func() error {
72 if len(opt) == 0 {
73 opt = ct.requestOpts
74 } else if len(ct.requestOpts) > 0 {
75 opt = append(opt[:], ct.requestOpts...)
76 }
77 resp, err = ct.callerInternal.httpDo(ctx, m, opt...)
78 return nil
79 })
80 return
81 }
82
83 func (ct *callerTemporary) Call(ctx context.Context, call *scheduler.Call) (resp mesos.Response, err error) {
84 ct.callerInternal.WithTemporary(ct.opt, func() error {
85 resp, err = ct.callerInternal.Call(ctx, call)
86 return nil
87 })
88 return
89 }
90
91 // MaxRedirects is a functional option that sets the maximum number of per-call HTTP redirects for a scheduler client
92 func MaxRedirects(mr int) Option {
93 return func(c *client) Option {
94 old := c.redirect.MaxAttempts
95 c.redirect.MaxAttempts = mr
96 return MaxRedirects(old)
97 }
98 }
99
100 func AllowReconnection(v bool) Option {
101 return func(c *client) Option {
102 old := c.allowReconnect
103 c.allowReconnect = v
104 return AllowReconnection(old)
105 }
106 }
107
108 // NewCaller returns a scheduler API Client in the form of a Caller. Concurrent invocations
109 // of Call upon the returned caller are safely executed in a serial fashion. It is expected that
110 // there are no other users of the given Client since its state may be modified by this impl.
111 func NewCaller(cl *httpcli.Client, opts ...Option) calls.Caller {
112 result := &client{Client: cl, redirect: DefaultRedirectSettings}
113 cl.With(result.redirectHandler())
114 for _, o := range opts {
115 if o != nil {
116 o(result)
117 }
118 }
119 return &state{
120 client: result,
121 fn: disconnectedFn,
122 }
123 }
124
125 // httpDo decorates the inherited behavior w/ support for HTTP redirection to follow Mesos leadership changes.
126 // NOTE: this implementation will change the state of the client upon Mesos leadership changes.
127 func (cli *client) httpDo(ctx context.Context, m encoding.Marshaler, opt ...httpcli.RequestOpt) (resp mesos.Response, err error) {
128 var (
129 done chan struct{} // avoid allocating these chans unless we actually need to redirect
130 redirectBackoff <-chan struct{}
131 getBackoff = func() <-chan struct{} {
132 if redirectBackoff == nil {
133 done = make(chan struct{})
134 redirectBackoff = backoff.Notifier(cli.redirect.MinBackoffPeriod, cli.redirect.MaxBackoffPeriod, done)
135 }
136 return redirectBackoff
137 }
138 )
139 defer func() {
140 if done != nil {
141 close(done)
142 }
143 }()
144 opt = append(opt, httpcli.Context(ctx))
145 for attempt := 0; ; attempt++ {
146 resp, err = cli.Client.Do(m, opt...)
147 redirectErr, ok := err.(*mesosRedirectionError)
148 if !ok {
149 return resp, err
150 }
151 if attempt < cli.redirect.MaxAttempts {
152 if debug {
153 log.Println("redirecting to " + redirectErr.newURL)
154 }
155 cli.With(httpcli.Endpoint(redirectErr.newURL))
156 select {
157 case <-getBackoff():
158 case <-ctx.Done():
159 return nil, ctx.Err()
160 }
161 continue
162 }
163 return
164 }
165 }
166
167 // Call implements Client
168 func (cli *client) Call(ctx context.Context, call *scheduler.Call) (mesos.Response, error) {
169 return cli.httpDo(ctx, call)
170 }
171
172 type mesosRedirectionError struct{ newURL string }
173
174 func (mre *mesosRedirectionError) Error() string {
175 return "mesos server sent redirect to: " + mre.newURL
176 }
177
178 // redirectHandler returns a config options that decorates the default response handling routine;
179 // it transforms normal Mesos redirect "errors" into mesosRedirectionErrors by parsing the Location
180 // header and computing the address of the next endpoint that should be used to replay the failed
181 // HTTP request.
182 func (cli *client) redirectHandler() httpcli.Opt {
183 return httpcli.HandleResponse(func(hres *http.Response, rc mesosclient.ResponseClass, err error) (mesos.Response, error) {
184 resp, err := cli.HandleResponse(hres, rc, err) // default response handler
185 if err == nil || !apierrors.CodeNotLeader.Matches(err) {
186 return resp, err
187 }
188 // TODO(jdef) for now, we're tightly coupled to the httpcli package's Response type
189 res, ok := resp.(*httpcli.Response)
190 if !ok {
191 if resp != nil {
192 resp.Close()
193 }
194 return nil, errNotHTTPCli
195 }
196 if debug {
197 log.Println("master changed?")
198 }
199 location, ok := buildNewEndpoint(res.Header.Get("Location"), cli.Endpoint())
200 if !ok {
201 return nil, errBadLocation
202 }
203 res.Close()
204 return nil, &mesosRedirectionError{location}
205 })
206 }
207
208 func buildNewEndpoint(location, currentEndpoint string) (string, bool) {
209 // TODO(jdef) refactor this
210 // mesos v0.29 will actually send back fully-formed URLs in the Location header
211 if location == "" {
212 return "", false
213 }
214 // current format appears to be //x.y.z.w:port
215 hostport, parseErr := url.Parse(location)
216 if parseErr != nil || hostport.Host == "" {
217 return "", false
218 }
219 current, parseErr := url.Parse(currentEndpoint)
220 if parseErr != nil {
221 return "", false
222 }
223 current.Host = hostport.Host
224 return current.String(), true
225 }