/
timeout.go
292 lines (252 loc) · 8.09 KB
/
timeout.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/*
Copyright 2020 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package handler
import (
"bufio"
"context"
"io"
"net"
"net/http"
"sync"
"time"
"k8s.io/apimachinery/pkg/util/clock"
"knative.dev/pkg/websocket"
)
type timeoutHandler struct {
handler http.Handler
timeout time.Duration
responseStartTimeout time.Duration
idleTimeout time.Duration
body string
clock clock.Clock
}
// NewTimeoutHandler returns a Handler that runs `h` with the
// given timeout in which the first byte of the response must be written,
// and with the given idle timeout
//
// The new Handler calls h.ServeHTTP to handle each request, but if a
// call runs for longer than its time limit, the handler responds with
// a 504 Gateway Timeout error and the given message in its body.
// (If msg is empty, a suitable default message will be sent.)
// After such a timeout, writes by h to its ResponseWriter will return
// ErrHandlerTimeout.
//
// A panic from the underlying handler is propagated as-is to be able to
// make use of custom panic behavior by HTTP handlers. See
// https://golang.org/pkg/net/http/#Handler.
//
// The implementation is largely inspired by http.TimeoutHandler.
func NewTimeoutHandler(h http.Handler, msg string, timeout time.Duration, responseStartTimeout time.Duration, idleTimeout time.Duration) http.Handler {
return &timeoutHandler{
handler: h,
body: msg,
timeout: timeout,
responseStartTimeout: responseStartTimeout,
idleTimeout: idleTimeout,
clock: clock.RealClock{},
}
}
func (h *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
timeout := getTimer(h.clock, h.timeout)
var timeoutDrained bool
defer func() {
putTimer(timeout, timeoutDrained)
}()
var idleTimeout clock.Timer
var idleTimeoutDrained bool
if h.idleTimeout > 0 {
idleTimeout = getTimer(h.clock, h.idleTimeout)
defer func() {
putTimer(idleTimeout, idleTimeoutDrained)
}()
}
var idleTimeoutCh <-chan time.Time
if idleTimeout != nil {
idleTimeoutCh = idleTimeout.C()
}
// done is closed when h.handler.ServeHTTP completes and contains
// the panic from h.handler.ServeHTTP if h.handler.ServeHTTP panics.
done := make(chan interface{})
tw := &timeoutWriter{w: w, clock: h.clock}
var responseStartTimeout clock.Timer
var responseStartTimeoutDrained bool
if h.responseStartTimeout > 0 {
responseStartTimeout = getTimer(h.clock, h.responseStartTimeout)
defer func() {
putTimer(responseStartTimeout, responseStartTimeoutDrained)
}()
}
var responseStartTimeoutCh <-chan time.Time
if responseStartTimeout != nil {
responseStartTimeoutCh = responseStartTimeout.C()
}
go func() {
defer func() {
defer close(done)
if p := recover(); p != nil {
done <- p
}
}()
h.handler.ServeHTTP(tw, r.WithContext(ctx))
}()
for {
select {
case p, ok := <-done:
if ok {
panic(p)
}
return
case <-timeout.C():
timeoutDrained = true
if tw.tryTimeoutAndWriteError(h.body) {
return
}
case now := <-idleTimeoutCh:
timedOut, timeToNextTimeout := tw.tryIdleTimeoutAndWriteError(now, h.idleTimeout, h.body)
if timedOut {
idleTimeoutDrained = true
return
}
idleTimeout.Reset(timeToNextTimeout)
case <-responseStartTimeoutCh:
timedOut := tw.tryResponseStartTimeoutAndWriteError(h.body)
if timedOut {
responseStartTimeoutDrained = true
return
}
}
}
}
// timeoutWriter is a wrapper around an http.ResponseWriter. It guards
// writing an error response to whether or not the underlying writer has
// already been written to.
//
// If the underlying writer has not been written to, an error response is
// returned. If it has already been written to, the error is ignored and
// the response is allowed to continue.
type timeoutWriter struct {
w http.ResponseWriter
clock clock.PassiveClock
mu sync.Mutex
timedOut bool
lastWriteTime time.Time
}
var _ http.Flusher = (*timeoutWriter)(nil)
var _ http.ResponseWriter = (*timeoutWriter)(nil)
func (tw *timeoutWriter) Flush() {
// The inner handler of timeoutHandler can call Flush at any time including after
// timeoutHandler.ServeHTTP has returned. Forwarding this call to the inner
// http.ResponseWriter would lead to a panic in HTTP2. See http2/server.go line 2556.
tw.mu.Lock()
defer tw.mu.Unlock()
if tw.timedOut {
return
}
tw.w.(http.Flusher).Flush()
}
// Hijack calls Hijack() on the wrapped http.ResponseWriter if it implements
// http.Hijacker interface, which is required for net/http/httputil/reverseproxy
// to handle connection upgrade/switching protocol. Otherwise returns an error.
func (tw *timeoutWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return websocket.HijackIfPossible(tw.w)
}
func (tw *timeoutWriter) Header() http.Header { return tw.w.Header() }
func (tw *timeoutWriter) Write(p []byte) (int, error) {
tw.mu.Lock()
defer tw.mu.Unlock()
if tw.timedOut {
return 0, http.ErrHandlerTimeout
}
tw.lastWriteTime = tw.clock.Now()
return tw.w.Write(p)
}
func (tw *timeoutWriter) WriteHeader(code int) {
tw.mu.Lock()
defer tw.mu.Unlock()
if tw.timedOut {
return
}
tw.lastWriteTime = tw.clock.Now()
tw.w.WriteHeader(code)
}
// tryTimeoutAndWriteError writes an error to the responsewriter if
// nothing has been written to the writer before. Returns whether
// an error was written or not.
//
// If this writes an error, all subsequent calls to Write will
// result in http.ErrHandlerTimeout.
func (tw *timeoutWriter) tryTimeoutAndWriteError(msg string) bool {
tw.mu.Lock()
defer tw.mu.Unlock()
if tw.lastWriteTime.IsZero() {
tw.timeoutAndWriteError(msg)
return true
}
return false
}
// tryResponseStartTimeoutAndWriteError writes an error to the responsewriter if
// the response has not started responding before. Returns whether an error was
// written or not.
//
// If this writes an error, all subsequent calls to Write will
// result in http.ErrHandlerTimeout.
func (tw *timeoutWriter) tryResponseStartTimeoutAndWriteError(msg string) bool {
tw.mu.Lock()
defer tw.mu.Unlock()
if tw.lastWriteTime.IsZero() {
tw.timeoutAndWriteError(msg)
return true
}
return false
}
// tryIdleTimeoutAndWriteError writes an error to the responsewriter if
// nothing has been written to the writer within the idleTimeout period. Returns whether
// an error was written or not and time left to the next timeout
//
// If this writes an error, all subsequent calls to Write will
// result in http.ErrHandlerTimeout.
func (tw *timeoutWriter) tryIdleTimeoutAndWriteError(curTime time.Time, idleTimeout time.Duration, msg string) (timedOut bool, timeToNextTimeout time.Duration) {
tw.mu.Lock()
defer tw.mu.Unlock()
timeSinceLastWrite := curTime.Sub(tw.lastWriteTime)
if timeSinceLastWrite >= idleTimeout {
tw.timeoutAndWriteError(msg)
return true, 0
}
return false, idleTimeout - timeSinceLastWrite
}
func (tw *timeoutWriter) timeoutAndWriteError(msg string) {
tw.w.WriteHeader(http.StatusGatewayTimeout)
io.WriteString(tw.w, msg)
tw.timedOut = true
}
var timerPool sync.Pool
func getTimer(c clock.Clock, timeout time.Duration) clock.Timer {
if v := timerPool.Get(); v != nil {
t := v.(clock.Timer)
t.Reset(timeout)
return t
}
return c.NewTimer(timeout)
}
func putTimer(t clock.Timer, alreadyDrained bool) {
if !t.Stop() && !alreadyDrained {
// Stop told us that we didn't *actually* stop the timer, so it expired. We've
// also not drained the channel yet, so the expiration raced the inner handler
// finishing, so we know we *have* to drain here.
<-t.C()
}
timerPool.Put(t)
}