Supervisors
A supervisor in Elixir is a process whose only job is to start children and watch them. When a child ends, the supervisor starts a new one according to the child specification, and the rest of the tree keeps running. This is the half of "let it crash" that makes the phrase true: the child does not rescue its errors, and the supervisor owns the recovery. The GenServer lesson shows the child; this one shows the parent.
A supervisor and a child
Supervisor.start_link/2 takes a list of children and a strategy. The child can be a module that defines child_spec/1, which use Agent and use GenServer write for you:
supervise.exs
defmodule Counter do use Agent def start_link(_opts), do: Agent.start_link(fn -> 0 end, name: __MODULE__) def bump, do: Agent.update(__MODULE__, &(&1 + 1)) def value, do: Agent.get(__MODULE__, & &1) end {:ok, supervisor} = Supervisor.start_link([Counter], strategy: :one_for_one) Counter.bump() Counter.bump() IO.inspect(Counter.value()) [{_, pid, _, _}] = Supervisor.which_children(supervisor) Process.exit(pid, :kill) Process.sleep(50) [{_, new_pid, _, _}] = Supervisor.which_children(supervisor) IO.inspect(pid != new_pid) IO.inspect(Counter.value()) IO.inspect(Supervisor.count_children(supervisor))
elixir supervise.exs
2
true
0
%{active: 1, workers: 1, supervisors: 0, specs: 1}
The counter had reached 2, the child was killed, and the supervisor started a fresh one with 0. The pid changed and the count of children stayed at one. The kill is here only to make the restart visible; the same path runs when the child raises, returns an error or exits.
The child that comes back
The restart is why a program does not need a rescue in every function. The child is a process with no memory of the crash, the supervisor has the specification of how to start it, and the callers see a short gap rather than a dead system. The strategy :one_for_one restarts only the child that died; the restart strategies lesson compares it with :one_for_all and :rest_for_one.
A supervisor is itself a child when it sits inside another supervisor, which is how a tree is built. The top of the tree is started by the application, and the OTP applications lesson shows the application/0 callback that starts it at boot.
The child specification
A child specification is a map with an id, a start function, a type, a restart policy and a shutdown time. A module that starts more than one child of its kind writes its own child_spec/1, so the id can carry the argument:
workers.exs
defmodule Worker do use Agent def start_link(n), do: Agent.start_link(fn -> n end) def child_spec(n) do %{ id: {__MODULE__, n}, start: {__MODULE__, :start_link, [n]}, restart: :temporary } end end {:ok, supervisor} = Supervisor.start_link([{Worker, 1}, {Worker, 2}], strategy: :one_for_one) IO.inspect(Supervisor.count_children(supervisor))
elixir workers.exs
%{active: 2, workers: 2, supervisors: 0, specs: 2}
Two children of one module need two ids, and the tuple of the module and the argument is the usual choice. restart: :temporary means the child is not started again when it ends, which is right for a job whose result is already delivered.
What the supervisor reports
Supervisor.count_children/1 answers a map with the active children, all the specifications, the workers and the nested supervisors. Supervisor.which_children/1 answers one tuple per child with its id, pid, type and modules. Both are the first calls to make when a tree does not behave as expected:
- active counts the children that run now, not the specs.
- specs counts the specifications, including the children that are not running.
- An :undefined pid in a which_children/1 tuple is a child that is restarting.
The mistake: a module with no child_spec/1
A module that does not use a behaviour and does not define child_spec/1 is not a child. The supervisor refuses to start and prints the fix with the call:
badchild.exs
defmodule NotAChild do end IO.inspect(Supervisor.start_link([NotAChild], strategy: :one_for_one))
elixir badchild.exs
** (ArgumentError) The module NotAChild was given as a child to a supervisor
but it does not implement child_spec/1.
See the Supervisor documentation for more information
(elixir 1.19.7) lib/supervisor.ex:814: Supervisor.init_child/1
(elixir 1.19.7) lib/enum.ex:1688: Enum."-map/2-lists^map/1-1-"/2
(elixir 1.19.7) lib/supervisor.ex:800: Supervisor.init/2
(elixir 1.19.7) lib/supervisor.ex:724: Supervisor.start_link/2
badchild.exs:4: (file)
The message explains both fixes: define child_spec/1 when the module belongs to the program, or pass a full specification map when it does not. The middle of the message is left out of the block because it repeats the two examples; the first and last lines are the ones a reader needs.
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.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the job of a supervisor?
Answer
To start children and restart them when they end
A supervisor owns the start and the restart of its children, not their work.
-
What does
use Agentanduse GenServergive a module for supervision?Answer
A child_spec/1 function
The use macro defines child_spec/1, which is what Supervisor.start_link needs.
-
What does
:one_for_onemean?Answer
Only the child that died is restarted
One-for-one restarts the failed child alone; the siblings keep their state.
-
Why does a restarted child start with its initial state?
Answer
Because the new process runs start_link again, and the old state is gone
The state lived in the dead process; the restart runs the start function from the beginning.
-
What does this program print?
defmodule C do use Agent def start_link(_), do: Agent.start_link(fn -> 0 end, name: __MODULE__) def bump, do: Agent.update(__MODULE__, &(&1 + 1)) def value, do: Agent.get(__MODULE__, & &1) end {:ok, sup} = Supervisor.start_link([C], strategy: :one_for_one) C.bump() [{_, pid, _, _}] = Supervisor.which_children(sup) Process.exit(pid, :kill) Process.sleep(50) IO.puts(C.value())Answer
0
The killed child is replaced by a new one with the initial value 0.
-
What does this program print?
defmodule C do use Agent def start_link(_), do: Agent.start_link(fn -> 0 end) end {:ok, sup} = Supervisor.start_link([C], strategy: :one_for_one) IO.inspect(Supervisor.count_children(sup))Answer
%{active: 1, workers: 1, supervisors: 0, specs: 1}
One worker child is active and one spec exists.
-
What does this program print?
defmodule W do use Agent def start_link(n), do: Agent.start_link(fn -> n end) def child_spec(n) do %{id: {__MODULE__, n}, start: {__MODULE__, :start_link, [n]}, restart: :temporary} end end {:ok, sup} = Supervisor.start_link([{W, 1}, {W, 2}], strategy: :one_for_one) IO.inspect(Supervisor.count_children(sup))Answer
%{active: 2, workers: 2, supervisors: 0, specs: 2}
The two ids keep the children apart, and both start.
-
A child has
restart: :temporaryand its work finishes normally. What does the supervisor do?Answer
It leaves the child ended and keeps the rest of the tree
A temporary child is never restarted; its end is final.
-
A module with no
child_spec/1is passed toSupervisor.start_link. What happens?Answer
The start fails with an ArgumentError that explains the two fixes
Supervisor needs a child spec; a module without one cannot be started as a child.
-
What does
Supervisor.which_children/1answer?Answer
One tuple per child with id, pid, type and modules
The tuple names the child and its process; the state stays private to the child.
Автор статьи: Arthur Isaev