Skip to content

State Machines in Infrastructure Software

State Machines in Infrastructure Software Written by:

Igor Gorovyy
DevOps Engineer Lead & Senior Solutions Architect

LinkedIn


Sheep and Shepherd have three state machines: Container states, Pod phases, Node conditions. Each defines the allowed states and transitions. Without them the code turns into a pile of if/else, and nobody can say what state a container is actually in.

Container States (Sheep)

stateDiagram-v2
    [*] --> created : Manager.Create()
    created --> running : Manager.Start()
    running --> stopped : Manager.Stop()
    running --> stopped : Process exits
    stopped --> running : Manager.Start() (restart)
    stopped --> [*] : Manager.Remove()
    created --> [*] : Manager.Remove()

    note right of created
        Overlay mounted
        state.json written
        Process NOT started
    end note

    note right of running
        Namespaces active
        Cgroups applied
        Network configured
        PID tracked
    end note

    note right of stopped
        Process stopped
        Cgroups removed
        Overlay still exists
        Exit code recorded
    end note

Three states, clear rules:

type State string

const (
    StateCreated State = "created"
    StateRunning State = "running"
    StateStopped State = "stopped"
)

Transition Matrix

Current state Start() Stop() Remove()
created -> running error -> removed
running error (already running) -> stopped error (stop first)
stopped -> running error (not running) -> removed

Each operation checks the current state:

func (m *Manager) Start(id string) error {
    c, ok := m.containers[id]
    if !ok {
        return fmt.Errorf("container %s not found", ShortID(id))
    }
    if c.State == StateRunning {
        return fmt.Errorf("container %s already running",
            ShortID(id))
    }
    // ... start
    c.State = StateRunning
    c.Pid = pid
    c.StartedAt = time.Now()
    return m.saveState(c)
}

func (m *Manager) Stop(id string) error {
    c, ok := m.containers[id]
    if c.State != StateRunning {
        return fmt.Errorf("container %s not running",
            ShortID(id))
    }
    // ... stop
    c.State = StateStopped
    c.ExitCode = exitCode
    c.StoppedAt = time.Now()
    c.Pid = 0
    return m.saveState(c)
}

func (m *Manager) Remove(id string) error {
    c, ok := m.containers[id]
    if c.State == StateRunning {
        return fmt.Errorf(
            "container %s is running, stop it first",
            ShortID(id))
    }
    delete(m.containers, id)
    m.cleanupOverlay(id)
    os.RemoveAll(filepath.Join(m.baseDir, "containers", id))
    return nil
}

Without a state machine the code would look like this:

// Bad - what's going on here?
if c.Pid > 0 && c.ExitCode == 0 && c.StartedAt.After(c.StoppedAt) {
    // running?.. maybe?
}

// Good - immediately clear
if c.State == StateRunning {
    // running
}

Pod Phases (Shepherd)

stateDiagram-v2
    [*] --> Pending : API Server creates
    Pending --> Pending : Scheduler assigns NodeName
    Pending --> Running : Agent starts all containers
    Pending --> Failed : Agent couldn't start
    Running --> Failed : Container crashed
    Running --> Succeeded : Process exited with code 0

    note right of Pending
        Without NodeName: waiting for scheduler
        With NodeName: waiting for agent
    end note
type PodPhase string

const (
    PodPending   PodPhase = "Pending"
    PodRunning   PodPhase = "Running"
    PodSucceeded PodPhase = "Succeeded"
    PodFailed    PodPhase = "Failed"
)

Look at Pending: it has two "sub-states" - with NodeName and without. The Scheduler sets NodeName, but Phase stays Pending. The Pod only becomes Running when the Agent actually starts the containers. This lets you distinguish "waiting for scheduler" from "waiting for agent" with a single field.

Who Changes the Phase

Transition Who does it Where in code
-> Pending API Server apiserver.go: createPod()
Pending (+ NodeName) Scheduler scheduler.go: SchedulePod()
Pending -> Running Agent agent.go: startPod()
Pending -> Failed Agent agent.go: startPod()
Running -> Failed Agent agent.go: checkPod()

The API Server never sets Running. The Agent never sets Pending. Each component owns its transitions.

Node Conditions (Shepherd)

stateDiagram-v2
    [*] --> Ready : Agent registers
    Ready --> Ready : Heartbeat every 10s
    Ready --> NotReady : Heartbeat timeout > 30s
    NotReady --> Ready : Heartbeat received
    NotReady --> [*] : Node deleted
type NodeCondition string

const (
    NodeReady    NodeCondition = "Ready"
    NodeNotReady NodeCondition = "NotReady"
)

The Scheduler checks the condition during filtering:

func (s *Scheduler) filterNodes(nodes []*Node, pod *Pod) []*Node {
    for _, node := range nodes {
        if node.Status.Condition != NodeReady {
            continue // skip NotReady nodes
        }
        if time.Since(node.Status.LastHeartbeat) > 30*time.Second {
            continue // stale heartbeat
        }
        // ...
    }
}

Double check: both the Condition and the timestamp. The NodeController updates the Condition, but the Scheduler doesn't trust the Condition alone - it also checks heartbeat freshness.

Bugs That State Machines Prevent

1. Deleting a running container: Without the check: overlay gets unmounted while the process is still writing files. Result: data corruption. With state machine: Remove() returns "stop it first".

