Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drop to a shell on panic #25

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 41 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime/debug"

"github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/grpc-ecosystem/go-grpc-middleware/tags"
Expand All @@ -17,13 +18,28 @@ import (
)

var (
// supervisor is the thing that handles all of the
// running of services, including tracking whether or not
// they're even running
//
// Why is this a global variable?
// Because we need to be able to stop all services and drop to
// a shell if our init process panics, so we can suss out what
// happened.
//
// Without a global, this needs all kinds of software architecture
// changes
supervisor *Supervisor

sockAddr = "/run/vinit.sock"
svcDir = envOrDefault("SVC_DIR", "/etc/vinit/services")
certDir = "certs"
kmesgF = "/dev/kmsg"
)

func main() {
defer panicHandler()

var err error
sugar, err = NewLogger(kmesgF)
if err != nil {
Expand Down Expand Up @@ -75,8 +91,6 @@ func main() {
}

func Setup() (grpcServer *grpc.Server, err error) {
var supervisor *Supervisor

supervisor, err = New(svcDir)
if err != nil {
if _, ok := err.(ConfigParseError); !ok {
Expand Down Expand Up @@ -141,6 +155,31 @@ func loadTLSCredentials() (credentials.TransportCredentials, error) {
return credentials.NewTLS(config), nil
}

func panicHandler() {
err := recover()
if err != nil {
if supervisor != nil {
_ = supervisor.StopAll()
}

stack := string(debug.Stack())
errStr := err.(error).Error()

if sugar.c != nil {
sugar.Errorw("vinit panic!",
"error", errStr,
"trace", stack,
)
} else {
// This branch occurs on any panic before our
// kmesg handler is enabled
fmt.Printf("panic:\n%s\n%s", errStr, stack)
}

recoveryShell()
}
}

func recoveryShell() {
fmt.Println("Press Ctrl+D to reboot")

Expand Down