OTP applications

A supervisor restarts a process, but something has to start the supervisor, and something has to stop the whole tree in the right order when the system shuts down. That unit is the application: a name, a version, a description, the applications it needs, and one callback module that OTP calls to start and stop the tree. The supervisors lesson builds the tree; this lesson wraps it in an Erlang application and starts it with the application controller.

The application resource

The resource file is what makes a tree an application. It names the version, the applications that must be running first, the callback module and the default environment. A project keeps the source as src/counter_app.app.src, and the build writes the final counter_app.app with the modules list filled in. This is a fragment of the resource, not a module:

counter_app.app.src

{application, counter_app, [ {description, "A counter as an OTP application"}, {vsn, "0.1.0"}, {registered, [counter_sup]}, {mod, {counter_app, []}}, {applications, [ kernel, stdlib ]}, {env, [{limit, 3}]}, {modules, []}, {licenses, ["Apache-2.0"]}, {links, []} ]}.

Two entries decide what starts. applications is the start order: kernel and stdlib are always there, and a project that uses crypto or inets must name it, or the first call into it fails with undef at run time. mod names the callback module and the arguments handed to its start/2, which must answer the pid of the top supervisor, because the controller links to that pid and watches the whole tree through it. stop/1 runs after the tree is gone, and it is the place for a last flush of a file or a log line, never for stopping children: the supervisor has done that already. vsn is the version the release tools compare when they upgrade a running system, in the releases lesson.

What the controller reads

A resource is data, and application:load/1 accepts the same term that the .app file holds, so a program can inspect it without a project. application:get_key/2 reads one key of a loaded application:

app_keys.erl

-module(app_keys). -export([main/0]). main() -> Spec = {application, demo, [{description, "A counter as an OTP application"}, {vsn, "0.1.0"}, {modules, [counter_app, counter_sup, counter]}, {registered, [counter_sup]}, {applications, [kernel, stdlib]}, {mod, {counter_app, []}}]}, ok = application:load(Spec), io:format("vsn: ~p~n", [application:get_key(demo, vsn)]), io:format("modules: ~p~n", [application:get_key(demo, modules)]), io:format("applications: ~p~n", [application:get_key(demo, applications)]), io:format("mod: ~p~n", [application:get_key(demo, mod)]), ok = application:unload(demo).

erlc app_keys.erl

erl -noshell -eval 'app_keys:main(), halt().'

vsn: {ok,"0.1.0"} modules: {ok,[counter_app,counter_sup,counter]} applications: {ok,[kernel,stdlib]} mod: {ok,{counter_app,[]}}

Each answer is the value in an ok tuple, or undefined for a key the resource does not name. The build fills modules from the files it compiled, and the release tools read the same key to check that nothing is missing from a release.

Start and stop

In a project the application callback, the supervisor and the counter are three files. The program below puts all three roles in one module so that it runs as a single block: it exports start/2 and stop/1 for the application behaviour, init/1 for the supervisor behaviour, and a counter loop. It loads a resource from a term, starts the application, uses the counter, and stops the application again:

demo_app.erl

-module(demo_app). -behaviour(application). -behaviour(supervisor). -export([main/0, start/2, stop/1, init/1]). -export([start_counter/0]). main() -> logger:set_primary_config(level, none), Spec = {application, demo, [{description, "A counter as an OTP application"}, {vsn, "0.1.0"}, {modules, [?MODULE]}, {registered, []}, {applications, [kernel, stdlib]}, {env, [{limit, 3}]}, {mod, {?MODULE, []}}]}, ok = application:load(Spec), io:format("default limit: ~p~n", [application:get_env(demo, limit)]), {ok, Started} = application:ensure_all_started(demo), io:format("started: ~p~n", [Started]), ok = increment(), io:format("value: ~p~n", [value()]), Running = lists:keymember(demo, 1, application:which_applications()), io:format("running: ~p~n", [Running]), ok = application:stop(demo), io:format("counter after stop: ~p~n", [whereis(counter)]). start(_StartType, _StartArgs) -> supervisor:start_link({local, ?MODULE}, ?MODULE, []). stop(_State) -> ok. init([]) -> Child = #{id => counter, start => {?MODULE, start_counter, []}, restart => permanent, shutdown => 5000, type => worker, modules => [?MODULE]}, {ok, {{one_for_one, 5, 10}, [Child]}}. start_counter() -> Pid = spawn_link(fun() -> loop(0) end), true = register(counter, Pid), {ok, Pid}. increment() -> counter ! add, ok. value() -> counter ! {get, self()}, receive {count, Number} -> Number after 1000 -> timeout end. loop(Count) -> receive add -> loop(Count + 1); {get, From} -> From ! {count, Count}, loop(Count) end.

