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

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
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
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics 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
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
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
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
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
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New

We're in Beta

About us Mission Statement