Hot code upgrades

A system that must run for years cannot stop for an upgrade, and Erlang was built around that requirement: a module holds code, not a file the program opened, and the runtime loads a new version next to the old one while the system runs. The code loading lesson shows the loader and its two generations; this one upgrades a running system, moves the state of a process with the new code, and follows the path a release takes.

What a hot upgrade is

An upgrade has three parts, and each of them has a name. The new beam must be loaded, which is a call to the loader. The processes that keep state must translate it, which is the code_change/3 callback of their behaviour. The order of the loads and the translations must be written down, which is what an .appup file of the application and the relup file of the release hold. A reader who does only the first part has loaded new code and kept the old state, which is usually worse than a restart.

The swap is possible because a process calls its own module with a local call, and a local call stays inside the code the process was running. Loading a second version does not move that process: it keeps running the old code until it makes a fully qualified call, such as ?MODULE:handle_call/3 through the behaviour, and then continues in the new version. That is why OTP behaviours are written with fully qualified calls, and why a hand written loop survives an upgrade only if it is written the same way.

Load a new version

The session below builds a module called greet three times in one shell. Each version writes its source, compiles it with compile:file/2 and loads the beam with code:load_file/1, which is the call a release handler makes:

erl

1> logger:set_primary_config(level, none). ok 2> ok = file:write_file("greet.erl", "-module(greet).\n-export([hello/0]).\nhello() -> v1.\n"). ok 3> {ok, greet} = compile:file("greet", []). {ok,greet} 4> {module, greet} = code:load_file(greet). {module,greet} 5> greet:hello(). v1 6> ok = file:write_file("greet.erl", "-module(greet).\n-export([hello/0]).\nhello() -> v2.\n"). ok 7> {ok, greet} = compile:file("greet", []). {ok,greet} 8> {module, greet} = code:load_file(greet). {module,greet} 9> greet:hello(). v2 10> ok = file:write_file("greet.erl", "-module(greet).\n-export([hello/0]).\nhello() -> v3.\n"). ok 11> {ok, greet} = compile:file("greet", []). {ok,greet} 12> {error, not_purged} = code:load_file(greet). {error,not_purged} 13> greet:hello(). v2 14> code:soft_purge(greet). true 15> {module, greet} = code:load_file(greet). {module,greet} 16> greet:hello(). v3

Line 12 is the rule of the two generations: version two is current, version one is old, and the loader refuses a third until the old one is purged. The failed load is not a lost upgrade, because line 13 still answers v2: the system keeps running the version it had. code:soft_purge/1 on line 14 removes the old generation when no process runs it, and only then does the third load succeed. The page turns logging off on line 1 because the loader writes an error report with a timestamp for the refused load, and a timestamp cannot be part of a transcript. A release handler runs exactly these steps, with a purge after it has moved every process.

The state moves too

A new version of a callback module often expects a different state shape. The state lives in the process, not in the module, so loading the beam changes nothing about it; the behaviour calls code_change/3 at the moment of the swap, and the callback answers the state the new code can read. The program keeps a counter in a two element tuple and upgrades it to a three element tuple:

migrate.erl

-module(migrate). -behaviour(gen_server). -export([main/0, state/0]). -export([init/1, handle_call/3, handle_cast/2, code_change/3]). main() -> {ok, _Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, {counter, 2}, []), io:format("old state: ~p~n", [state()]), ok = sys:suspend(?MODULE), ok = sys:change_code(?MODULE, ?MODULE, {down, 1}, []), ok = sys:resume(?MODULE), io:format("new state: ~p~n", [state()]), ok = gen_server:stop(?MODULE). state() -> gen_server:call(?MODULE, state). init(State) -> {ok, State}. handle_call(state, _From, State) -> {reply, State, State}. handle_cast(_Msg, State) -> {noreply, State}. code_change({down, _Vsn}, {counter, N}, _Extra) -> {ok, {counter, N, migrated}}; code_change(_OldVsn, State, _Extra) -> {ok, State}.

erlc migrate.erl

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

old state: {counter,2} new state: {counter,2,migrated}

