Archive for the ‘functional’ Category

Erlang Remote Shells and Hot Swapping Code

2009-09-12

Michael Hashimoto over at spawn_link is doing a wonderful service in providing examples of Erlang code.  One of his examples, Rules of Hot Code Swapping,  explains details behind one of the cooler features of the Erlang runtime – the ability to “hot swap”, that is change out executing code without stopping the service that using it.  In doing so, he glosses over a few steps that a beginning Erlang programmer might need, so I’ve augmented his example with a few instructions that can help a novice get his example to work.  You can pull the example from my git repository  (git clone git://github.com/jbgreer/Erlang.git), where I’ve added these instructions as comments.

First, I assume that you’ve installed a fairly recent version of Erlang and that erl and erlc are executable from your prompt.

  1. Edit hotswap.erl

    Bump the version number in -define(VERSION, 3).

    Edit the message in the io:format to something distinctive.

  2. Compile the module

    erlc hotswap.erl

  3. Start a Erlang shell. Here I set use two command-line options, sname and setcookie. Sname sets the “shortname” of the node; setting the node’s name is necessary if I want to connect to it later (and we do, so we can update the code running in it). Setcookie is a security mechanism used in connecting to nodes. Setting it like this on the command-line is an unrecommended practice but necessary if you don’t have a cookie file.

    Note that the values for sname and the cookie are arbitrary.

    erl -sname node1 -setcookie foo

  4. In the shell, start the server and test. You should get a response back formatted according to your io:format line. After you’ve tested this do not exit the Erlang shell. We will use it again in a minute.

    Pid = hotswap:start().

    Pid ! {echo, "foo"}.

  5. Open another command-line shell/terminal.
  6. Repeat steps 1 & 2. Try to edit the io:format string to make it visually distinctive from the current value.
  7. Connect to the current (remote) Erlang Shell. It’s called a remote shell even it isn’t on another machine because it is running on a separate node. By default, if you start an Erlang shell you’re starting a new node.

    erl -sname node2 -remsh node1@MACHINENAME -setcookie foo

    where MACHINENAME should be replaced with your host’s name.

  8. In the connected shell perform the code swap

    code:load_file(hotswap).

  9. Test the change in the original Erlang shell. The first echo will likely show the existing message, while the second will show the new message.

    Pid ! {echo, "foo"}.

    Pid ! {echo, "foo"}.