forked from Velocidex/velociraptor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpanic.go
65 lines (57 loc) · 1.58 KB
/
panic.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
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
kingpin "github.com/alecthomas/kingpin/v2"
"github.com/mitchellh/panicwrap"
"www.velocidex.com/golang/velociraptor/config"
)
func writeLogOnPanic() error {
// Figure out the log directory.
config_obj, err := new(config.Loader).
WithFileLoader(*config_path).
WithEmbedded(*embedded_config_path).
WithEnvLoader("VELOCIRAPTOR_CONFIG").
LoadAndValidate()
if err != nil {
return fmt.Errorf("Unable to load config file: %w", err)
}
if config_obj.Logging != nil &&
config_obj.Logging.OutputDirectory != "" {
exitStatus, err := panicwrap.BasicWrap(func(output string) {
// Create a special log file in the log directory.
filename := filepath.Join(
config_obj.Logging.OutputDirectory,
fmt.Sprintf("panic-%v.log", strings.Replace(
time.Now().Format(time.RFC3339), ":", "_", -1)))
fd, err := os.OpenFile(filename,
os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return
}
fd.Write([]byte(output))
fd.Close()
})
if err != nil {
// Something went wrong setting up the panic
// wrapper. Unlikely, but possible.
panic(err)
}
// If exitStatus >= 0, then we're the parent process
// and the panicwrap re-executed ourselves and
// completed. Just exit with the proper status.
if exitStatus >= 0 {
os.Exit(exitStatus)
}
// Otherwise, exitStatus < 0 means we're the
// child. Continue executing as normal...
}
return nil
}
func FatalIfError(command *kingpin.CmdClause, cb func() error) {
err := cb()
kingpin.FatalIfError(err, command.FullCommand())
}