Add partial deadlock detection in debug mode

This commit is contained in:
Tulir Asokan
2019-04-27 15:02:52 +03:00
parent bc7e2d9a1c
commit 6f54066c43
9 changed files with 79 additions and 23 deletions

View File

@ -22,40 +22,75 @@ import (
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime/debug"
"time"
"github.com/sasha-s/go-deadlock"
)
var writer io.Writer
var RecoverPrettyPanic bool
var DeadlockDetection bool
var WriteLogs bool
var OnRecover func()
var LogDirectory = filepath.Join(os.TempDir(), "gomuks")
func init() {
var err error
writer, err = os.OpenFile("/tmp/gomuks-debug.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
func Initialize() {
err := os.MkdirAll(LogDirectory, 0750)
if err != nil {
writer = nil
RecoverPrettyPanic = false
DeadlockDetection = false
WriteLogs = false
return
}
if WriteLogs {
writer, err = os.OpenFile(filepath.Join(LogDirectory, "debug.log"), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
panic(err)
}
}
_, _ = fmt.Fprintf(writer, "======================= Debug init @ %s =======================\n", time.Now().Format("2006-01-02 15:04:05"))
if DeadlockDetection {
deadlocks, err := os.OpenFile(filepath.Join(LogDirectory, "deadlock.log"), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
panic(err)
}
deadlock.Opts.LogBuf = deadlocks
deadlock.Opts.OnPotentialDeadlock = func() {
if OnRecover != nil {
OnRecover()
}
os.Exit(88)
}
_, err = fmt.Fprintf(deadlocks, "======================= Debug init @ %s =======================\n", time.Now().Format("2006-01-02 15:04:05"))
if err != nil {
panic(err)
}
} else {
deadlock.Opts.Disable = true
}
}
func Printf(text string, args ...interface{}) {
if writer != nil {
fmt.Fprintf(writer, time.Now().Format("[2006-01-02 15:04:05] "))
fmt.Fprintf(writer, text+"\n", args...)
_, _ = fmt.Fprintf(writer, time.Now().Format("[2006-01-02 15:04:05] "))
_, _ = fmt.Fprintf(writer, text+"\n", args...)
}
}
func Print(text ...interface{}) {
if writer != nil {
fmt.Fprintf(writer, time.Now().Format("[2006-01-02 15:04:05] "))
fmt.Fprintln(writer, text...)
_, _ = fmt.Fprintf(writer, time.Now().Format("[2006-01-02 15:04:05] "))
_, _ = fmt.Fprintln(writer, text...)
}
}
func PrintStack() {
if writer != nil {
data := debug.Stack()
writer.Write(data)
_, _ = writer.Write(debug.Stack())
}
}
@ -90,10 +125,10 @@ A fatal error has occurred.
func PrettyPanic(panic interface{}) {
fmt.Print(Oops)
traceFile := fmt.Sprintf("/tmp/gomuks-panic-%s.txt", time.Now().Format("2006-01-02--15-04-05"))
traceFile := fmt.Sprintf(filepath.Join(LogDirectory, "panic-%s.txt"), time.Now().Format("2006-01-02--15-04-05"))
var buf bytes.Buffer
fmt.Fprintln(&buf, panic)
_, _ = fmt.Fprintln(&buf, panic)
buf.Write(debug.Stack())
err := ioutil.WriteFile(traceFile, buf.Bytes(), 0640)