Skip to content

Commit 17246b8

Browse files
authored
Merge pull request kubernetes#82588 from liggitt/abort-handler-panic
Propagate and honor http.ErrAbortHandler
2 parents ab8bb23 + 4341529 commit 17246b8

File tree

7 files changed

+88
-14
lines changed

7 files changed

+88
-14
lines changed

staging/src/k8s.io/apimachinery/pkg/util/runtime/runtime.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package runtime
1818

1919
import (
2020
"fmt"
21+
"net/http"
2122
"runtime"
2223
"sync"
2324
"time"
@@ -56,8 +57,16 @@ func HandleCrash(additionalHandlers ...func(interface{})) {
5657
}
5758
}
5859

59-
// logPanic logs the caller tree when a panic occurs.
60+
// logPanic logs the caller tree when a panic occurs (except in the special case of http.ErrAbortHandler).
6061
func logPanic(r interface{}) {
62+
if r == http.ErrAbortHandler {
63+
// honor the http.ErrAbortHandler sentinel panic value:
64+
// ErrAbortHandler is a sentinel panic value to abort a handler.
65+
// While any panic from ServeHTTP aborts the response to the client,
66+
// panicking with ErrAbortHandler also suppresses logging of a stack trace to the server's error log.
67+
return
68+
}
69+
6170
// Same as stdlib http server code. Manually allocate stack trace buffer size
6271
// to prevent excessively large logs
6372
const size = 64 << 10

staging/src/k8s.io/apimachinery/pkg/util/runtime/runtime_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"bytes"
2121
"fmt"
2222
"io"
23+
"net/http"
2324
"os"
2425
"regexp"
2526
"strings"
@@ -114,6 +115,24 @@ func TestHandleCrashLog(t *testing.T) {
114115
}
115116
}
116117