2. Double Start: Without the check: a second clone() creates a second process with the same rootfs. The PID gets overwritten. The first process becomes an orphan. With state machine: Start() returns "already running".

3. Scheduler assigns to a dead node: Without the check: pod is assigned, agent isn't running, pod stays Pending forever. With state machine: filterNodes() rejects NotReady nodes.

4. Agent starts containers for a Running pod: Without the check: the Agent sees its pod and starts containers again. Result: duplicates. With state machine: the Agent only processes Pending pods, Running ones only get health checks.

How the State Machines Connect

graph LR
    subgraph "Container (Sheep)"
        CS["created -> running -> stopped"]
    end

    subgraph "Pod (Shepherd)"
        PS["Pending -> Running -> Failed"]
    end

    subgraph "Node (Shepherd)"
        NS["Ready <-> NotReady"]
    end

    NS -->|"Ready? -> can schedule"| PS
    PS -->|"Pending + NodeName"| CS
    CS -->|"running -> all Ready"| PS

Node condition affects pod scheduling. Pod phase determines whether the Agent should create containers. Container state is reflected back into Pod status.

Where the Gotchas Are

State machines in Sheep are informal - they're if/else checks, not an explicit state machine framework. There's no runtime visualization of allowed transitions. If you add a new state, you have to manually check every place where State is checked.

Two more traps:

  • In-memory state vs on-disk state can drift. c.State = StateRunning changes the struct in memory, saveState writes it to disk. If the process crashes between the two, disk says one thing and reality says another. After a restart Sheep trusts the file, not the actual PID.
  • There's no transition for "the process died on its own." If a container crashes but Sheep didn't stop it, the state stays running until something checks the PID. This is the classic reaping problem - real runtimes catch SIGCHLD.

Fun facts

  • Kubernetes deliberately calls it a Pod phase, not a state: the phase is an intentionally coarse, high-level signal (Pending/Running/Succeeded/Failed/Unknown), while detailed state lives in conditions. So new details can be added without breaking what the old phases meant.
  • The Unknown phase in Kubernetes doesn't mean the pod is broken - it means the connection to the kubelet was lost, so the apiserver simply doesn't know the truth. Shepherd models this differently: through the Node condition NotReady, not a separate pod phase.
  • The classic "zombie process" bug is also a state machine: a process in state Z (zombie) is already dead, but its entry in the process table lives on until the parent calls wait(). PID 1 inside a container is obligated to reap orphans, otherwise they pile up.
  • The fact that each component owns its own transitions (the API Server never sets Running, the Agent never sets Pending) is how Kubernetes works too: each controller writes only its own fields and doesn't touch transitions owned by someone else.
  • The OCI Runtime Spec, which runc implements, has almost the same set: creating, created, running, stopped. The extra creating covers the window while the runtime is still setting up the container. Sheep folds it into Create().
  • Docker has more: created, running, paused, restarting, removing, exited, dead. dead is the state for a container Docker failed to remove halfway, for example when a mount is busy.
  • In Kubernetes a node going NotReady doesn't kill its pods right away. Pods get default tolerations for the not-ready and unreachable taints with tolerationSeconds: 300, so eviction starts after five minutes. A short network blip doesn't trigger a mass reschedule.
  • docker run --init (since Docker 1.13, 2017) puts tini as PID 1 in the container. All it does is reap zombies and forward signals, which is the problem from the "Where the Gotchas Are" section.
  • TCP is a state machine too: RFC 793 from 1981 describes 11 states, from LISTEN to TIME_WAIT. Those TIME_WAIT lines in ss -tan are connections that are closed but still waiting out their timer.
  • Statecharts, the nested states and parallel regions that Mermaid's stateDiagram borrows from, came from David Harel's 1987 paper. He built them for the avionics of a fighter jet, where flat state machines had too many states to draw.

What I figured out while digging into this

At first explicit states felt like bureaucracy: why created/running/stopped when there's a PID? Then I deleted a container I thought was stopped and got corrupted files. After that it made sense: a state machine is less about describing the system and more about refusing actions that make no sense. The useful part is the transitions that aren't in the table.

Second thing: one field that says "where are we now" removes a lot of guessing. Pending with and without a NodeName - one enum, two different expectations. Without it I'd need a separate boolean, and sooner or later it would disagree with the rest of the struct.

What could be improved

  • Extract transitions into an explicit table (map[State][]State of allowed next states) and a single transition() function instead of scattered ifs - then adding a state becomes one change.
  • A reaper for processes: catch SIGCHLD and automatically move the container to stopped with the real exit code, instead of trusting the last written state.
  • Record transition history (at least the last N) in state.json - it answers "how did this pod end up Failed" without guessing from logs.
  • Add an Unknown or Terminating phase/state to handle graceful shutdown properly - right now "stopping right now" has no representation.

Try It Yourself

# Try disallowed transitions:
sudo ./sheep rm $(sudo ./sheep ps -q)  # error: running, stop first
sudo ./sheep stop non-existent          # error: not found
# View states:
sudo ./sheep ps -a  # created, running, stopped

Final article of the series - Entity Relationships: the full data model.

Resources

Source code for the series: github.com/igorgorovoy/sheep-shepherd-meadow

Previous: Filesystem Layout | Next: Entity Relationships