Debian Codegraph @

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

raw symbols SCIP
1 package httpsched
2
3 import (
4 "context"
5 "fmt"
6 "log"
7 "net/http"
8 "sync"
9
10 "github.com/mesos/mesos-go/api/v1/lib"
11 "github.com/mesos/mesos-go/api/v1/lib/encoding"
12 "github.com/mesos/mesos-go/api/v1/lib/httpcli"
13 "github.com/mesos/mesos-go/api/v1/lib/httpcli/apierrors"
14 "github.com/mesos/mesos-go/api/v1/lib/scheduler"
15 "github.com/mesos/mesos-go/api/v1/lib/scheduler/calls"
16 )
17
18 const (
19 headerMesosStreamID = "Mesos-Stream-Id"
20 debug = false
21 )
22
23 type StateError string
24
25 func (err StateError) Error() string { return string(err) }
26
27 var (
28 errMissingStreamID = httpcli.ProtocolError("missing Mesos-Stream-Id header expected with successful SUBSCRIBE")
29 errAlreadySubscribed = StateError("already subscribed, cannot re-issue a SUBSCRIBE call")
30 )
31
32 type (
33 // state implements calls.Caller and tracks connectivity with Mesos
34 state struct {
35 client *client // client is a handle to the original underlying HTTP client
36
37 m sync.Mutex
38 fn stateFn // fn is the next state function to execute
39 caller calls.Caller // caller is (maybe) used by a state function to execute a call
40
41 call *scheduler.Call // call is the next call to execute
42 resp mesos.Response // resp is the Mesos response from the most recently executed call
43 err error // err is the error from the most recently executed call
44 }
45
46 stateFn func(context.Context, *state) stateFn
47 )
48
49 func maybeLogged(f httpcli.DoFunc) httpcli.DoFunc {
50 if debug {
51 return func(req *http.Request) (*http.Response, error) {
52 log.Println("wrapping request", req.URL, req.Header)
53 resp, err := f(req)
54 if err == nil {
55 log.Printf("status %d", resp.StatusCode)
56 for k := range resp.Header {
57 log.Println("header " + k + ": " + resp.Header.Get(k))
58 }
59 }
60 return resp, err
61 }
62 }
63 return f
64 }
65
66 // DisconnectionDetector is a programmable response decorator that attempts to detect errors
67 // that should transition the state from "connected" to "disconnected". Detector implementations
68 // are expected to invoke the `disconnect` callback in order to initiate the disconnection.
69 //
70 // The default implementation will transition to a disconnected state when:
71 // - an error occurs while decoding an object from the subscription stream
72 // - mesos reports an ERROR-type scheduler.Event object via the subscription stream
73 // - an object on the stream does not decode to a *scheduler.Event (sanity check)
74 //
75 // Consumers of this package may choose to override default behavior by overwriting the default
76 // value of this var, but should exercise caution: failure to properly transition to a disconnected
77 // state may cause subsequent Call operations to fail (without recourse).
78 var DisconnectionDetector = func(disconnect func()) mesos.ResponseDecorator {
79 return mesos.ResponseDecoratorFunc(func(resp mesos.Response) mesos.Response {
80 return &mesos.ResponseWrapper{
81 Response: resp,
82 Decoder: disconnectionDecoder(resp, disconnect),
83 }
84 })
85 }
86
87 func disconnectionDecoder(decoder encoding.Decoder, disconnect func()) encoding.Decoder {
88 return encoding.DecoderFunc(func(u encoding.Unmarshaler) (err error) {
89 err = decoder.Decode(u)
90 if err != nil {
91 disconnect()
92 return
93 }
94 switch e := u.(type) {
95 case (*scheduler.Event):
96 if e.GetType() == scheduler.Event_ERROR {
97 // the mesos scheduler API recommends that scheduler implementations
98 // resubscribe in this case. we initiate the disconnection here because
99 // it is assumed to be convenient for most framework implementations.
100 disconnect()
101 }
102 default:
103 // sanity check: this should never happen in practice.
104 err = httpcli.ProtocolError(
105 fmt.Sprintf("unexpected object on subscription event stream: %v", e))
106 disconnect()
107 }
108 return
109 })
110 }
111
112 func disconnectedFn(ctx context.Context, state *state) stateFn {
113 // (a) validate call = SUBSCRIBE
114 if state.call.GetType() != scheduler.Call_SUBSCRIBE {
115 state.resp = nil
116 state.err = apierrors.CodeUnsubscribed.Error("")
117 return disconnectedFn
118 }
119
120 // (b) prepare client for a subscription call
121 var (
122 mesosStreamID = ""
123 undoable = httpcli.WrapDoer(func(f httpcli.DoFunc) httpcli.DoFunc {
124 f = maybeLogged(f)
125 return func(req *http.Request) (resp *http.Response, err error) {
126 resp, err = f(req)
127 if err == nil && resp.StatusCode == 200 {
128 // grab Mesos-Stream-Id header; if missing then
129 // close the response body and return an error
130 mesosStreamID = resp.Header.Get(headerMesosStreamID)
131 if mesosStreamID == "" {
132 resp.Body.Close()
133 resp = nil
134 err = errMissingStreamID
135 }
136 }
137 return
138 }
139 })
140 subscribeCaller = &callerTemporary{
141 opt: undoable,
142 callerInternal: state.client,
143 requestOpts: []httpcli.RequestOpt{httpcli.Close(true)},
144 }
145 )
146
147 // (c) execute the call, save the result in resp, err
148 stateResp, stateErr := subscribeCaller.Call(ctx, state.call)
149 state.err = stateErr
150
151 // (d) if err != nil return disconnectedFn since we're unsubscribed
152 if stateErr != nil {
153 if stateResp != nil {
154 stateResp.Close()
155 }
156 state.resp = nil
157 return disconnectedFn
158 }
159
160 transitionToDisconnected := func() {
161 state.m.Lock()
162 defer state.m.Unlock()
163 state.fn = disconnectedFn
164 _ = stateResp.Close() // swallow any error here
165 }
166
167 // wrap the response: any errors processing the subscription stream should result in a
168 // transition to a disconnected state ASAP.
169 state.resp = DisconnectionDetector(transitionToDisconnected).Decorate(stateResp)
170
171 // (e) else prepare callerTemporary w/ special header, return connectedFn since we're now subscribed
172 state.caller = &callerTemporary{
173 opt: httpcli.DefaultHeader(headerMesosStreamID, mesosStreamID),
174 callerInternal: state.client,
175 }
176 return connectedFn
177 }
178
179 func errorIndicatesSubscriptionLoss(err error) (result bool) {
180 type lossy interface {
181 SubscriptionLoss() bool
182 }
183 if lossyErr, ok := err.(lossy); ok {
184 result = lossyErr.SubscriptionLoss()
185 }
186 return
187 }
188
189 func connectedFn(ctx context.Context, state *state) stateFn {
190 // (a) validate call != SUBSCRIBE
191 if state.call.GetType() == scheduler.Call_SUBSCRIBE {
192 if state.client.allowReconnect {
193 // Reset internal state back to DISCONNECTED and re-execute the SUBSCRIBE call.
194 // Mesos will hangup on the old SUBSCRIBE socket after this one completes.
195 state.caller = nil
196 state.resp = nil
197 state.err = nil
198 state.fn = disconnectedFn
199
200 return state.fn(ctx, state)
201 } else {
202 state.resp = nil
203
204 // TODO(jdef) not super happy with this error: I don't think that mesos minds if we issue
205 // redundant subscribe calls. However, the state tracking mechanism in this module can't
206 // cope with it (e.g. we'll need to track a new stream-id, etc).
207 // We make a best effort to transition to a disconnected state if we detect protocol errors,
208 // error events, or mesos-generated "not subscribed" errors. But we don't handle things such
209 // as, for example, authentication errors. Granted, the initial subscribe call should fail
210 // if authentication is an issue, so we should never end up here. I'm not convinced there's
211 // not other edge cases though with respect to other error codes.
212 state.err = errAlreadySubscribed
213 return connectedFn
214 }
215 }
216
217 // (b) execute call, save the result in resp, err
218 state.resp, state.err = state.caller.Call(ctx, state.call)
219
220 if errorIndicatesSubscriptionLoss(state.err) {
221 // properly transition back to a disconnected state if mesos thinks that we're unsubscribed
222 return disconnectedFn
223 }
224
225 // stay connected, don't attempt to interpret other errors here
226 return connectedFn
227 }
228
229 func (state *state) Call(ctx context.Context, call *scheduler.Call) (resp mesos.Response, err error) {
230 state.m.Lock()
231 defer state.m.Unlock()
232 state.call = call
233 state.fn = state.fn(ctx, state)
234
235 if debug && state.err != nil {
236 log.Print(*call, state.err)
237 }
238
239 return state.resp, state.err
240 }