thomas.fortes

thomas.fortes

Best way to get a pid for a supervisors child

I’m deploying an app at fly.io that can shut down when idle, this post from Chris McCord shows how to do it, but in the app I’m using bandit and thousand island, not cowboy and ranch, so I asked @mtrudel if thousand island supported introspection and he implemented a way to get the connection pids from a server, which was awesomely nice of him.

Anyway, my solution uses the exact same structure as the Chris McCord one but replacing the use of ranch with Bandit and Thousand Island, the problem is that I don’t see anything wrong and it works perfectly, but maybe some of you know a more elegant way to fetch the pid needed, here’s the code:

 defp shutdown_when_inactive(every_ms) do
    Process.sleep(every_ms)

    pid =
      Supervisor.which_children(AppWeb.Endpoint)
      |> Enum.find(fn c ->
        case c do
          {{AppWeb.Endpoint, :http}, _pid, :worker, [Bandit]} -> true
          _ -> false
        end
      end)
      |> elem(1)

    {:ok, connections} = ThousandIsland.connection_pids(pid)

    if connections == [] do
      System.stop(0)
    else
      shutdown_when_inactive(every_ms)
    end
  end

Thanks

Most Liked

mtrudel

mtrudel

Creator of Bandit

Great to hear you got this working!

As you’ve figured out, once you get a handle on the root Bandit process (which is actually just a Thousand Island server process), you can get the list of current connection processes for it via the ThousandIsland.connection_pids/1 function added in Thousand Island 0.5.17. That part is pretty straightforward.

This leaves the problem of how to get the Bandit/Thousand Island pid from an Endpoint process (accessible via id as the Endpoint’s module name). Pulling out specific children of a supervisor (by id or otherwise) is always as awkward as you’ve done here; there’s not really an easier way. There’s a million ways to golf this sort of thing down to something more elegant but I’ve never really seen an approach I like; curious if anyone else has a better approach. FWIW I use a pattern more or less like you do here within Thousand Island.

fceruti

fceruti

Cool, thanks!

For future reference, here’s the snippet using everything I learned today :stuck_out_tongue:

 defp shutdown_when_inactive(every_ms) do
    Process.sleep(every_ms)

    {_, pid, _, _} =
      AppWeb.Endpoint
      |> Supervisor.which_children()
      |> Enum.find(&Kernel.match?({{AppWeb.Endpoint, :http}, _pid, _type, [Bandit]}, &1))

    {:ok, connections} = ThousandIsland.connection_pids(pid)

    if connections == [] do
      System.stop(0)
    else
      shutdown_when_inactive(every_ms)
    end
  end
thomas.fortes

thomas.fortes

Yeah, your approach is more elegant than mine, similar idea, cleaner execution, still wondering if someone has a different approach.

Thanks again

mtrudel

mtrudel

Creator of Bandit

:worker or :supervisor at the place you indicate is a record of the type field from the child spec (see Supervisor — Elixir v1.14.3). The value of this field isn’t super material to you one way or the other; your match can safely ignore it.

(As background, Bandit’s behaviour in this regard had some minor chages with the 0.6.11 release that moved that field from :worker to :supervisor. It’s a purely internal change that you don’t really need to care about).

Where Next?

Popular in Questions Top

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
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
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
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
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
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
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New

Other popular topics Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
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
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New

We're in Beta

About us Mission Statement