Code loading

In Erlang a module is not a file the program opened: it is a piece of code the runtime loads by name from the code path, and it can load a second version of it while the first one still runs. That is what makes an upgrade without a restart possible. The hot code upgrades lesson shows the whole swap; this one shows the four pieces under it: the code_change/3 callback that translates a state, the calls that name the file of a module, the two generations the loader keeps, and the release step that drives them.

code_change/3

A running process can switch to a new version of its module without stopping. The runtime keeps the old code and the new code side by side, the process keeps its state, and the module gets a chance to translate that state: the code_change/3 callback. It receives the old version, the current state and an extra term from the upgrade script, and answers {ok, NewState}. The program forces the callback with sys:change_code/4 and shows the counter move:

change.erl

-module(change). -behaviour(gen_server). -export([main/0, bump/0, value/0]). -export([init/1, handle_call/3, handle_cast/2, code_change/3]). main() -> {ok, _Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, 0, []), bump(), bump(), io:format("before: ~p~n", [value()]), ok = sys:suspend(?MODULE), ok = sys:change_code(?MODULE, ?MODULE, old_vsn, []), ok = sys:resume(?MODULE), io:format("after: ~p~n", [value()]), ok = gen_server:stop(?MODULE). bump() -> gen_server:cast(?MODULE, bump). value() -> gen_server:call(?MODULE, value). init(N) -> {ok, N}. handle_call(value, _From, N) -> {reply, N, N}. handle_cast(bump, N) -> {noreply, N + 1}. code_change(old_vsn, N, _Extra) -> {ok, N + 1}; code_change(_OldVsn, N, _Extra) -> {ok, N}.

erlc change.erl

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

before: 2 after: 3

The second clause is the contract every gen_server implements: an unknown version passes the state through untouched. This module makes the change visible instead and adds one to the counter when it sees old_vsn. A real upgrade needs a state that the new code can still read: keep the state a plain term, keep the atom names stable, and put every migration in this callback.

Which file is loaded

code:ensure_loaded/1 loads a module from the code path unless it is loaded already, and code:which/1 names the file the loader used. code:get_object_code/1 answers the module, the beam binary and the file name, which is the material an upgrade script moves between nodes. The program asks for sets, deletes it and asks again:

paths.erl

-module(paths). -export([main/0]). main() -> io:format("loaded before: ~p~n", [code:is_loaded(sets)]), io:format("ensure_loaded: ~p~n", [code:ensure_loaded(sets)]), io:format("which: ~p~n", [filename:basename(code:which(sets))]), {sets, Binary, File} = code:get_object_code(sets), io:format("object code: ~p from ~p~n", [is_binary(Binary), filename:basename(File)]), {module, sets} = code:ensure_loaded(sets), io:format("delete: ~p~n", [code:delete(sets)]), io:format("loaded after the delete: ~p~n", [code:is_loaded(sets)]), {module, sets} = code:ensure_loaded(sets), io:format("loaded again: ~p~n", [code:is_loaded(sets) =/= false]).

erlc paths.erl

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

loaded before: {file,"/usr/lib/erlang/lib/stdlib-6.2.2.5/ebin/sets.beam"} ensure_loaded: {module,sets} which: "sets.beam" object code: true from "sets.beam" delete: true loaded after the delete: false loaded again: true

The first line shows the whole path of the beam the runtime used, and filename:basename/1 keeps the output of the page stable. Normally rebar3 and the release handler do this work, and a node that loads a module by hand is either a shell or an upgrade script. The code path is a list of folders, and code:add_patha/1 puts one more at the front of it.

Two generations of a module

A module can have two loaded versions at once: the current one and the old one. A process that was running the old code keeps running it until it makes a fully qualified call into the module, which is the moment the runtime moves it to the current version. Loading a third version is refused until the old one is purged. The program loads a second generation of sets from the object code it already has and asks the runtime about the old one:

generations.erl

-module(generations). -export([main/0]). main() -> {module, sets} = code:ensure_loaded(sets), {sets, Binary, File} = code:get_object_code(sets), true = code:unstick_mod(sets), {module, sets} = code:load_binary(sets, File, Binary), io:format("old code: ~p~n", [erlang:check_old_code(sets)]), io:format("soft purge: ~p~n", [code:soft_purge(sets)]), io:format("old code after the purge: ~p~n", [erlang:check_old_code(sets)]).

