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
|
|
|
|
|
|
|
"github.com/gogo/protobuf/proto"
|
|
|
|
"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.
|
2019-03-17 02:56:05 +00:00
|
|
|
func SafelyHandleMessage(ctx context.Context, fn func(ctx context.Context, message proto.Message) error, msg proto.Message) {
|
2019-03-10 22:53:28 +00:00
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
2019-04-26 06:24:01 +00:00
|
|
|
printedMsg := noMsgData
|
2019-03-10 22:53:28 +00:00
|
|
|
if msg != nil {
|
|
|
|
printedMsg = proto.MarshalTextString(msg)
|
|
|
|
}
|
|
|
|
log.WithFields(logrus.Fields{
|
|
|
|
"r": r,
|
|
|
|
"msg": printedMsg,
|
|
|
|
}).Error("Panicked when handling p2p message! Recovering...")
|
|
|
|
|
2019-03-20 14:17:44 +00:00
|
|
|
debug.PrintStack()
|
|
|
|
|
2019-03-10 22:53:28 +00:00
|
|
|
if ctx == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if span := trace.FromContext(ctx); span != nil {
|
|
|
|
span.SetStatus(trace.Status{
|
|
|
|
Code: trace.StatusCodeInternal,
|
|
|
|
Message: fmt.Sprintf("Panic: %v", r),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
// 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
|
|
|
}
|