118+
func TestHandleCrashLogSilenceHTTPErrAbortHandler(t *testing.T) {
119+
log, err := captureStderr(func() {
120+
defer func() {
121+
if r := recover(); r != http.ErrAbortHandler {
122+
t.Fatalf("expected to recover from http.ErrAbortHandler")
123+
}
124+
}()
125+
defer HandleCrash()
126+
panic(http.ErrAbortHandler)
127+
})
128+
if err != nil {
129+
t.Fatalf("%v", err)
130+
}
131+
if len(log) > 0 {
132+
t.Fatalf("expected no stderr log, got: %s", log)
133+
}
134+
}
135+
117136
// captureStderr redirects stderr to result string, and then restore stderr from backup
118137
func captureStderr(f func()) (string, error) {
119138
r, w, err := os.Pipe()

staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest.go

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -220,12 +220,15 @@ func finishRequest(timeout time.Duration, fn resultFunc) (result runtime.Object,
220220
defer func() {
221221
panicReason := recover()
222222
if panicReason != nil {
223-
// Same as stdlib http server code. Manually allocate stack
224-
// trace buffer size to prevent excessively large logs
225-
const size = 64 << 10
226-
buf := make([]byte, size)
227-
buf = buf[:goruntime.Stack(buf, false)]
228-
panicReason = fmt.Sprintf("%v\n%s", panicReason, buf)
223+
// do not wrap the sentinel ErrAbortHandler panic value
224+
if panicReason != http.ErrAbortHandler {
225+
// Same as stdlib http server code. Manually allocate stack
226+
// trace buffer size to prevent excessively large logs
227+
const size = 64 << 10
228+
buf := make([]byte, size)
229+
buf = buf[:goruntime.Stack(buf, false)]
230+
panicReason = fmt.Sprintf("%v\n%s", panicReason, buf)
231+
}
229232
// Propagate to parent goroutine
230233
panicCh <- panicReason
231234
}

staging/src/k8s.io/apiserver/pkg/endpoints/handlers/rest_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -849,6 +849,8 @@ func TestFinishRequest(t *testing.T) {
849849
expectedObj runtime.Object
850850
expectedErr error
851851
expectedPanic string
852+
853+
expectedPanicObj interface{}
852854
}{
853855
{
854856
name: "Expected obj is returned",
@@ -906,6 +908,17 @@ func TestFinishRequest(t *testing.T) {
906908
expectedErr: nil,
907909
expectedPanic: "rest_test.go",
908910
},
911+
{
912+
name: "http.ErrAbortHandler panic is propagated without wrapping with stack",
913+
timeout: time.Second,
914+
fn: func() (runtime.Object, error) {
915+
panic(http.ErrAbortHandler)
916+
},
917+
expectedObj: nil,
918+
expectedErr: nil,
919+
expectedPanic: http.ErrAbortHandler.Error(),
920+
expectedPanicObj: http.ErrAbortHandler,
921+
},
909922
}
910923
for i, tc := range testcases {
911924
t.Run(tc.name, func(t *testing.T) {
@@ -919,6 +932,10 @@ func TestFinishRequest(t *testing.T) {
919932
case r != nil && len(tc.expectedPanic) > 0 && !strings.Contains(fmt.Sprintf("%v", r), tc.expectedPanic):
920933
t.Errorf("expected panic containing '%s', got '%v'", tc.expectedPanic, r)
921934
}
935+
936+
if tc.expectedPanicObj != nil && !reflect.DeepEqual(tc.expectedPanicObj, r) {
937+
t.Errorf("expected panic obj %#v, got %#v", tc.expectedPanicObj, r)
938+
}
922939
}()
923940
obj, err := finishRequest(tc.timeout, tc.fn)
924941
if (err == nil && tc.expectedErr != nil) || (err != nil && tc.expectedErr == nil) || (err != nil && tc.expectedErr != nil && err.Error() != tc.expectedErr.Error()) {

staging/src/k8s.io/apiserver/pkg/server/filters/timeout.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,8 @@ func (t *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
9898
go func() {
9999
defer func() {
100100
err := recover()
101-
if err != nil {
101+
// do not wrap the sentinel ErrAbortHandler panic value
102+
if err != nil && err != http.ErrAbortHandler {
102103
// Same as stdlib http server code. Manually allocate stack
103104
// trace buffer size to prevent excessively large logs
104105
const size = 64 << 10

staging/src/k8s.io/apiserver/pkg/server/filters/timeout_test.go

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,14 @@ func (r *recorder) Count() int {
5252
return r.count
5353
}
5454

55-
func newHandler(responseCh <-chan string, panicCh <-chan struct{}, writeErrCh chan<- error) http.HandlerFunc {
55+
func newHandler(responseCh <-chan string, panicCh <-chan interface{}, writeErrCh chan<- error) http.HandlerFunc {
5656
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
5757
select {
5858
case resp := <-responseCh:
5959
_, err := w.Write([]byte(resp))
6060
writeErrCh <- err
61-
case <-panicCh:
62-
panic("inner handler panics")
61+
case panicReason := <-panicCh:
62+
panic(panicReason)
6363
}
6464
})
6565
}
@@ -72,7 +72,7 @@ func TestTimeout(t *testing.T) {
7272
}()
7373

7474
sendResponse := make(chan string, 1)
75-
doPanic := make(chan struct{}, 1)
75+
doPanic := make(chan interface{}, 1)
7676
writeErrors := make(chan error, 1)
7777
gotPanic := make(chan interface{}, 1)
7878
timeout := make(chan time.Time, 1)
@@ -139,7 +139,7 @@ func TestTimeout(t *testing.T) {
139139
}
140140

141141
// Panics
142-
doPanic <- struct{}{}
142+
doPanic <- "inner handler panics"
143143
res, err = http.Get(ts.URL)
144144
if err != nil {
145145
t.Fatal(err)
@@ -156,4 +156,22 @@ func TestTimeout(t *testing.T) {
156156
case <-time.After(30 * time.Second):
157157
t.Fatalf("expected to see a handler panic, but didn't")
158158
}
159+
160+
// Panics with http.ErrAbortHandler
161+
doPanic <- http.ErrAbortHandler
162+
res, err = http.Get(ts.URL)
163+
if err != nil {
164+
t.Fatal(err)
165+
}
166+
if res.StatusCode != http.StatusInternalServerError {
167+
t.Errorf("got res.StatusCode %d; expected %d due to panic", res.StatusCode, http.StatusInternalServerError)
168+
}
169+
select {
170+
case err := <-gotPanic:
171+
if err != http.ErrAbortHandler {
172+
t.Errorf("expected unwrapped http.ErrAbortHandler, got %#v", err)
173+
}
174+
case <-time.After(30 * time.Second):
175+
t.Fatalf("expected to see a handler panic, but didn't")
176+
}
159177
}

staging/src/k8s.io/apiserver/pkg/server/filters/wrap.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,16 @@ import (
2525
"k8s.io/apiserver/pkg/server/httplog"
2626
)
2727

28-
// WithPanicRecovery wraps an http Handler to recover and log panics.
28+
// WithPanicRecovery wraps an http Handler to recover and log panics (except in the special case of http.ErrAbortHandler panics, which suppress logging).
2929
func WithPanicRecovery(handler http.Handler) http.Handler {
3030
return withPanicRecovery(handler, func(w http.ResponseWriter, req *http.Request, err interface{}) {
31+
if err == http.ErrAbortHandler {
32+
// honor the http.ErrAbortHandler sentinel panic value:
33+
// ErrAbortHandler is a sentinel panic value to abort a handler.
34+
// While any panic from ServeHTTP aborts the response to the client,
35+
// panicking with ErrAbortHandler also suppresses logging of a stack trace to the server's error log.
36+
return
37+
}
3138
http.Error(w, "This request caused apiserver to panic. Look in the logs for details.", http.StatusInternalServerError)
3239
klog.Errorf("apiserver panic'd on %v %v", req.Method, req.RequestURI)
3340
})

0 commit comments

Comments
 (0)