erlc demo_app.erl

erl -noshell -eval 'demo_app:main(), halt().'

default limit: {ok,3} started: [demo] value: 1 running: true counter after stop: undefined

ensure_all_started/1 starts the applications of the list first and answers the ones it started, so an application that names crypto in applications needs no manual start of it. stop/1 stops the tree through the top supervisor and then calls the stop/1 callback, which is why the counter is gone and the application is no longer in which_applications/0.

Application environment

The env key is the configuration of the application, and application:get_env/2 reads one value with its default. application:set_env/3 changes a value at run time, and every reader sees the new one; the value survives a restart of the application because it lives in the application controller, not in a process. The two calls in the program show both directions: the default comes from the resource, and a reader that needs the value does not care where it was set.

A rebar3 app

The app template writes all of this in one command: the callback, a supervisor, the .app.src file and the config. The name becomes the folder, the application name and the prefix of both modules:

rebar3 new app myapp

===> Writing myapp/src/myapp_app.erl ===> Writing myapp/src/myapp_sup.erl ===> Writing myapp/src/myapp.app.src ===> Writing myapp/rebar.config ===> Writing myapp/.gitignore ===> Writing myapp/LICENSE.md ===> Writing myapp/README.md

The compile task builds every module into _build and writes the final app file next to the beams, with the modules list filled in. The project layout lesson reads each generated file:

cd myapp

rebar3 compile

===> Verifying dependencies... ===> Analyzing applications... ===> Compiling myapp

Start types

The first argument of start/2 is the start type: normal for a boot, {takeover, Node} when a distributed node takes an application over from a dead one, and {failover, Node} when it restarts the application on another node. Nearly every application ignores it, as this one does, and only the release handler of a clustered system reads it. A start that fails must answer {error, Reason} rather than raise: the controller then refuses the application instead of taking the whole node down with a boot failure.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which behaviour does the application callback module implement?

    Answer

    application

    The module declares -behaviour(application) and exports start/2 and stop/1.

  2. What must start/2 return?

    Answer

    The pid of the top supervisor in an ok tuple

    The controller links to that pid, so it must be the supervisor of the whole tree.

  3. When does stop/1 run?

    Answer

    After the tree is gone

    The supervisor has already stopped the children, so stop/1 is only the last cleanup.

  4. Which key of the resource points at the callback module?

    Answer

    {mod, {counter_app, []}}

    mod holds the callback module and the arguments handed to start/2.

  5. Which key lists the applications that must be started first?

    Answer

    {applications, [kernel, stdlib]}

    The controller starts the listed applications before it starts this one.

  6. What does rebar3 new app myapp write?

    Answer

    A callback, a supervisor, an app.src file and a config

    The app template scaffolds the whole OTP application skeleton.

  7. What does this module print? -module(q1). -export([main/0]). main() -> ok = application:load({application, demo, [{description, "demo"}, {vsn, "0.2.0"}, {modules, []}, {applications, [kernel, stdlib]}]}), io:format("~p~n", [application:get_key(demo, vsn)]).

    Answer

    {ok,"0.2.0"}

    get_key/2 answers the value in an ok tuple, and vsn is the version of the resource.

  8. What does this module print? -module(q2). -export([main/0]). main() -> ok = application:load({application, demo, [{description, "demo"}, {vsn, "0.1.0"}, {modules, []}, {applications, [kernel, stdlib]}, {env, [{limit, 3}]}]}), io:format("~p~n", [application:get_env(demo, limit)]).

    Answer

    {ok,3}

    The default comes from the env key of the resource, and get_env/2 answers it in an ok tuple.

  9. What does this module print? -module(q3). -export([main/0]). main() -> ok = application:load({application, demo, [{description, "demo"}, {vsn, "0.1.0"}, {modules, []}, {applications, [kernel, stdlib]}]}), io:format("~p~n", [application:ensure_all_started(demo)]).

    Answer

    {ok,[demo]}

    The call answers the list of applications it started; this application has no callback and no tree, so the list holds only its name.

  10. What does this module print? -module(q4). -export([main/0]). main() -> logger:set_primary_config(level, none), ok = application:load({application, demo, [{description, "demo"}, {vsn, "0.1.0"}, {modules, []}, {applications, [kernel, stdlib]}]}), {ok, [demo]} = application:ensure_all_started(demo), ok = application:stop(demo), io:format("~p~n", [lists:keymember(demo, 1, application:which_applications())]).

    Answer

    false

    The application was stopped, so it is no longer in the running list.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) and rebar3 3.27.3 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev