Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion .github/workflows/pr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ permissions:
pull-requests: read

env:
DAGGER_VERSION: "0.20.6"
DAGGER_VERSION: "0.20.8"

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
Expand Down
12 changes: 11 additions & 1 deletion cmd/run/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ Examples:

const runShortDesc string = "Start the stereosd daemon"

var listenMode string
var (
listenMode string
poweroffMode string
)

// NewRunCmd creates the "run" subcommand.
func NewRunCmd() *cobra.Command {
Expand All @@ -44,6 +47,8 @@ func NewRunCmd() *cobra.Command {

cmd.Flags().StringVar(&listenMode, "listen-mode", "auto",
`Control plane listener mode: "vsock", "tcp", or "auto" (try vsock, fall back to tcp)`)
Comment thread
yeazelm marked this conversation as resolved.
Resolved
cmd.Flags().StringVar(&poweroffMode, "poweroff", "systemctl",
`Shutdown power-off strategy: "systemctl" (systemd) or "signal-init" (SIGTERM PID 1, for capstan)`)

return cmd
}
Expand All @@ -52,11 +57,16 @@ func runDaemon() error {
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.Println("stereosd: starting StereOS daemon")

if err := stereosd.ValidatePoweroffMode(poweroffMode); err != nil {
return err
}

ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()

config := stereosd.DefaultConfig()
config.ListenMode = listenMode
config.PoweroffMode = poweroffMode

daemon := stereosd.NewDaemonWithConfig(config)
if err := daemon.Run(ctx); err != nil {
Expand Down
98 changes: 86 additions & 12 deletions pkg/shutdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,116 @@
// When the host sends a shutdown command (via "mb down"), stereosd:
// 1. Unmounts all shared directories
// 2. Syncs filesystems
// 3. Initiates system shutdown via systemctl poweroff
// 3. Powers the machine off using the configured strategy
//
// agentd is an independent systemd service that manages its own lifecycle.
// When systemctl poweroff runs, systemd sends SIGTERM to all services
// (including agentd), allowing each to shut down gracefully within their
// configured TimeoutStopSec.
// The power-off strategy depends on the init system:
// - Under the full systemd-based stereOS image, `systemctl poweroff` lets
// systemd SIGTERM every service (including agentd) for graceful shutdown.
// - Under a minimal init (capstan as PID 1), there is no systemd; instead we
// SIGTERM PID 1 and let init stop the supervised services and call
// reboot(2) itself.
package stereosd

import (
"context"
"fmt"
"log"
"syscall"
)

// Poweroff strategy names (Config.PoweroffMode).
const (
// PoweroffSystemctl powers off via `systemctl poweroff`. Default; correct
// under the systemd-based stereOS image.
PoweroffSystemctl = "systemctl"
// PoweroffSignalInit asks PID 1 to shut down by sending it SIGTERM. Use
// under a minimal init (capstan) that owns the orderly stop + power-off.
PoweroffSignalInit = "signal-init"
)

// poweroffFunc performs the final power-off step of a shutdown.
type poweroffFunc func(Commander, func() error) error

func systemctlPoweroff(c Commander, _ func() error) error {
return c.Run("systemctl", "poweroff")
}

func killPID1() error {
return syscall.Kill(1, syscall.SIGTERM)
}

func signalInitPoweroff(_ Commander, killPID1 func() error) error {
// Under a minimal init (capstan as PID 1), SIGTERM tells init to stop the
// supervised services and reboot(RB_POWER_OFF). No command is run.
return killPID1()
}

func poweroffFor(mode string) poweroffFunc {
switch mode {
case "", PoweroffSystemctl:
return systemctlPoweroff
case PoweroffSignalInit:
return signalInitPoweroff
default:
return func(Commander, func() error) error {
return ValidatePoweroffMode(mode)
}
}
}

// ValidatePoweroffMode returns an error when mode is not a supported power-off
// strategy.
func ValidatePoweroffMode(mode string) error {
switch mode {
case "", PoweroffSystemctl, PoweroffSignalInit:
return nil
default:
return fmt.Errorf("unknown poweroff mode %q (valid: %q, %q)", mode, PoweroffSystemctl, PoweroffSignalInit)
}
}

// ShutdownCoordinator manages the graceful shutdown sequence.
type ShutdownCoordinator struct {
mounts *MountManager
lifecycle *LifecycleManager
commander Commander
poweroff poweroffFunc
killPID1 func() error
}

// NewShutdownCoordinator creates a new shutdown coordinator.
// NewShutdownCoordinator creates a new shutdown coordinator. poweroffMode
// selects the final power-off step (see the Poweroff* constants); an empty or
// unknown value makes shutdown return a power-off error.
func NewShutdownCoordinator(
mounts *MountManager,
lifecycle *LifecycleManager,
commander Commander,
poweroffMode string,
) *ShutdownCoordinator {
return newShutdownCoordinatorWithKiller(mounts, lifecycle, commander, poweroffMode, killPID1)
}

func newShutdownCoordinatorWithKiller(
mounts *MountManager,
lifecycle *LifecycleManager,
commander Commander,
poweroffMode string,
killPID1 func() error,
) *ShutdownCoordinator {
if commander == nil {
commander = ExecCommander{}
}
if killPID1 == nil {
killPID1 = func() error {
return fmt.Errorf("kill PID 1 function is not configured")
}
}
return &ShutdownCoordinator{
mounts: mounts,
lifecycle: lifecycle,
commander: commander,
poweroff: poweroffFor(poweroffMode),
killPID1: killPID1,
}
}

Expand All @@ -60,12 +136,10 @@ func (sc *ShutdownCoordinator) Execute(ctx context.Context, payload *ShutdownPay
log.Printf("shutdown: sync warning: %v", err)
}

// Step 3: Initiate system shutdown. systemd will send SIGTERM to all
// managed services (including agentd), allowing each to handle its
// own graceful shutdown.
log.Println("shutdown: initiating system poweroff")
if err := sc.commander.Run("systemctl", "poweroff"); err != nil {
return fmt.Errorf("shutdown: systemctl poweroff: %w", err)
// Step 3: Power off using the configured strategy.
log.Println("shutdown: initiating power-off")
if err := sc.poweroff(sc.commander, sc.killPID1); err != nil {
return fmt.Errorf("shutdown: poweroff: %w", err)
}

return nil
Expand Down
39 changes: 39 additions & 0 deletions pkg/shutdown_strategy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package stereosd

import (
"context"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

var _ = Describe("ShutdownCoordinator poweroff strategy", func() {
It("defaults to systemctl poweroff", func() {
cmd := newMockCommander()
sc := NewShutdownCoordinator(NewMountManager(cmd), NewLifecycleManager(), cmd, "")

Expect(sc.Execute(context.Background(), nil)).To(Succeed())
Expect(cmd.hasCommand("systemctl")).To(BeTrue())
})

It("signal-init mode signals PID 1 and never runs systemctl", func() {
killed := false

cmd := newMockCommander()
sc := newShutdownCoordinatorWithKiller(
NewMountManager(cmd),
NewLifecycleManager(),
cmd,
PoweroffSignalInit,
func() error { killed = true; return nil },
)

Expect(sc.Execute(context.Background(), nil)).To(Succeed())
Expect(killed).To(BeTrue())
Expect(cmd.hasCommand("systemctl")).To(BeFalse())
})

It("rejects unknown poweroff modes", func() {
Expect(ValidatePoweroffMode("signal_init")).To(MatchError(ContainSubstring("unknown poweroff mode")))
})
})
7 changes: 6 additions & 1 deletion pkg/stereosd.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ type Config struct {

// Commander abstracts system commands. If nil, uses real exec.
Commander Commander

// PoweroffMode selects how shutdown powers the machine off:
// "systemctl" (default) or "signal-init" (SIGTERM PID 1, for capstan).
PoweroffMode string
}

// DefaultConfig returns the default daemon configuration.
Expand All @@ -97,6 +101,7 @@ func DefaultConfig() Config {
AgentdSocketPath: AgentdSocketPath,
PollInterval: DefaultPollInterval,
RuntimeDirs: DefaultRuntimeDirs(),
PoweroffMode: PoweroffSystemctl,
}
}

Expand Down Expand Up @@ -160,7 +165,7 @@ func NewDaemonWithConfig(config Config) *Daemon {
d.ipc.SetDaemon(d)

// Shutdown coordinator
d.shutdown = NewShutdownCoordinator(mounts, lifecycle, commander)
d.shutdown = NewShutdownCoordinator(mounts, lifecycle, commander, config.PoweroffMode)

return d
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/stereosd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1518,7 +1518,7 @@ var _ = Describe("ShutdownCoordinator", func() {
lifecycle := NewLifecycleManager()
mounts := NewMountManager(cmd)

sc := NewShutdownCoordinator(mounts, lifecycle, cmd)
sc := NewShutdownCoordinator(mounts, lifecycle, cmd, PoweroffSystemctl)

ctx := context.Background()
err := sc.Execute(ctx, &ShutdownPayload{
Expand Down
Loading