forked from alileza/panics
-
Notifications
You must be signed in to change notification settings - Fork 11
/
panics.go
386 lines (344 loc) · 8.64 KB
/
panics.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package panics
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"os"
"os/signal"
"runtime/debug"
"strings"
"syscall"
"time"
"github.com/eapache/go-resiliency/breaker"
"github.com/gin-gonic/gin"
"github.com/julienschmidt/httprouter"
"github.com/nsqio/go-nsq"
"google.golang.org/grpc"
)
var (
env string
filepath string
slackWebhookURL string
slackChannel string
tagString string
capturedBadDeployment bool
customMessage string
// circuit breaker
cb *breaker.Breaker
// ErrorPanic variable used as global error message
ErrorPanic = errors.New("Panic happened")
)
type Tags map[string]string
type Options struct {
Env string
Filepath string
SentryDSN string
SlackWebhookURL string
SlackChannel string
Tags Tags
CustomMessage string
DontLetMeDie bool
}
func SetOptions(o *Options) {
filepath = o.Filepath
slackWebhookURL = o.SlackWebhookURL
slackChannel = o.SlackChannel
env = o.Env
var tmp []string
for key, val := range o.Tags {
tmp = append(tmp, fmt.Sprintf("`%s: %s`", key, val))
}
tagString = strings.Join(tmp, " | ")
customMessage = o.CustomMessage
// set circuit breaker to nil
if o.DontLetMeDie {
cb = nil
}
CaptureBadDeployment()
}
func init() {
env = os.Getenv("TKPENV")
// circuitbreaker to let apps died when got too many panics
cb = breaker.New(3, 2, time.Minute*1)
}
// CaptureHandler handle panic on http handler.
func CaptureHandler(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
request, _ := httputil.DumpRequest(r, true)
defer func() {
if !recoveryBreak() {
r := panicRecover(recover())
if r != nil {
publishError(r, request, true)
http.Error(w, r.Error(), http.StatusInternalServerError)
}
}
}()
h.ServeHTTP(w, r)
}
}
// CaptureHTTPRouterHandler handle panic on httprouter handler.
func CaptureHTTPRouterHandler(h httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
request, _ := httputil.DumpRequest(r, true)
defer func() {
if !recoveryBreak() {
r := panicRecover(recover())
if r != nil {
publishError(r, request, true)
http.Error(w, r.Error(), http.StatusInternalServerError)
}
}
}()
h(w, r, ps)
}
}
// CaptureNegroniHandler handle panic on negroni handler.
func CaptureNegroniHandler(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
request, _ := httputil.DumpRequest(r, true)
defer func() {
if !recoveryBreak() {
r := panicRecover(recover())
if r != nil {
publishError(r, request, true)
http.Error(w, r.Error(), http.StatusInternalServerError)
}
}
}()
next(w, r)
}
// CaptureGinHandler handle panic on gin handler.
func CaptureGinHandler() gin.HandlerFunc {
return func(c *gin.Context) {
request, _ := httputil.DumpRequest(c.Request, true)
defer func() {
if !recoveryBreak() {
r := panicRecover(recover())
if r != nil {
publishError(r, request, true)
http.Error(c.Writer, r.Error(), http.StatusInternalServerError)
}
}
}()
c.Next()
}
}
// Capture will publish any errors
func Capture(err string, message ...string) {
var tmp string
for i, val := range message {
if i == 0 {
tmp += val
} else {
tmp += fmt.Sprintf("\n\n%s", val)
}
}
publishError(errors.New(err), []byte(tmp), false)
}
// Capture will publish any errors with stack trace
func CaptureWithStackTrace(err string, message ...string) {
var tmp string
for i, val := range message {
if i == 0 {
tmp += val
} else {
tmp += fmt.Sprintf("\n\n%s", val)
}
}
publishError(errors.New(err), []byte(tmp), true)
}
// CaptureBadDeployment will listen to SIGCHLD signal, and send notification when it's receive one.
func CaptureBadDeployment() {
if !capturedBadDeployment {
capturedBadDeployment = true
go func() {
term := make(chan os.Signal)
signal.Notify(term, syscall.SIGUSR1)
for {
select {
case <-term:
publishError(errors.New("Failed to deploy an application"), nil, false)
}
}
}()
}
}
// CaptureNSQConsumer capture panics on NSQ consumer
func CaptureNSQConsumer(handler nsq.HandlerFunc) nsq.HandlerFunc {
return func(message *nsq.Message) error {
defer func() {
r := panicRecover(recover())
if r != nil {
publishError(r, nil, true)
}
}()
return handler(message)
}
}
// CaptureGoroutine wrap function call with goroutines and send notification when there's panic inside it
//
// Receives handle function that will be executed on normal condition and recovery function that will be executed in-case there's panic
func CaptureGoroutine(handleFn func(), recoveryFn func()) {
defer func() {
if !recoveryBreak() {
rcv := panicRecover(recover())
if rcv != nil {
fmt.Fprintf(os.Stderr, "Panic: %+v\n", rcv)
debug.PrintStack()
publishError(rcv, nil, true)
recoveryFn()
}
}
}()
handleFn()
}
// HTTPRecoveryMiddleware act as middleware that capture panics standard in http handler
func HTTPRecoveryMiddleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
request, _ := httputil.DumpRequest(r, true)
defer func() {
if !recoveryBreak() {
rcv := panicRecover(recover())
if rcv != nil {
// log the panic
fmt.Fprintf(os.Stderr, "Panic: %+v\n", rcv)
debug.PrintStack()
publishError(rcv, request, true)
http.Error(w, rcv.Error(), http.StatusInternalServerError)
}
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
// UnaryServerInterceptor intercept the execution of a unary RPC on the server when panic happen
func UnaryServerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
defer func() {
if !recoveryBreak() {
rcv := panicRecover(recover())
if rcv != nil {
fmt.Fprintf(os.Stderr, "Panic: %+v\n", rcv)
debug.PrintStack()
publishError(rcv, nil, true)
}
}
}()
return handler(ctx, req)
}
func panicRecover(rc interface{}) error {
if cb != nil {
r := cb.Run(func() error {
return recovery(rc)
})
return r
}
return recovery(rc)
}
func recoveryBreak() bool {
if cb == nil {
return false
}
if err := cb.Run(func() error {
return nil
}); err == breaker.ErrBreakerOpen {
return true
}
return false
}
func recovery(r interface{}) error {
var err error
if r != nil {
switch t := r.(type) {
case string:
err = errors.New(t)
case error:
err = t
default:
err = errors.New("Unknown error")
}
}
return err
}
func publishError(errs error, reqBody []byte, withStackTrace bool) {
var text string
var snip string
var buffer bytes.Buffer
errorStack := debug.Stack()
buffer.WriteString(fmt.Sprintf(`[%s] *%s*`, env, errs.Error()))
if len(tagString) > 0 {
buffer.WriteString(" | " + tagString)
}
if customMessage != "" {
buffer.WriteString("\n" + customMessage + "\n")
}
if reqBody != nil {
buffer.WriteString(fmt.Sprintf(" ```%s``` ", string(reqBody)))
}
text = buffer.String()
if errorStack != nil && withStackTrace {
snip = fmt.Sprintf("```\n%s```", string(errorStack))
}
if slackWebhookURL != "" {
go postToSlack(buffer.String(), snip)
}
if filepath != "" {
go func() {
fp := fmt.Sprintf("%s/panics.log", filepath)
file, err := os.OpenFile(fp, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
log.Printf("[panics] failed to open file %s", fp)
return
}
file.Write([]byte(text))
file.Write([]byte(snip + "\r\n"))
file.Close()
}()
}
}
func postToSlack(text, snip string) {
payload := map[string]interface{}{
"text": text,
//Enable slack to parse mention @<someone>
"link_names": 1,
"attachments": []map[string]interface{}{
map[string]interface{}{
"text": snip,
"color": "#e50606",
"title": "Stack Trace",
"mrkdwn_in": []string{"text"},
},
},
}
if slackChannel != "" {
payload["channel"] = slackChannel
}
b, err := json.Marshal(payload)
if err != nil {
log.Println("[panics] marshal err", err, text, snip)
return
}
client := http.Client{
Timeout: 5 * time.Second,
}
resp, err := client.Post(slackWebhookURL, "application/json", bytes.NewBuffer(b))
if err != nil {
log.Printf("[panics] error on capturing error : %s %s %s\n", err.Error(), text, snip)
return
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("[panics] error on capturing error : %s %s %s\n", err, text, snip)
return
}
log.Printf("[panics] error on capturing error : %s %s %s\n", string(b), text, snip)
}
}