sys:suspend/1 stops the server between two messages so that no call is handled halfway through the swap, sys:change_code/4 runs the callback, and sys:resume/1 lets the mailbox flow again. The {down, 1} is the version the upgrade comes from, which an appup instruction writes; a running system that upgrades upwards passes {up, Vsn} instead. The catch-all clause answers the state unchanged for every version the code does not know, which keeps a downgrade from breaking the server.

The release path

In a real system nobody types code:load_file/1 by hand. The release handler of OTP reads a relup file, which is built from the .appup file of each application, and runs the instructions in order: {load_module, Module}, {update, Module, Change} and {apply, {M, F, A}} are the common ones. A .appup names the versions it upgrades from and rolls back to:

{'2.0.0', [{'1.0.0', [{load_module, greet}, {load_module, greet_sup}]}], [{'1.0.0', [{load_module, greet}, {load_module, greet_sup}]}]}.

The page shows this file as a fragment on purpose: it is a term of the application, not a program that runs by itself. rebar3 relup turns the two source versions into the relup, and rebar3 release builds the release the package is applied to; the releases lesson builds one and reads its folders. The package is installed with release_handler:install_release/1 and made permanent with release_handler:make_permanent/1, and release_handler:check_install_release/1 is the dry run that a careful operator runs first.

Three habits make an upgrade survive: keep the state a plain term that the callback can translate, keep the names and arities of exported functions stable because the old generation calls them by name, and change the message format of a protocol only in a version that can read both. The last one is the upgrade nobody tests: a new field in a message that the other node does not send yet crashes the receiver, and the crash report points at a function that is correct in the new code.

Questions

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

  1. What are the three parts of a hot upgrade?

    Answer

    Load the beam, translate the state, follow the relup order

    The loader, the code_change/3 callback and the release handler each do one of the three.

  2. When does a running process switch to the new version of its module?

    Answer

    When it makes a fully qualified call into the module

    A local call stays in the code the process was running; a fully qualified call enters the current version.

  3. What does code:load_file/1 answer when the old generation has not been purged?

    Answer

    {error, not_purged}

    The loader keeps two generations, and a third load waits until the old one is gone.

  4. Why is the process suspended around sys:change_code/4?

    Answer

    So that no call is handled halfway through the swap

    A suspended process handles the system message alone and then resumes with the new state.

  5. Which file tells the release handler how to upgrade an application?

    Answer

    The .appup file of the application

    The appup lists the versions and the instructions for each upgrade and downgrade step.

  6. What does code:soft_purge/1 do?

    Answer

    Removes the old version when 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). -behaviour(gen_server). -export([main/0, state/0]). -export([init/1, handle_call/3, handle_cast/2, code_change/3]). main() -> {ok, _Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, 1, []), ok = sys:suspend(?MODULE), ok = sys:change_code(?MODULE, ?MODULE, {down, 1}, []), ok = sys:resume(?MODULE), io:format("~p~n", [state()]), gen_server:stop(?MODULE). state() -> gen_server:call(?MODULE, state). init(N) -> {ok, N}. handle_call(state, _From, N) -> {reply, N, N}. handle_cast(_Msg, N) -> {noreply, N}. code_change({down, _Vsn}, N, _Extra) -> {ok, N + 10}; code_change(_OldVsn, N, _Extra) -> {ok, N}.

    Answer

    11

    The change names the down version, so the first clause adds ten to the state the server already holds.

  8. What does this module print? -module(q2). -export([main/0]). main() -> io:format("~p~n", [code:load_file(no_such_module)]).

    Answer

    {error, nofile}

    The loader looks for the beam on the code path, and a module it cannot find is reported as nofile.

  9. What does this module print? -module(q3). -export([main/0]). main() -> io:format("~p~n", [erlang:check_old_code(lists)]), io:format("~p~n", [code:soft_purge(lists)]).

    Answer

    false / true

    No old generation is loaded, so the check is false and the purge has nothing to remove.

  10. What does this module print? -module(q4). -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)]).

    Answer

    true

    The second load leaves the previous generation as old code until something purges it.

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. The release commands were not run in this environment: they build and start a release.

Автор статьи: Arthur Isaev