From d6b07f12ff5064682b722f77bbb4436451bfcdab Mon Sep 17 00:00:00 2001 From: Ophestra Date: Mon, 28 Jul 2025 01:44:31 +0900 Subject: container: forward context cancellation This allows container processes to exit gracefully. Signed-off-by: Ophestra --- container/container.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'container/container.go') diff --git a/container/container.go b/container/container.go index 941b6631..09360df5 100644 --- a/container/container.go +++ b/container/container.go @@ -21,6 +21,10 @@ const ( // Nonexistent is a path that cannot exist. // /proc is chosen because a system with covered /proc is unsupported by this package. Nonexistent = "/proc/nonexistent" + + // CancelSignal is the signal expected by container init on context cancel. + // A custom [Container.Cancel] function must eventually deliver this signal. + CancelSignal = SIGTERM ) type ( @@ -62,6 +66,8 @@ type ( Path string // Initial process argv. Args []string + // Deliver SIGINT to the initial process on context cancellation. + ForwardCancel bool // Mapped Uid in user namespace. Uid int @@ -129,7 +135,7 @@ func (p *Container) Start() error { if p.Cancel != nil { p.cmd.Cancel = func() error { return p.Cancel(p.cmd) } } else { - p.cmd.Cancel = func() error { return p.cmd.Process.Signal(SIGTERM) } + p.cmd.Cancel = func() error { return p.cmd.Process.Signal(CancelSignal) } } p.cmd.Dir = "/" p.cmd.SysProcAttr = &SysProcAttr{ @@ -226,6 +232,14 @@ func (p *Container) String() string { p.Args, !p.SeccompDisable, len(p.SeccompRules), int(p.SeccompFlags), int(p.SeccompPresets)) } +// ProcessState returns the address to os.ProcessState held by the underlying [exec.Cmd]. +func (p *Container) ProcessState() *os.ProcessState { + if p.cmd == nil { + return nil + } + return p.cmd.ProcessState +} + func New(ctx context.Context, name string, args ...string) *Container { return &Container{name: name, ctx: ctx, Params: Params{Args: append([]string{name}, args...), Dir: "/", Ops: new(Ops)}, -- cgit v1.3.1