Skip to content

Commit

Permalink
cmd/run: Ensure underlying container is stopped when toolbox is killed
Browse files Browse the repository at this point in the history
Right now "toolbox enter" creates a container on the fly, but
then lets it linger after the foreground toolbox process is
killed (for instance, from a terminal hangup).

Not killing the underlying container has the negative side effect of
stalling shutdown if a toolbox shell is running.

This commit addresses that problem by detecting when the toolbox process
is signaled, and then in response, kills off the entire cgroup associated
with the underlying container.

Closes #1157
  • Loading branch information
halfline committed Dec 22, 2022
1 parent 7e2badc commit f28ca61
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ import (
"fmt"
"io"
"os"
"os/signal"
"strings"
"syscall"
"time"

"github.com/containers/toolbox/pkg/podman"
Expand Down Expand Up @@ -263,6 +265,30 @@ func runCommand(container string,
return fmt.Errorf("invalid entry point PID of container %s", container)
}

logrus.Debugf("Setting up monitor to stop container %s on termination", container)
signalChannel := make(chan os.Signal, 1)
signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)

go func() {
signal := <-signalChannel

logrus.Debugf("Got signal %d, killing cgroup", signal)
cgroupFilePath := fmt.Sprintf("/proc/%d/cgroup", entryPointPID);
cgroupId, err := os.ReadFile(cgroupFilePath);
if err != nil {
logrus.Debugf("Could not look up cgroup of container %s: %s", container, err)
return
}

cgroup := strings.Trim(string(cgroupId), "0:/\n")
killPath := fmt.Sprintf("/sys/fs/cgroup/%s/cgroup.kill", cgroup)

if err := os.WriteFile(killPath, []byte("1"), 0644); err != nil {
logrus.Debugf("Could not write 1 to %s: %s", killPath, err)
return
}
}()

logrus.Debugf("Waiting for container %s to finish initializing", container)

toolboxRuntimeDirectory, err := utils.GetRuntimeDirectory(currentUser)
Expand Down

0 comments on commit f28ca61

Please sign in to comment.