Skip to content

Commit 2c0ec31

Browse files
committed
cmd/run: Ensure underlying container is stopped when toolbox is killed
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 containers#1157 Signed-off-by: Ray Strode <[email protected]>
1 parent 7e2badc commit 2c0ec31

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/cmd/run.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ import (
2121
"fmt"
2222
"io"
2323
"os"
24+
"os/signal"
2425
"strings"
26+
"syscall"
2527
"time"
2628

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

268+
logrus.Debugf("Setting up monitor to stop container %s on termination", container)
269+
signalChannel := make(chan os.Signal, 1)
270+
signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
271+
272+
go func() {
273+
signal := <-signalChannel
274+
275+
logrus.Debugf("Got signal %d, killing cgroup", signal)
276+
cgroupFilePath := fmt.Sprintf("/proc/%d/cgroup", entryPointPID)
277+
cgroupId, err := os.ReadFile(cgroupFilePath)
278+
if err != nil {
279+
logrus.Debugf("Could not look up cgroup of container %s: %s", container, err)
280+
return
281+
}
282+
283+
cgroup := strings.Trim(string(cgroupId), "0:/\n")
284+
killPath := fmt.Sprintf("/sys/fs/cgroup/%s/cgroup.kill", cgroup)
285+
286+
if err := os.WriteFile(killPath, []byte("1"), 0644); err != nil {
287+
logrus.Debugf("Could not write 1 to %s: %s", killPath, err)
288+
return
289+
}
290+
}()
291+
266292
logrus.Debugf("Waiting for container %s to finish initializing", container)
267293

268294
toolboxRuntimeDirectory, err := utils.GetRuntimeDirectory(currentUser)

0 commit comments

Comments
 (0)