github.com/datadog/cilium@v1.6.12/pkg/api/apipanic.go (about)

     1  // Copyright 2018-2019 Authors of Cilium
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package api
    16  
    17  import (
    18  	"net/http"
    19  	"os"
    20  	"runtime/debug"
    21  
    22  	"github.com/cilium/cilium/pkg/logging"
    23  
    24  	"github.com/sirupsen/logrus"
    25  )
    26  
    27  // APIPanicHandler recovers from API panics and logs encountered panics
    28  type APIPanicHandler struct {
    29  	Next http.Handler
    30  }
    31  
    32  // ServeHTTP implements the http.Handler interface.
    33  // It recovers from panics of all next handlers and logs them
    34  func (h *APIPanicHandler) ServeHTTP(wr http.ResponseWriter, req *http.Request) {
    35  	defer func() {
    36  		if r := recover(); r != nil {
    37  			fields := logrus.Fields{
    38  				"panic_message": r,
    39  				"url":           req.URL.String(),
    40  				"method":        req.Method,
    41  				"client":        req.RemoteAddr,
    42  			}
    43  			log.WithFields(fields).Warn("Cilium API handler panicked")
    44  			if logging.DefaultLogger.IsLevelEnabled(logrus.DebugLevel) {
    45  				os.Stdout.Write(debug.Stack())
    46  			}
    47  			wr.WriteHeader(http.StatusInternalServerError)
    48  			if _, err := wr.Write([]byte("Internal error occurred, check Cilium logs for details.")); err != nil {
    49  				log.WithError(err).Debug("Failed to write API response")
    50  			}
    51  		}
    52  	}()
    53  	h.Next.ServeHTTP(wr, req)
    54  }