apr

apr

Structure code to run before any application starts

Hello,

I have an umbrella application with many children applications. I would like to run some code (the same code) if any or all those child applications are started (i.e. when running tests, when running iex -S mix at the umbrella level, etc.) What would be the best way to structure such code?

Thanks!

Most Liked

axelson

axelson

Scenic Core Team

Couldn’t you create a new application (that all of the other applications depend on), whose supervision tree contains a GenServer that inserts the rows in :persistent_term?

amnu3387

amnu3387

If you’re using an umbrella I found it useful to create an application that is responsible for bootstrapping the actual app. This allows you to setup things before starting your actual “core”.
As an example, on the umbrella mix.exs I have the following release:

defmodule YourApp.MixProject do
  use Mix.Project

  def project do
    [
      apps_path: "apps",
      version: "1.0.0",
      start_permanent: Mix.env() == :prod,
      deps: deps(),
      releases: [
        your_release_name: [
          applications: [
            bootstrap: :permanent, #this is so that when releasing it starts this app which in turn will run its logic
            server: :load #this is the actual core application, we set it to only load its modules but not start the supervision tree
          ],
          include_executables_for: [:unix]
        ]
      ]
    ]
  end
  #other things.... like deps etc
end

Then the bootstrap app is a simple app with a supervision tree, it has a bootstrap.ex which is a gen_server to be started from the supervision tree, eg:

defmodule Bootstrap do
  
  @moduledoc """
  This starts mnesia and etc and once ok starts the web interface
  """

  use GenServer, shutdown: 50_000
  require Logger
  
  @mnesia_tables_attrs %{
    categories: [:slug, :title, :description, :image, :id, :struct]
  }

  @mnesia_tables Enum.reduce(@mnesia_tables_attrs, [], fn({table, _}, acc) ->
    [table | acc]
  end) |> :lists.reverse

  def start_link(_) do
    GenServer.start_link(__MODULE__, nil, name: __MODULE__)
  end

  def init(_) do
    System.cmd("epmd", ["-daemon"])

    #random_uuid = (:crypto.strong_rand_bytes(4) |> Base.encode16())
    #name = :"#{random_uuid}@#{:net_adm.localhost()}"

    #:net_kernel.start([name])
    
    case :mnesia.start() do
      :ok ->
        
        Enum.each(@mnesia_tables_attrs, fn({table, attributes}) ->
          :mnesia.create_table(table, [attributes: attributes])
        end)
        
        case :mnesia.wait_for_tables(@mnesia_tables, 5_000) do
          :ok ->
            Logger.warn("Mnesia tables loaded")
            {:ok, :started, {:continue, :ensure_all_started}}
          {:timeout, tables} ->
            Logger.error("Mnesia Unable to load tables: #{inspect tables} - shutting down...")
            :init.stop()
        end

      error -> :init.stop()
    end
  end

  def handle_continue(:ensure_all_started, state) do
    Logger.info("Starting server")
    {:ok, _started_apps} = :application.ensure_all_started(:server, :permanent)
    {:noreply, :started}
  end

  def copy_hex_cache(_, _, _) do
    File.cp_r!(Path.expand("~/.hex"), File.cwd!() <> "/hex")
    :ok
  end

  def delete_hex_cache(_, _, _) do
    File.rm_rf!(File.cwd!() <> "/hex")
    :ok
  end

end

Then it’s application file includes:

defmodule Bootstrap.Application do
  @moduledoc false

  use Application

  def start(_type, _args) do
    children = [
      {Bootstrap, []}
    ]

    opts = [strategy: :one_for_one, name: Bootstrap.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

And it has a task in all similar to the phx.server task:

defmodule Mix.Tasks.Bootstrap do
  use Mix.Task

  def run(_) do
    Application.put_env(:phoenix, :serve_endpoints, true, persistent: true)
    {:ok, _} = Application.ensure_all_started(:bootstrap)
    Mix.Tasks.Run.run run_args() ++ ["--no-start"]
  end

  defp run_args do
    if iex_running?(), do: [], else: ["--no-halt"]
  end

  defp iex_running? do
    Code.ensure_loaded?(IEx) and IEx.started?
  end

end

This task is to be run when in dev, so that you can do iex -S mix bootstrap
In my case I do Ecto migrations when I need manually, but there’s nothing preventing you from adding a step to run migrations as well as part of the bootstrap gen_server. Any other things you need to do before starting your actual core, can be done here too if needed. When running the release it will start the bootstrap app (you don’t run the task) and that start your actual app.

I have found this a good way of structuring the startup of an application.

gregvaughn

gregvaughn

I have used the Module @on_load callback to ensure persistent terms are set up the first time the wrapper module is used. That allowed me to avoid any concerns about app startup processes.

gregvaughn

gregvaughn

Oh, good because I just grepped the ecto code and “on_load” does not appear, so my suspicion was all wrong :sweat_smile:

I think my first attempt forgot that :ok too, so I can relate. I hope it works out for you.

apr

apr

Thanks for the suggestions everyone! I looked at all of them and this reply as well: Change my mind: Migrations in a start phase.

I finally decided to use a Genserver like @axelson suggested, but ran it directly in my application supervision tree. Since I need to populate :persistent_term with DB rows, I need the Repo running. I could always start the repo process in another application that my main application depends on, but just running a temporary Genserver after the Repo process starts in the main application was simpler. Also, the Genserver's blocking init fn returns :ignore once it populates :persistent_term, so it exits normally without entering the msg receive loop. Works well for my use case :slight_smile:

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