erlc generations.erl

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

old code: true soft purge: true old code after the purge: false

code:unstick_mod/1 is needed because a module of the OTP installation lives in a sticky directory, which the loader refuses to replace; a project that loads its own beams has no such directory. code:soft_purge/1 removes the old generation only when no process still runs it and answers false otherwise, while code:purge/1 kills the processes that are still there. That is the whole bookkeeping of a hot upgrade, done in the right order: load, let the processes make their qualified call, then purge.

Release upgrades

A release bundles the VM, the applications and a boot script, and an upgrade package adds the new beams plus a relup file. The release handler reads the relup steps, loads the new code, calls sys:change_code/4 on the processes that need it, and applies the instructions of each application. Those instructions live in the .appup file next to the .app resource of the releases lesson: a list of {UpFromVsn, DownToVsn, Instructions} terms that name the modules to load and the state to translate.

The practical rules for code that must survive an upgrade: keep the state a plain term, put every migration in code_change/3, keep the function names and arities stable because a process of the old generation calls them by name, and test the path from the previous release rather than only a fresh start. rebar3 relup builds the package and rebar3 release builds the release itself.

Questions

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

  1. What is code_change/3 for?

    Answer

    Translating a process state to a new version

    The callback turns the old state into the shape the new code expects.

  2. What does code_change/3 answer?

    Answer

    {ok, NewState}

    The process continues with the state the callback returns.

  3. What does code:ensure_loaded/1 do?

    Answer

    Loads a module unless it is loaded already

    It answers {module, Name} when the module is available, and loads it if needed.

  4. What does code:which/1 answer?

    Answer

    The path of the beam file

    It names the file the loader would use, or non_existing.

  5. How many versions of a module can be loaded at once?

    Answer

    Two: the current and the old

    The runtime keeps the old version for the processes that still run it, and refuses a third.

  6. What does code:soft_purge/1 do?

    Answer

    Removes the old version if no process runs it

    It is the polite purge; code:purge/1 is the one that kills the remaining processes.

  7. What does this module print? -module(q1). -export([main/0]). main() -> io:format("~p~n", [filename:basename(code:which(lists))]).

    Answer

    "lists.beam"

    code:which/1 answers the path of the beam, and filename:basename/1 leaves the file name.

  8. What does this module print? -module(q2). -export([main/0]). main() -> {module, sets} = code:ensure_loaded(sets), true = code:delete(sets), io:format("~p~n", [code:is_loaded(sets)]), io:format("~p~n", [code:ensure_loaded(sets)]).

    Answer

    false / {module,sets}

    A deleted module is no longer loaded, and ensure_loaded/1 loads it again from the code path.

  9. What does this module print? -module(q3). -export([main/0]). main() -> {module, sets} = code:ensure_loaded(sets), {sets, Binary, File} = code:get_object_code(sets), true = code:unstick_mod(sets), {module, sets} = code:load_binary(sets, File, Binary), io:format("~p~n", [erlang:check_old_code(sets)]), io:format("~p~n", [code:soft_purge(sets)]), io:format("~p~n", [erlang:check_old_code(sets)]).

    Answer

    true / true / false

    A load makes the previous generation old, a soft purge removes it when nothing runs it, and the check then finds no old code.

  10. What does this module print? -module(q4). -behaviour(gen_server). -export([main/0, value/0]). -export([init/1, handle_call/3, handle_cast/2, code_change/3]). main() -> {ok, _Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, 5, []), ok = sys:suspend(?MODULE), ok = sys:change_code(?MODULE, ?MODULE, 1, []), ok = sys:resume(?MODULE), io:format("~p~n", [value()]), gen_server:stop(?MODULE). value() -> gen_server:call(?MODULE, value). init(N) -> {ok, N}. handle_call(value, _From, N) -> {reply, N, N}. handle_cast(_Msg, N) -> {noreply, N}. code_change(1, N, _Extra) -> {ok, N * 2}; code_change(_OldVsn, N, _Extra) -> {ok, N}.

    Answer

    10

    The upgrade names version 1, so the first clause runs and the state leaves the callback doubled.

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

Article author: Arthur Isaev