Capstone: supervising the capstone

The two capstones in Elixir are pieces of one program: a store that keeps the items and a listener that answers a request. In an OTP program both are children of one supervisor, so a crash of one restarts it and leaves the other running. This lesson puts them under one tree, checks the answers and kills a child to show the restart.

The tree

Supervisor.start_link/2 takes the two modules, and use GenServer gives each one the child specification the supervisor needs. The store keeps a list, the listener keeps a socket and the port, and the supervisor keeps both alive:

The store as a child

The store is the counter of the GenServer lesson with a list in the state. A cast adds an item without waiting, and a call reads the list:

app.exs

defmodule Store do use GenServer def start_link(_opts), do: GenServer.start_link(__MODULE__, [], name: __MODULE__) def add(item), do: GenServer.cast(__MODULE__, {:add, item}) def items, do: GenServer.call(__MODULE__, :items) @impl true def init(items), do: {:ok, items} @impl true def handle_cast({:add, item}, items), do: {:noreply, items ++ [item]} @impl true def handle_call(:items, _from, items), do: {:reply, items, items} end defmodule Listener do use GenServer def start_link(_opts), do: GenServer.start_link(__MODULE__, nil, name: __MODULE__) def port, do: GenServer.call(__MODULE__, :port) def accept, do: GenServer.call(__MODULE__, :accept) @impl true def init(_opts) do {:ok, listen} = :gen_tcp.listen(0, [:binary, packet: :raw, active: false, reuseaddr: true]) {:ok, port} = :inet.port(listen) {:ok, {listen, port}} end @impl true def handle_call(:port, _from, {_listen, port} = state), do: {:reply, port, state} def handle_call(:accept, _from, {listen, port}) do {:ok, socket} = :gen_tcp.accept(listen) {:ok, request} = :gen_tcp.recv(socket, 0) :gen_tcp.send(socket, "stored: " <> request) :gen_tcp.close(socket) {:reply, :ok, {listen, port}} end end defmodule Check do def equal!(left, right) do if left == right, do: :ok, else: raise("expected #{inspect(right)}, got #{inspect(left)}") end end {:ok, sup} = Supervisor.start_link([Store, Listener], strategy: :one_for_one) Store.add("buy milk") Check.equal!(Store.items(), ["buy milk"]) IO.puts("store check passed") {:ok, client} = :gen_tcp.connect(~c"127.0.0.1", Listener.port(), [:binary, active: false]) :gen_tcp.send(client, "milk") Listener.accept() {:ok, reply} = :gen_tcp.recv(client, 0) IO.puts("server answered: " <> reply) :gen_tcp.close(client) IO.inspect(Supervisor.count_children(sup))

The listener as a child

The listener opens the socket in init/1, the one place a GenServer may fail and have the supervisor retry. The port is part of the state, and accept/0 is a call that blocks until one client sends its request:

The checks

A check is a tiny function that raises when two values differ, which is the assertion of ExUnit without the framework. The program starts the tree, adds an item, checks the store, sends a request to the listener and prints the supervisor report:

elixir app.exs

store check passed
server answered: stored: milk
%{active: 2, workers: 2, supervisors: 0, specs: 2}

The store check reads a value a cast wrote, so it proves the message arrived before the call. The server check reads the bytes the listener wrote. Both are ordinary functions, and a test module can call the same ones; the ExUnit lesson shows the report a failure prints.

The child that restarts

Kill the store and the supervisor starts a new one with the initial list. The listener is untouched, which is the point of :one_for_one:

restart.exs

defmodule Store do use GenServer def start_link(_opts), do: GenServer.start_link(__MODULE__, [], name: __MODULE__) def add(item), do: GenServer.cast(__MODULE__, {:add, item}) def items, do: GenServer.call(__MODULE__, :items) @impl true def init(items), do: {:ok, items} @impl true def handle_cast({:add, item}, items), do: {:noreply, items ++ [item]} @impl true def handle_call(:items, _from, items), do: {:reply, items, items} end {:ok, sup} = Supervisor.start_link([Store], strategy: :one_for_one) Store.add("buy milk") IO.inspect(Store.items()) [{_, pid, _, _}] = Supervisor.which_children(sup) Process.exit(pid, :kill) Process.sleep(50) IO.inspect(Store.items()) IO.inspect(Supervisor.count_children(sup))

elixir restart.exs

["buy milk"]
[]
%{active: 1, workers: 1, supervisors: 0, specs: 1}

The list is empty after the restart because the new process runs init/1 again. A store that must survive a crash writes to a file or to ETS, and the ETS lesson shows the table that outlives one process. The supervisors lesson and the restart strategies lesson take the tree apart.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container. The listener uses the loopback interface only.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why are the store and the listener children of one supervisor?

    Answer

    So a crash of one is restarted while the other keeps running

    The supervisor owns the restart, and one_for_one restarts only the failed child.

  2. Where does the listener open its socket?

    Answer

    In init/1

    init/1 is where a GenServer sets up the state it needs, and a failure there is retried.

  3. What does Supervisor.count_children/1 report?

    Answer

    The active children, the specs, the workers and the nested supervisors

    The map summarises the tree from the supervisor point of view.

  4. What happens to the store state after the store child is killed?

    Answer

    It is lost, and the new child starts with the initial state

    The state lived in the killed process; the restart runs init/1 again.

  5. What does this program print? defmodule S do use GenServer def start_link(_), do: GenServer.start_link(__MODULE__, [], name: __MODULE__) def add(x), do: GenServer.cast(__MODULE__, {:add, x}) def items, do: GenServer.call(__MODULE__, :items) @impl true def init(items), do: {:ok, items} @impl true def handle_cast({:add, x}, items), do: {:noreply, items ++ [x]} @impl true def handle_call(:items, _from, items), do: {:reply, items, items} end {:ok, _} = S.start_link([]) S.add(:a) IO.inspect(S.items())

    Answer

    [:a]

    The cast arrives before the call, and the state is the list with one item.

  6. What does this program print? defmodule S do use GenServer def start_link(_), do: GenServer.start_link(__MODULE__, [], name: __MODULE__) def add(x), do: GenServer.cast(__MODULE__, {:add, x}) def items, do: GenServer.call(__MODULE__, :items) @impl true def init(items), do: {:ok, items} @impl true def handle_cast({:add, x}, items), do: {:noreply, items ++ [x]} @impl true def handle_call(:items, _from, items), do: {:reply, items, items} end {:ok, sup} = Supervisor.start_link([S], strategy: :one_for_one) S.add(:a) [{_, pid, _, _}] = Supervisor.which_children(sup) Process.exit(pid, :kill) Process.sleep(50) IO.inspect(S.items())

    Answer

    []

    The killed child is replaced by a new one with the initial empty list.

  7. What does the check if left == right, do: :ok, else: raise(...) do?

    Answer

    Raises when the two values differ

    It is a minimal assertion for a script that has no ExUnit.

  8. Which strategy restarts only the killed child?

    Answer

    :one_for_one

    One-for-one restarts the failed child and leaves its siblings.

  9. Where should a value that must survive a restart live?

    Answer

    In a file or an ETS table

    The process state is lost; a file or ETS outlives the process.

  10. Why does the listener need a call to accept?

    Answer

    The accept blocks until a client connects, so it runs on demand

    The call runs the blocking accept in the server when a client is expected.

Автор статьи: Arthur Isaev