|
| 1 | +// Copyright 2013 Martini Authors |
| 2 | +// Copyright 2014 The Macaron Authors |
| 3 | +// |
| 4 | +// Licensed under the Apache License, Version 2.0 (the "License"): you may |
| 5 | +// not use this file except in compliance with the License. You may obtain |
| 6 | +// a copy of the License at |
| 7 | +// |
| 8 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +// |
| 10 | +// Unless required by applicable law or agreed to in writing, software |
| 11 | +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | +// License for the specific language governing permissions and limitations |
| 14 | +// under the License. |
| 15 | + |
| 16 | +package middleware |
| 17 | + |
| 18 | +import ( |
| 19 | + "bytes" |
| 20 | + "fmt" |
| 21 | + "io/ioutil" |
| 22 | + "net/http" |
| 23 | + "runtime" |
| 24 | + |
| 25 | + "gopkg.in/macaron.v1" |
| 26 | + |
| 27 | + "github.com/go-macaron/inject" |
| 28 | + "github.com/grafana/grafana/pkg/log" |
| 29 | + "github.com/grafana/grafana/pkg/setting" |
| 30 | +) |
| 31 | + |
| 32 | +const ( |
| 33 | + panicHtml = `<html> |
| 34 | +<head><title>PANIC: %s</title> |
| 35 | +<meta charset="utf-8" /> |
| 36 | +<style type="text/css"> |
| 37 | +html, body { |
| 38 | + font-family: "Roboto", sans-serif; |
| 39 | + color: #333333; |
| 40 | + background-color: #ea5343; |
| 41 | + margin: 0px; |
| 42 | +} |
| 43 | +h1 { |
| 44 | + color: #d04526; |
| 45 | + background-color: #ffffff; |
| 46 | + padding: 20px; |
| 47 | + border-bottom: 1px dashed #2b3848; |
| 48 | +} |
| 49 | +pre { |
| 50 | + margin: 20px; |
| 51 | + padding: 20px; |
| 52 | + border: 2px solid #2b3848; |
| 53 | + background-color: #ffffff; |
| 54 | + white-space: pre-wrap; /* css-3 */ |
| 55 | + white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ |
| 56 | + white-space: -pre-wrap; /* Opera 4-6 */ |
| 57 | + white-space: -o-pre-wrap; /* Opera 7 */ |
| 58 | + word-wrap: break-word; /* Internet Explorer 5.5+ */ |
| 59 | +} |
| 60 | +</style> |
| 61 | +</head><body> |
| 62 | +<h1>PANIC</h1> |
| 63 | +<pre style="font-weight: bold;">%s</pre> |
| 64 | +<pre>%s</pre> |
| 65 | +</body> |
| 66 | +</html>` |
| 67 | +) |
| 68 | + |
| 69 | +var ( |
| 70 | + dunno = []byte("???") |
| 71 | + centerDot = []byte("·") |
| 72 | + dot = []byte(".") |
| 73 | + slash = []byte("/") |
| 74 | +) |
| 75 | + |
| 76 | +// stack returns a nicely formated stack frame, skipping skip frames |
| 77 | +func stack(skip int) []byte { |
| 78 | + buf := new(bytes.Buffer) // the returned data |
| 79 | + // As we loop, we open files and read them. These variables record the currently |
| 80 | + // loaded file. |
| 81 | + var lines [][]byte |
| 82 | + var lastFile string |
| 83 | + for i := skip; ; i++ { // Skip the expected number of frames |
| 84 | + pc, file, line, ok := runtime.Caller(i) |
| 85 | + if !ok { |
| 86 | + break |
| 87 | + } |
| 88 | + // Print this much at least. If we can't find the source, it won't show. |
| 89 | + fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc) |
| 90 | + if file != lastFile { |
| 91 | + data, err := ioutil.ReadFile(file) |
| 92 | + if err != nil { |
| 93 | + continue |
| 94 | + } |
| 95 | + lines = bytes.Split(data, []byte{'\n'}) |
| 96 | + lastFile = file |
| 97 | + } |
| 98 | + fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line)) |
| 99 | + } |
| 100 | + return buf.Bytes() |
| 101 | +} |
| 102 | + |
| 103 | +// source returns a space-trimmed slice of the n'th line. |
| 104 | +func source(lines [][]byte, n int) []byte { |
| 105 | + n-- // in stack trace, lines are 1-indexed but our array is 0-indexed |
| 106 | + if n < 0 || n >= len(lines) { |
| 107 | + return dunno |
| 108 | + } |
| 109 | + return bytes.TrimSpace(lines[n]) |
| 110 | +} |
| 111 | + |
| 112 | +// function returns, if possible, the name of the function containing the PC. |
| 113 | +func function(pc uintptr) []byte { |
| 114 | + fn := runtime.FuncForPC(pc) |
| 115 | + if fn == nil { |
| 116 | + return dunno |
| 117 | + } |
| 118 | + name := []byte(fn.Name()) |
| 119 | + // The name includes the path name to the package, which is unnecessary |
| 120 | + // since the file name is already included. Plus, it has center dots. |
| 121 | + // That is, we see |
| 122 | + // runtime/debug.*T·ptrmethod |
| 123 | + // and want |
| 124 | + // *T.ptrmethod |
| 125 | + // Also the package path might contains dot (e.g. code.google.com/...), |
| 126 | + // so first eliminate the path prefix |
| 127 | + if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 { |
| 128 | + name = name[lastslash+1:] |
| 129 | + } |
| 130 | + if period := bytes.Index(name, dot); period >= 0 { |
| 131 | + name = name[period+1:] |
| 132 | + } |
| 133 | + name = bytes.Replace(name, centerDot, dot, -1) |
| 134 | + return name |
| 135 | +} |
| 136 | + |
| 137 | +// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. |
| 138 | +// While Martini is in development mode, Recovery will also output the panic as HTML. |
| 139 | +func Recovery() macaron.Handler { |
| 140 | + return func(c *macaron.Context) { |
| 141 | + defer func() { |
| 142 | + if err := recover(); err != nil { |
| 143 | + stack := stack(3) |
| 144 | + |
| 145 | + panicLogger := log.Root |
| 146 | + // try to get request logger |
| 147 | + if ctx, ok := c.Data["ctx"]; ok { |
| 148 | + ctxTyped := ctx.(*Context) |
| 149 | + panicLogger = ctxTyped.Logger |
| 150 | + } |
| 151 | + |
| 152 | + panicLogger.Error("Request error", "error", err, "stack", string(stack)) |
| 153 | + |
| 154 | + // Lookup the current responsewriter |
| 155 | + val := c.GetVal(inject.InterfaceOf((*http.ResponseWriter)(nil))) |
| 156 | + res := val.Interface().(http.ResponseWriter) |
| 157 | + |
| 158 | + // respond with panic message while in development mode |
| 159 | + var body []byte |
| 160 | + if setting.Env == setting.DEV { |
| 161 | + res.Header().Set("Content-Type", "text/html") |
| 162 | + body = []byte(fmt.Sprintf(panicHtml, err, err, stack)) |
| 163 | + } |
| 164 | + |
| 165 | + res.WriteHeader(http.StatusInternalServerError) |
| 166 | + if nil != body { |
| 167 | + res.Write(body) |
| 168 | + } |
| 169 | + } |
| 170 | + }() |
| 171 | + |
| 172 | + c.Next() |
| 173 | + } |
| 174 | +} |
0 commit comments