github.com/m3db/m3@v1.5.0/src/query/api/v1/middleware/panic.go (about) 1 // Copyright (c) 2021 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package middleware 22 23 import ( 24 "fmt" 25 "net/http" 26 "sync" 27 28 "github.com/gorilla/mux" 29 "go.uber.org/zap" 30 "go.uber.org/zap/zapcore" 31 32 "github.com/m3db/m3/src/query/util/logging" 33 "github.com/m3db/m3/src/x/instrument" 34 xhttp "github.com/m3db/m3/src/x/net/http" 35 ) 36 37 var highPriority = zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { 38 return lvl >= zapcore.ErrorLevel 39 }) 40 41 // Panic recovers from panics and logs the error/stacktrace if possible. 42 func Panic(iOpts instrument.Options) mux.MiddlewareFunc { 43 return func(base http.Handler) http.Handler { 44 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 45 writeCheckWriter := &responseWrittenResponseWriter{writer: w} 46 w = writeCheckWriter 47 48 defer func() { 49 if err := recover(); err != nil { 50 logger := logging.WithContext(r.Context(), iOpts). 51 WithOptions(zap.AddStacktrace(highPriority)) 52 logger.Error("panic captured", zap.Any("stack", err)) 53 54 if !writeCheckWriter.Written() { 55 xhttp.WriteError(w, fmt.Errorf("caught panic: %v", err)) 56 return 57 } 58 59 // cannot write the error back to the caller, some contents already written. 60 logger.Warn("cannot write error for request; already written") 61 } 62 }() 63 64 base.ServeHTTP(w, r) 65 }) 66 } 67 } 68 69 type responseWrittenResponseWriter struct { 70 sync.RWMutex 71 writer http.ResponseWriter 72 written bool 73 } 74 75 func (w *responseWrittenResponseWriter) Written() bool { 76 w.RLock() 77 v := w.written 78 w.RUnlock() 79 return v 80 } 81 82 func (w *responseWrittenResponseWriter) setWritten() { 83 w.RLock() 84 if w.written { 85 return 86 } 87 w.RUnlock() 88 89 w.Lock() 90 w.written = true 91 w.Unlock() 92 } 93 94 func (w *responseWrittenResponseWriter) Header() http.Header { 95 return w.writer.Header() 96 } 97 98 func (w *responseWrittenResponseWriter) Write(d []byte) (int, error) { 99 w.setWritten() 100 return w.writer.Write(d) 101 } 102 103 func (w *responseWrittenResponseWriter) WriteHeader(statusCode int) { 104 w.setWritten() 105 w.writer.WriteHeader(statusCode) 106 }