2020-04-29 21:32:39 +00:00
|
|
|
// Package messagehandler contains useful helpers for recovering
|
|
|
|
// from panic conditions at runtime and logging their trace.
|
2019-03-10 22:53:28 +00:00
|
|
|
package messagehandler
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2019-03-20 14:17:44 +00:00
|
|
|
"runtime/debug"
|
2019-03-10 22:53:28 +00:00
|
|
|
|
2021-05-17 18:32:04 +00:00
|
|
|
pubsub "github.com/libp2p/go-libp2p-pubsub"
|
2019-03-10 22:53:28 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
"go.opencensus.io/trace"
|
|
|
|
)
|
|
|
|
|
2019-04-26 06:24:01 +00:00
|
|
|
const noMsgData = "message contains no data"
|
|
|
|
|
2019-03-10 22:53:28 +00:00
|
|
|
var log = logrus.WithField("prefix", "message-handler")
|
|
|
|
|
|
|
|
// SafelyHandleMessage will recover and log any panic that occurs from the
|
|
|
|
// function argument.
|
2021-05-17 18:32:04 +00:00
|
|
|
func SafelyHandleMessage(ctx context.Context, fn func(ctx context.Context, message *pubsub.Message) error, msg *pubsub.Message) {
|
2019-12-24 04:59:08 +00:00
|
|
|
defer HandlePanic(ctx, msg)
|
2019-03-10 22:53:28 +00:00
|
|
|
|
|
|
|
// Fingers crossed that it doesn't panic...
|
2019-03-17 02:56:05 +00:00
|
|
|
if err := fn(ctx, msg); err != nil {
|
|
|
|
// Report any error on the span, if one exists.
|
|
|
|
if span := trace.FromContext(ctx); span != nil {
|
|
|
|
span.SetStatus(trace.Status{
|
|
|
|
Code: trace.StatusCodeInternal,
|
|
|
|
Message: err.Error(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
2019-03-10 22:53:28 +00:00
|
|
|
}
|
2019-12-24 04:59:08 +00:00
|
|
|
|
|
|
|
// HandlePanic returns a panic handler function that is used to
|
|
|
|
// capture a panic.
|
2021-05-17 18:32:04 +00:00
|
|
|
func HandlePanic(ctx context.Context, msg *pubsub.Message) {
|
2019-12-24 04:59:08 +00:00
|
|
|
if r := recover(); r != nil {
|
|
|
|
printedMsg := noMsgData
|
|
|
|
if msg != nil {
|
2021-05-17 18:32:04 +00:00
|
|
|
printedMsg = msg.String()
|
2019-12-24 04:59:08 +00:00
|
|
|
}
|
|
|
|
log.WithFields(logrus.Fields{
|
|
|
|
"r": r,
|
|
|
|
"msg": printedMsg,
|
|
|
|
}).Error("Panicked when handling p2p message! Recovering...")
|
|
|
|
|
|
|
|
debug.PrintStack()
|
|
|
|
|
|
|
|
if ctx == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if span := trace.FromContext(ctx); span != nil {
|
|
|
|
span.SetStatus(trace.Status{
|
|
|
|
Code: trace.StatusCodeInternal,
|
|
|
|
Message: fmt.Sprintf("Panic: %v", r),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|