This section describes how to implement an own carrier protocol for the Erlang distribution. The distribution is normally carried by TCP/IP. Here is explained a method for replacing TCP/IP with another protocol.
The section is a step-by-step explanation of the
This section was written a long time ago. Most of it is still
valid, but some things have changed since then.
Most notably is the driver interface. Some updates have been made
to the documentation of the driver presented here,
but more can be done and is planned for the future.
The reader is encouraged to read the
To implement a new carrier for the Erlang distribution, the main steps are as follows.
First, the protocol must be available to the Erlang machine, which involves writing an Erlang driver. A port program cannot be used, an Erlang driver is required. Erlang drivers can be:
Statically linked to the emulator, which can be an alternative when using the open source distribution of Erlang, or
Dynamically loaded into the Erlang machines address space, which is the only alternative if a precompiled version of Erlang is to be used
Writing an Erlang driver is not easy. The driver is written as some callback functions called by the Erlang emulator when data is sent to the driver, or the driver has any data available on a file descriptor. As the driver callback routines execute in the main thread of the Erlang machine, the callback functions can perform no blocking activity whatsoever. The callbacks are only to set up file descriptors for waiting and/or read/write available data. All I/O must be non-blocking. Driver callbacks are however executed in sequence, why a global state can safely be updated within the routines.
When the driver is implemented, one would preferably write an
Erlang interface for the driver to be able to test the
functionality of the driver separately. This interface can then
be used by the distribution module, which will cover the details of
the protocol from the
The easiest path
is to mimic the
When the protocol is available to Erlang through a driver and an
Erlang interface module, a distribution module can be written.
The distribution module is a module with well-defined callbacks,
much like a
There is however a utility module,
The last step is to create boot scripts to make the protocol implementation available at boot time. The implementation can be debugged by starting the distribution when all the system is running, but in a real system the distribution is to start very early, why a boot script and some command-line parameters are necessary.
This step also implies that the Erlang code in the
interface and distribution modules is written in such a way that
it can be run in the startup phase. In particular, there can be no
calls to the
Although Erlang drivers in general can be beyond the scope of this section, a brief introduction seems to be in place.
An Erlang driver is a native code module written in C (or
assembler), which serves as an interface for some special operating
system service. This is a general mechanism that is used
throughout the Erlang emulator for all kinds of I/O. An Erlang
driver can be dynamically linked (or loaded) to the Erlang
emulator at runtime by using the
The driver data types and the functions available to the driver
writer are defined in header file
When writing a driver to make a communications protocol available to Erlang, one should know just about everything worth knowing about that particular protocol. All operation must be non-blocking and all possible situations are to be accounted for in the driver. A non-stable driver will affect and/or crash the whole Erlang runtime system.
The emulator calls the driver in the following situations:
When the driver is loaded. This callback must have a special
name and inform the emulator of what callbacks are to be used
by returning a pointer to a
When a port to the driver is opened (by a
When an Erlang process sends data to the port. The data
arrives as a buffer of bytes, the interpretation is not defined,
but is up to the implementor. This callback returns nothing to the
caller, answers are sent to the caller as messages (using a
routine called
When a file descriptor is signaled for input. This callback
is called when the emulator detects input on a file descriptor
that the driver has marked for monitoring by using the interface
When a file descriptor is signaled for output. This callback
is called in a similar way as the previous, but when writing to a
file descriptor is possible. The usual scenario is that Erlang
orders writing on a file descriptor and that the driver calls
When a port is closed, either by an Erlang process or by the
driver calling one of the
When an Erlang process calls
When a timer expires. The driver can set timers with the function
When the whole driver is unloaded. Every resource allocated by the driver is to be freed.
The driver used for Erlang distribution is to implement a reliable, order maintaining, variable length packet-oriented protocol. All error correction, resending and such need to be implemented in the driver or by the underlying communications protocol. If the protocol is stream-oriented (as is the case with both TCP/IP and our streamed Unix domain sockets), some mechanism for packaging is needed. We will use the simple method of having a header of four bytes containing the length of the package in a big-endian 32-bit integer. As Unix domain sockets only can be used between processes on the same machine, we do not need to code the integer in some special endianess, but we will do it anyway because in most situation you need to do it. Unix domain sockets are reliable and order maintaining, so we do not need to implement resends and such in the driver.
We start writing the example Unix domain sockets driver by
declaring prototypes and filling in a static
( 2) #include
( 3) #include
( 4) #include
( 5) #include
( 6) #include
( 7) #include
( 8) #include
( 9) #include
(10) #include
(11) #define HAVE_UIO_H
(12) #include "erl_driver.h"
(13) /*
(14) ** Interface routines
(15) */
(16) static ErlDrvData uds_start(ErlDrvPort port, char *buff);
(17) static void uds_stop(ErlDrvData handle);
(18) static void uds_command(ErlDrvData handle, char *buff, int bufflen);
(19) static void uds_input(ErlDrvData handle, ErlDrvEvent event);
(20) static void uds_output(ErlDrvData handle, ErlDrvEvent event);
(21) static void uds_finish(void);
(22) static int uds_control(ErlDrvData handle, unsigned int command,
(23) char* buf, int count, char** res, int res_size);
(24) /* The driver entry */
(25) static ErlDrvEntry uds_driver_entry = {
(26) NULL, /* init, N/A */
(27) uds_start, /* start, called when port is opened */
(28) uds_stop, /* stop, called when port is closed */
(29) uds_command, /* output, called when erlang has sent */
(30) uds_input, /* ready_input, called when input
(31) descriptor ready */
(32) uds_output, /* ready_output, called when output
(33) descriptor ready */
(34) "uds_drv", /* char *driver_name, the argument
(35) to open_port */
(36) uds_finish, /* finish, called when unloaded */
(37) NULL, /* void * that is not used (BC) */
(38) uds_control, /* control, port_control callback */
(39) NULL, /* timeout, called on timeouts */
(40) NULL, /* outputv, vector output interface */
(41) NULL, /* ready_async callback */
(42) NULL, /* flush callback */
(43) NULL, /* call callback */
(44) NULL, /* event callback */
(45) ERL_DRV_EXTENDED_MARKER, /* Extended driver interface marker */
(46) ERL_DRV_EXTENDED_MAJOR_VERSION, /* Major version number */
(47) ERL_DRV_EXTENDED_MINOR_VERSION, /* Minor version number */
(48) ERL_DRV_FLAG_SOFT_BUSY, /* Driver flags. Soft busy flag is
(49) required for distribution drivers */
(50) NULL, /* Reserved for internal use */
(51) NULL, /* process_exit callback */
(52) NULL /* stop_select callback */
(53) };]]>
On line 1-10 the OS headers needed for the driver are included.
As this driver is written for Solaris, we know that the
header
On line 16-23 the different callback functions are declared ("forward declarations").
The driver structure is similar for statically linked-in
drivers and dynamically loaded. However, some of the fields
are to be left empty (that is, initialized to NULL) in the
different types of drivers. The first field (the
As from
This driver was written before the runtime system had SMP support.
The driver will still function in the runtime system with SMP support,
but performance will suffer from lock contention on the driver lock
used for the driver. This can be alleviated by reviewing and perhaps
rewriting the code so that each instance of the driver safely can
execute in parallel. When instances safely can execute in parallel, it
is safe to enable instance-specific locking on the driver. This is done
by passing
Thus, the defined callbacks are as follows:
Must initiate data for a port. We do not create any sockets here, only initialize data structures.
Called when a port is closed.
Handles messages from Erlang. The messages can either be plain data to be sent or more subtle instructions to the driver. This function is here mostly for data pumping.
Called when there is something to read from a socket.
Called when it is possible to write to a socket.
Called when the driver is unloaded. A distribution driver will actually (or hopefully) never be unloaded, but we include this for completeness. To be able to clean up after oneself is always a good thing.
The
The ports implemented by this driver operate in two major modes,
named
While
An enum is defined for the different types of ports:
The different types are as follows:
The type a port has when it is opened, but not bound to any file descriptor.
A port that is connected to a listen socket. This port does not do much, no data pumping is done on this socket, but read data is available when one is trying to do an accept on the port.
This port is to represent the result of an accept operation. It is
created when one wants to accept from a listen socket, and it is
converted to a
Very similar to
A connected socket (or accepted socket) in
The intermediate stage for a connected socket. There is to be no processing of input for this socket.
The mode where data is pumped through the port and the
We study the state that is needed for the ports. Notice that not all fields are used for all types of ports. Some space could be saved by using unions, but that would clutter the code with multiple indirections, so here is used one struct for all types of ports, for readability:
This structure is used for all types of ports although some fields are useless for some types. The least memory consuming solution would be to arrange this structure as a union of structures. However, the multiple indirections in the code to access a field in such a structure would clutter the code too much for an example.
The fields in the structure are as follows:
The file descriptor of the socket associated with the port.
The port identifier for the port that this structure
corresponds to. It is needed for most
If the socket is a listen socket, we use a separate (regular) file for two purposes:
We want a locking mechanism that gives no race conditions, to be sure if another Erlang node uses the listen socket name we require or if the file is only left there from a previous (crashed) session.
We store the
In a system with TCP-based distribution, this data is
kept in the Erlang port mapper daemon
(
The creation number for a listen socket, which is calculated as (the value found in the lock-file + 1) rem 4. This creation value is also written back into the lock file, so that the next invocation of the emulator finds our value in the file.
The current type/state of the port, which can be one of the values declared above.
The name of the socket file (the path prefix removed),
which allows for deletion (
How many bytes that have been sent over the
socket. This can wrap, but that is no problem for the
distribution, as the Erlang distribution is only interested in
if this value has changed. (The Erlang
How many bytes that are read (received) from the
socket, used in similar ways as
A pointer to another port structure, which is either the listen port from which this port is accepting a connection or conversely. The "partner relation" is always bidirectional.
Pointer to next structure in a linked list of all port structures. This list is used when accepting connections and when the driver is unloaded.
Data for input buffering. For details about the input buffering,
see the source code in directory
The implemenation of the distribution driver is not completely covered here, details about buffering and other things unrelated to driver writing are not explained. Likewise are some peculiarities of the UDS protocol not explained in detail. The chosen protocol is not important.
Prototypes for the driver callback routines can be found in
the
The driver initialization routine is (usually) declared with a
macro to make the driver easier to port between different
operating systems (and flavors of systems). This is the only
routine that must have a well-defined name. All other
callbacks are reached through the driver structure. The macro
to use is named
The routine initializes the single global data structure and
returns a pointer to the driver entry. The routine is called
when
The
fd = -1;
( 7) ud->lockfd = -1;
( 8) ud->creation = 0;
( 9) ud->port = port;
(10) ud->type = portTypeUnknown;
(11) ud->name = NULL;
(12) ud->buffer_size = 0;
(13) ud->buffer_pos = 0;
(14) ud->header_pos = 0;
(15) ud->buffer = NULL;
(16) ud->sent = 0;
(17) ud->received = 0;
(18) ud->partner = NULL;
(19) ud->next = first_data;
(20) first_data = ud;
(21)
(22) return((ErlDrvData) ud);
(23) } ]]>
Every data item is initialized, so that no problems arise
when a newly created port is closed (without there being any
corresponding socket). This routine is called when
The
type == portTypeData || ud->type == portTypeIntermediate) {
( 5) DEBUGF(("Passive do_send %d",bufflen));
( 6) do_send(ud, buff + 1, bufflen - 1); /* XXX */
( 7) return;
( 8) }
( 9) if (bufflen == 0) {
(10) return;
(11) }
(12) switch (*buff) {
(13) case 'L':
(14) if (ud->type != portTypeUnknown) {
(15) driver_failure_posix(ud->port, ENOTSUP);
(16) return;
(17) }
(18) uds_command_listen(ud,buff,bufflen);
(19) return;
(20) case 'A':
(21) if (ud->type != portTypeUnknown) {
(22) driver_failure_posix(ud->port, ENOTSUP);
(23) return;
(24) }
(25) uds_command_accept(ud,buff,bufflen);
(26) return;
(27) case 'C':
(28) if (ud->type != portTypeUnknown) {
(29) driver_failure_posix(ud->port, ENOTSUP);
(30) return;
(31) }
(32) uds_command_connect(ud,buff,bufflen);
(33) return;
(34) case 'S':
(35) if (ud->type != portTypeCommand) {
(36) driver_failure_posix(ud->port, ENOTSUP);
(37) return;
(38) }
(39) do_send(ud, buff + 1, bufflen - 1);
(40) return;
(41) case 'R':
(42) if (ud->type != portTypeCommand) {
(43) driver_failure_posix(ud->port, ENOTSUP);
(44) return;
(45) }
(46) do_recv(ud);
(47) return;
(48) default:
(49) return;
(50) }
(51) } ]]>
The command routine takes three parameters; the handle returned for
the port by
If Erlang sends, for example, the list
Creates and listens on socket with the specified name.
Accepts from the listen socket identified by the specified
identification number. The identification number is retrieved with
the
Connects to the socket named <socket name>.
Sends the data <data> on the
connected/accepted socket (in
Receives one packet of data.
"One packet of data" in command
On line 4-8 is handled the case where the port is in
The
port, (ErlDrvEvent) ud->fd, DO_READ, 1);
( 9) } else {
(10) driver_failure_eof(ud->port);
(11) }
(12) return;
(13) }
(14) /* Got a package */
(15) if (ud->type == portTypeCommand) {
(16) ibuf[-1] = 'R'; /* There is always room for a single byte
(17) opcode before the actual buffer
(18) (where the packet header was) */
(19) driver_output(ud->port,ibuf - 1, res + 1);
(20) driver_select(ud->port, (ErlDrvEvent) ud->fd, DO_READ,0);
(21) return;
(22) } else {
(23) ibuf[-1] = DIST_MAGIC_RECV_TAG; /* XXX */
(24) driver_output(ud->port,ibuf - 1, res + 1);
(25) driver_select(ud->port, (ErlDrvEvent) ud->fd, DO_READ,1);
(26) }
(27) }
(28) } ]]>
The routine tries to read data until a packet is read or the
When the port is in
The
type == portTypeListener) {
( 5) UdsData *ad = ud->partner;
( 6) struct sockaddr_un peer;
( 7) int pl = sizeof(struct sockaddr_un);
( 8) int fd;
( 9) if ((fd = accept(ud->fd, (struct sockaddr *) &peer, &pl)) < 0) {
(10) if (errno != EWOULDBLOCK) {
(11) driver_failure_posix(ud->port, errno);
(12) return;
(13) }
(14) return;
(15) }
(16) SET_NONBLOCKING(fd);
(17) ad->fd = fd;
(18) ad->partner = NULL;
(19) ad->type = portTypeCommand;
(20) ud->partner = NULL;
(21) driver_select(ud->port, (ErlDrvEvent) ud->fd, DO_READ, 0);
(22) driver_output(ad->port, "Aok",3);
(23) return;
(24) }
(25) do_recv(ud);
(26) } ]]>
The important line is the last line in the function: the
The output mechanisms are similar to the input.
The
port) == 0) {
(19) if ((written = writev(ud->fd, iov, 2)) == eio.size) {
(20) ud->sent += written;
(21) if (ud->type == portTypeCommand) {
(22) driver_output(ud->port, "Sok", 3);
(23) }
(24) return;
(25) } else if (written < 0) {
(26) if (errno != EWOULDBLOCK) {
(27) driver_failure_eof(ud->port);
(28) return;
(29) } else {
(30) written = 0;
(31) }
(32) } else {
(33) ud->sent += written;
(34) }
(35) /* Enqueue remaining */
(36) }
(37) driver_enqv(ud->port, &eio, written);
(38) send_out_queue(ud);
(39) } ]]>
This driver uses the
The routine builds an I/O vector containing the header bytes
and the buffer (the opcode has been removed and the buffer
length decreased by the output routine). If the queue is
empty, we write the data directly to the socket (or at
least try to). If any data is left, it is stored in the queue
and then we try to send the queue (line 38). An acknowledgement
is sent when the message is delivered completely (line 22). The
The
port, &vlen);
( 6) int wrote;
( 7) if (tmp == NULL) {
( 8) driver_select(ud->port, (ErlDrvEvent) ud->fd, DO_WRITE, 0);
( 9) if (ud->type == portTypeCommand) {
(10) driver_output(ud->port, "Sok", 3);
(11) }
(12) return 0;
(13) }
(14) if (vlen > IO_VECTOR_MAX) {
(15) vlen = IO_VECTOR_MAX;
(16) }
(17) if ((wrote = writev(ud->fd, tmp, vlen)) < 0) {
(18) if (errno == EWOULDBLOCK) {
(19) driver_select(ud->port, (ErlDrvEvent) ud->fd,
(20) DO_WRITE, 1);
(21) return 0;
(22) } else {
(23) driver_failure_eof(ud->port);
(24) return -1;
(25) }
(26) }
(27) driver_deq(ud->port, wrote);
(28) ud->sent += wrote;
(29) }
(30) } ]]>
We simply pick out an I/O vector from the queue
(which is the whole queue as a
We continue trying to write until the queue is empty or the writing blocks.
The routine above is called from the
type == portTypeConnector) {
( 5) ud->type = portTypeCommand;
( 6) driver_select(ud->port, (ErlDrvEvent) ud->fd, DO_WRITE, 0);
( 7) driver_output(ud->port, "Cok",3);
( 8) return;
( 9) }
(10) send_out_queue(ud);
(11) } ]]>
The routine is simple: it first handles the fact that the output select will concern a socket in the business of connecting (and the connecting blocked). If the socket is in a connected state, it simply sends the output queue. This routine is called when it is possible to write to a socket where we have an output queue, so there is no question what to do.
The driver implements a control interface, which is a
synchronous interface called when Erlang calls
Sets port in
Sets port in
Sets port in
Gets identification number for listen port. This identification number is used in an accept command to the driver. It is returned as a big-endian 32-bit integer, which is the file identifier for the listen socket.
Gets statistics, which is the number of bytes received, the number of bytes sent, and the number of bytes pending in the output queue. This data is used when the distribution checks that a connection is alive (ticking). The statistics is returned as three 32-bit big-endian integers.
Sends a tick message, which is a packet of length 0.
Ticking is done when the port is in
Note: It is important that the interface for
sending ticks is not blocking. This implementation uses
Gets creation number of a listen socket, which is used to dig out the number stored in the lock file to differentiate between invocations of Erlang nodes with the same name.
The control interface gets a buffer to return its value in,
but is free to allocate its own buffer if the provided one is
too small. The
received);
(18) put_packet_length((*res) + 5, ud->sent);
(19) put_packet_length((*res) + 9, driver_sizeq(ud->port));
(20) return 13;
(21) }
(22) case 'C':
(23) if (ud->type < portTypeCommand) {
(24) return report_control_error(res, res_size, "einval");
(25) }
(26) ud->type = portTypeCommand;
(27) driver_select(ud->port, (ErlDrvEvent) ud->fd, DO_READ, 0);
(28) ENSURE(1);
(29) **res = 0;
(30) return 1;
(31) case 'I':
(32) if (ud->type < portTypeCommand) {
(33) return report_control_error(res, res_size, "einval");
(34) }
(35) ud->type = portTypeIntermediate;
(36) driver_select(ud->port, (ErlDrvEvent) ud->fd, DO_READ, 0);
(37) ENSURE(1);
(38) **res = 0;
(39) return 1;
(40) case 'D':
(41) if (ud->type < portTypeCommand) {
(42) return report_control_error(res, res_size, "einval");
(43) }
(44) ud->type = portTypeData;
(45) do_recv(ud);
(46) ENSURE(1);
(47) **res = 0;
(48) return 1;
(49) case 'N':
(50) if (ud->type != portTypeListener) {
(51) return report_control_error(res, res_size, "einval");
(52) }
(53) ENSURE(5);
(54) (*res)[0] = 0;
(55) put_packet_length((*res) + 1, ud->fd);
(56) return 5;
(57) case 'T': /* tick */
(58) if (ud->type != portTypeData) {
(59) return report_control_error(res, res_size, "einval");
(60) }
(61) do_send(ud,"",0);
(62) ENSURE(1);
(63) **res = 0;
(64) return 1;
(65) case 'R':
(66) if (ud->type != portTypeListener) {
(67) return report_control_error(res, res_size, "einval");
(68) }
(69) ENSURE(2);
(70) (*res)[0] = 0;
(71) (*res)[1] = ud->creation;
(72) return 2;
(73) default:
(74) return report_control_error(res, res_size, "einval");
(75) }
(76) #undef ENSURE
(77) } ]]>
The macro
The rest of the driver is more or less UDS-specific and not of general interest.
To test the distribution, the
For
If no
The path to the directory where the distribution modules reside
must be known at boot. This can be achieved either by
specifying
The distribution starts at boot if all the above is
specified and an
Example 1:
$ erl -pa $ERL_TOP/lib/kernel/examples/uds_dist/ebin -proto_dist uds -no_epmd Erlang (BEAM) emulator version 5.0 Eshell V5.0 (abort with ^G) 1> net_kernel:start([bing,shortnames]). {ok,<0.30.0>} (bing@hador)2>
Example 2:
$ erl -pa $ERL_TOP/lib/kernel/examples/uds_dist/ebin -proto_dist uds \ -no_epmd -sname bong Erlang (BEAM) emulator version 5.0 Eshell V5.0 (abort with ^G) (bong@hador)1>
The
$ ERL_FLAGS=-pa $ERL_TOP/lib/kernel/examples/uds_dist/ebin \ -proto_dist uds -no_epmd $ export ERL_FLAGS $ erl -sname bang Erlang (BEAM) emulator version 5.0 Eshell V5.0 (abort with ^G) (bang@hador)1>