Phillipp

Phillipp

DynamicSupervisor: Send message to itself after startup

Hey,

I got a module based DynamicSupervisor:

defmodule MyApp.ExampleSupervisor do
  use DynamicSupervisor

  def start_link(name) do
    IO.inspect name
    DynamicSupervisor.start_link(__MODULE__, name, name: String.to_atom("sup_example_#{name}"))
  end

  def init(name) do
    IO.inspect self()
    DynamicSupervisor.init(strategy: :one_for_one, extra_arguments: [name])
  end
end

I would like it to start children on its own so my idea was to use Process.send_after/3 in the init callback and use a handle_info callback. But that doesn’t work since the started supervisor process is not my own module but the DynamicSupervisor module itself.

Marked As Solved

gon782

gon782

There are a few considerations here:

  1. A supervisor crashing would generally be the result of multiple crashes of its children. It’s not generally advisable unless you have good reason to replay potentially crappy states. If you save too much state for these processes and that ends up being what actually killed the supervisor from the beginning, you’re only creating a cascade of crashes that will ultimately kill the entire supervision tree as the supervisors of the supervisors start crashing fast enough.

  2. It can be an idea not put logic like this in your supervisors, but instead have a managing process (I prefer to have X.Supervisor and X.Manager for whatever X is) that would deal with the logic surrounding spawning, killing, otherwise managing whatever the thing is. What that would entail in this case is the supervisor sending an asynchronous message to a manager when it starts and that manager then starting the children.

Generally I’m wary of potentially replaying poisoned state, so much so that I’ve always felt that it wasn’t worth it.

Here is a sketch of what you could do, though:

Sandbox.SomeChild:

defmodule Sandbox.SomeChild do
  use GenServer, restart: :transient

  def start_link(name), do: GenServer.start_link(__MODULE__, [name])

  def name(pid), do: GenServer.call(pid, :name)

  def init([name]), do: {:ok, name}

  def handle_call(:name, _from, name), do: {:reply, name, name}
end

Sandbox.SomeChild.Supervisor:

defmodule Sandbox.SomeChild.Supervisor do
  require Logger
  use DynamicSupervisor

  def start_link([]), do: DynamicSupervisor.start_link(__MODULE__, [], name: __MODULE__)

  def start_child(supervisor_pid, name) do
    spec = {Sandbox.SomeChild, name}
    DynamicSupervisor.start_child(supervisor_pid, spec)
  end

  def init([]) do
    Sandbox.SomeChild.Manager.start_children(self())
    DynamicSupervisor.init(strategy: :one_for_one)
  end
end

Sandbox.SomeChild.Manager:

defmodule Sandbox.SomeChild.Manager do
  use GenServer

  def start_link([]), do: GenServer.start_link(__MODULE__, [], name: __MODULE__)

  def names(pid \\ __MODULE__), do: GenServer.call(pid, :names)

  def add_name(name, pid \\ __MODULE__), do: GenServer.cast(pid, {:add_name, name})

  def start_children(supervisor_pid, pid \\ __MODULE__) do
    GenServer.cast(pid, {:start_children, supervisor_pid})
  end

  def init([]), do: {:ok, []}

  def handle_call(:names, _from, names) do
    {:reply, names, names}
  end

  def handle_cast({:add_name, name}, names) do
    {:noreply, [name | names]}
  end

  def handle_cast({:start_children, supervisor_pid}, names) do
    Enum.each(names, &Sandbox.SomeChild.Supervisor.start_child(supervisor_pid, &1))
    {:noreply, names}
  end
end
iex(1)> Sandbox.SomeChild.Manager.start_link([])
{:ok, #PID<0.163.0>}
iex(2)> Sandbox.SomeChild.Manager.add_name("hej")
:ok
iex(3)> Sandbox.SomeChild.Supervisor.start_link([])
{:ok, #PID<0.166.0>}
iex(4)> [{_, pid, _, _}] = DynamicSupervisor.which_children(Sandbox.SomeChild.Supervisor)
[{:undefined, #PID<0.168.0>, :worker, [Sandbox.SomeChild]}]
iex(5)> Sandbox.SomeChild.name(pid)
"hej"
iex(6)> Sandbox.SomeChild.Manager.names()
["hej"]
iex(1)> Sandbox.SomeChild.Manager.start_link([])
{:ok, #PID<0.154.0>}
iex(2)> Sandbox.SomeChild.Manager.add_name("hej")
:ok
iex(3)> Sandbox.SomeChild.Manager.add_name("hopp")
:ok
iex(4)> Sandbox.SomeChild.Supervisor.start_link([])
{:ok, #PID<0.158.0>}
iex(5)> [{_, child1, _, _}, {_, child2, _, _}] = DynamicSupervisor.which_children(Sandbox.SomeChild.Supervisor)
[
  {:undefined, #PID<0.160.0>, :worker, [Sandbox.SomeChild]},
  {:undefined, #PID<0.161.0>, :worker, [Sandbox.SomeChild]}
]
iex(6)> Sandbox.SomeChild.Manager.names()
["hopp", "hej"]
iex(7)> [child1, child2] |> Enum.map(&Sandbox.SomeChild.name/1)
["hopp", "hej"]

Note that if there is anything fatally wrong about the state that’s being stored in the manager you’ll have essentially only set up a guarantee that everything is going to crash almost instantly, as long as that poisoned state is used early enough in the started childrens’ lifetime. Worst case scenario the poisoned state doesn’t kill the children fast enough and you just have bombs lying there in wait, but they don’t kill anything fast enough to have the system die, so you can’t rely on a bad system being shut down for safety.

Also Liked

Phillipp

Phillipp

Thanks for the very detailed answer! You may be right and I should trust in the OTP mechanics. I gonna play with your suggestion later and report back what worked for me :slight_smile:

gon782

gon782

Your message won’t be handled until init finishes anyway. A message arriving as you are processing something will always have to wait until you loop around and process the next message. All processes are single-threaded, so you will never suddenly process a message while something else is going on. send() is completely fine to use.

On top of that your process hasn’t even started processing messages yet until after init finishes.

ragamuf

ragamuf

Late to the party but having face this problem now what worked was to place both the DynamicSupervisor and the so Initialization GenServer in a supervision tree with a rest_for _one strategy. This way whenever the DynamicSupervisor starts or is restarted following a crash the initialization routine will run and populate the DynamicSupervisor with the initial set of children.

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New

Other popular topics Top

peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement