# &adminguide;

## Overview

Erlang is a general-purpose programming language and runtime environment. Erlang has built-in support for concurrency, distribution and fault tolerance. This module provides interact with Erlang node. The module allows sending, receiving Erlang messages and RPC calls between each other.

## Dependencies

### &kamailio; Modules

The following modules must be loaded before this module:

- None

### External Libraries or Applications

The following libraries or applications must be installed before running &kamailio; with this module loaded:

- ei - Erlang interface C library.

  The routines for handling the Erlang binary term format and communicate with with distributed Erlang. For more details see Erlang Interface Reference Manual

- epmd - Erlang Port Mapper Daemon.

  This daemon acts as a name server on all hosts involved in distributed Erlang computations. For more details see Erlang Port Mapper Daemon Manual.

epmd must running on the same host where &kamailio; is running. Erlang does not need to be installed on the same host where &kamailio; is running.

## Parameters

### `no_cnodes` (int)

Number of erlang C node processes to be started to handle the communication tasks. A C node is a C program written to act as a hidden node in a distributed Erlang system.

Default value is 1.

#### Set `no_cnodes` parameter

    ...
    modparam("erlang", "no_cnodes", 2)
    ...

### `cnode_alivename` (str)

alivename is the registered name of the &kamailio; process.

Note, if the `no_cnodes` is greater than 1, then alivename of &kamailio; process will be suffixed with number.

#### Set `cnode_alivename` parameter

    ...
    modparam("erlang", "cnode_alivename", "proxy")
    ...

### `cnode_host` (str)

C node host is the name of the machine we're running on. If long names are to be used, it should be fully qualified.

#### Set `cnode_host` parameter

    ...
    modparam("erlang", "cnode_host", "kamailio.lan")
    ...

### `erlang_nodename` (str)

The format of the node name is a name@host where name is the name given by the user and host is the full host name if long names are used, or the first part of the host name if short names are used.

#### Set `erlang_nodename` parameter

    ...
    modparam("erlang", "erlang_nodename", "node1@erlang.lan")
    ...

### `cookie` (str)

Each node has its own magic cookie. When a nodes tries to connect to another node, the magic cookies are compared If they do not match, the connected node rejects the connection.

#### Set `cookie` parameter

    ...
    modparam("erlang", "cookie", "secretcookie")
    ...

### `trace_level` (int)

Used to set tracing on the distribution. The parameter is different verbosity level. A higher level means more information. Useful in development, but in production should be disabled.

The different tracelevels has the following messages:

1. Verbose error messages
2. Above messages and verbose warning messages
3. Above messages and progress reports for connection handling
4. Above messages and progress reports for communication
5. Above messages and progress reports for data conversion

Default value is 0, no verbose is set. To see trace log on stdout, &kamailio; must be started with -E option.

#### Set `trace_level` parameter

    ...
    modparam("erlang", "trace_level", 5)
    ...

### `rpc_reply_with_struct` (int)

Prepend Erlang atom struct in RPC &kamailio; reply where RPC struct is generated. Some libraries for converting erlang term in JSON require atom struct as first element in tuple to convert list of properties into javscript object.

Default value is 0 (disabled).

## Exported pseudo variables

### Overview

Erlang provides a number of data types but not all of them are supported by &kamailio;. This module provides several of them as pseudo variables. These pseudo variables allow user to create Erlang message or function arguments and receive result from Erlang node. Some Erlang variables can contain other data types, so we introduced several attributes to determine type, length, or get formatted output useful for debug, quick compare or put into the log.

### Attributes

Exported pseudo variable has several attributes to get type, length and formatted output readable by transformations or user. Pseudo variable by self determine variable type, but we need to know what type on some position is.

- `type`

  get variable type. Possible types are: atom, integer, list, string, tuple, pid and ref.

- `length`

  get length of list or tuple.

- `format`

  Prints a term, in clear text. It tries to resemble the term printing in the Erlang shell.

#### Example of using attribute length

    ...
    xlogl("L_DEBUG","The number of elements in list L: $erl_list(L=>length)\n");
    xlogl("L_DEBUG","The number of elements in tuple T: $erl_tuple(T=>length)\n");
    ...

    > example of log output:

    DEBUG: <script>: 120:The number of elements in list L: 4
    DEBUG: <script>: 121:The number of elements in tuple T: 2
    ...

#### Example of using attributes type and format

    ...
    xlogl("L_DEBUG","list L in clear text: $erl_list(L=>format), the type at index 2: $erl_list(L[2]=>type)\n");
    xlogl("L_DEBUG","tuple T in clear text: $erltuple(T=>format), the type at index 1: $erl_tuple[T[1]=>type)\n");
    ...

    > example of log output:

    DEBUG: <script>: 130:list L in clear text: [example, list, 4, "items"], the type at index 2: integer
    DEBUG: <script>: 131:tuple T in clear text: {example, tuple}, the type at index 1: atom
    ...

### `$erl_atom(name)`

erl_atom pseudo variable allows create analog to Erlang atom data type. Erlang atom is a literal, a constant with name. Formatted output pseudo variable atom could be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @.

#### Example set and print to log $erl_atom

    ...
    $erl_atom(A) = "badrpc";
    xlogl("L_DEBUG","$$erl_atom(A): $erl_atom(A=>format)\n");
    ...

    > log output is:

    DEBUG: <script>: 123:$erl_atom(A): badrpc
    ...

### `$erl_list(name)`

Compound data type with a variable number of terms. Formally, a list is either the empty list [] or consists of one or more elements.

Behavior of the list is the same as AVP variable. Set value without index prepends element on list. You are able to replace element at given index. List supports [*] index to get whole list or reset all elements in the list. To create empty list set whole list to $null.

#### Example of using $erl_list

    ...
    $erl_atom(E) = "example";
    $erl_list(L) = "list";
    $erl_list(L) = "of";
    $erl_list(L) = $erl_atom(E);

    xlogl("L_DEBUG","length(L): $erl_list(L=>length), format(L): $erl_list(L=>format)\n");

    # empty list
    $erl_tuple(E[*]) = $null;

    xlogl("L_DEBUG","length(E): $erl_list(E=>length), format(E): $erl_list(L=>format)\n");
    ...

    > log output is:

    DEBUG: <script>: 143:length(L): 3, format(L): [example, "of", "list"]
    DEBUG: <script>: 148:length(E): 0, format(E): []
    ...

### `$erl_tuple(name)`

From the Erlang point of view the tuple compound data type with a fixed number of terms. The module implementation of tuple has the same behavior as the list.

#### Example of using erl_tuple

    ...
    $erl_atom(line) = "line";
    $erl_atom(id)   = "id";
    $erl_atom(owner)= "owner";

    $var(user)  = "Bob";

    $erl_tuple(owner) = $var(user);
    $erl_tuple(owner) = $erl_atom(owner);

    $erl_tuple(id) = 23;
    $erl_tuple(id) = $erl_atom(id);

    $erl_list(L) = $erl_tuple(owner);
    $erl_list(L) = $erl_tuple(id);

    $erl_tuple(T) = $erl_list(L);
    $erl_tuple(T) = $erl_atom(line);

    xlogl("L_DEBUG","length(T): $erl_tuple(T=>length), format(T): $erl_tuple(T=>format)\n");
    ...

    > log output is:
    ...
    DEBUG: <script>: 153:length(T): 2, format(T): {line, [{id, 23}, {owner, "Bob"}]}
    ...

### `$erl_pid(name)`

erl_pid holds Eralng process identifier. Provides access to Erlang PID value and could be used in send message.

#### Example of using $erl_pid

    ...
    if ($erl_xbuff(msg[0]=>type) == "pid") {
    	$erl_pid(pid) = $erl_xbuff(msg[0]);
    	xlogl("L_INFO","Received PID: $erl_pid(pid=>format)\n");
    }
    ...

### `$erl_ref(name)`

erl_ref holds Erlang reference. Provides access to reference value and could be used in send message.

#### Example of using erl_ref

    ...
    if ($erl_xbuff(msg[0]=>type) == "ref") {
    	$erl_ref(ref) = $erl_xbuff(msg[0]);
    	xlogl("L_INFO","Reference: $erl_ref(ref=>format)\n");
    }
    ...

### `$erl_xbuff(name)`

erl_xbuff is created as generic pseudo variable to acts as other pseudo variables exported from module. It's useful when in advance we don't know what variable type to expect. The behavior of variable depends of initialization. Module functions expect this PV as return value, and PV for incoming Erlang message.

#### Example of using $erl_xbuff

    ...
    # Tuple T from previous example

    $erl_xbuff(X) = $erl_tuple(T);

    xlogl("L_DEBUG","typeof(X): $erl_xbuff(X=>type), length(X): $erl_xbuff(X=>length), format(X): $erl_xbuff(X=>format)\n");
    ...

    > log output is:
    ...
    DEBUG: <script>: 410:typeof(X): tuple, length(X): 2, format(X): {line, [{id, 23}, {owner, "Bob"}]}
    ...

## Functions

### `erl_rpc(mod, fun, args, reply)`

This function supports calling Erlang functions on remote nodes.

The parameter mod and fun are module and function name respectively. It can be a static string or a dynamic string value with config variables.

The parameter args is list of arguments passed to function, so it must be list, or xbuff that contains list.

The parameter reply is result from RPC call. It must be xbuff to accept any result.

Function returns false on error to send or wrong arguments passed to function. If executing remote function caused error function still returns true but error is encoded into repl parameter.

#### Example of using erl_rpc

    ...
    # example of call erlang:list_to_tuple(["one","two"])
    # on remote node

    $erl_list(L) = "two";
    $erl_list(L) = "one";

    # put list into list
    $erl_list(args) = $erl_list(L);

    erl_rpc("erlang", "list_to_tuple", "$erl_list(args)", "$erl_xbuff(repl)");

    xlogl("L_DEBUG","type(repl): $erl_xbuff(repl=>type), format(repl): $erl_xbuff(repl=>format)\n");

    > log output:
    ...
    DEBUG: <script>: 386:type(repl): tuple, format(repl): {"one", "two"}
    ...

### `erl_reg_send(server, msg)`

This function sends an Erlang term to a registered process.

The argument server is the registered name of the intended recipient process on remote node.

The argument msg is containing the message to be sent.

#### Example of using erl_reg_send

    ...
    # example of send message to registered process
    # {notifier,'node1@erlang.lan'} ! {example,message}

    $erl_atom(example) = "example";
    $erl_atom(message) = "message";

    $erl_tuple(M) = $erl_atom(message);
    $erl_tuple(M) = $erl_atom(example);

    erl_reg_send("notifier","$erl_tuple(M)");
    ...

### `erl_send(pid, msg)`

This function sends an Erlang term to a process. This function can be used from ANY_ROUTE. The argument pid is the Erlang process id of the intended recipient process on remote node. The argument msg is containing the message to be sent.

#### Example of using erl_send

    ...
    # example of send message to process
    # Pid ! {example,message}

    $erl_atom(notifier) = "notifier";
    $erl_list(args) = $erl_atom(notifier);

    erl_rpc("erlang", "whereis", "$erl_list(args)", "$erl_xbuff(pid)");

    $erl_atom(example) = "example";
    $erl_atom(message) = "message";

    $erl_tuple(M) = $erl_atom(message);
    $erl_tuple(M) = $erl_atom(example);

    erl_send("$erl_xbuff(pid)","$erl_tuple(M)");
    ...

### `erl_reply(msg)`

Function to send message from event route (pseudo process). Function sends reply message msg to the sender process.

#### Example of use erl_reply

    ...
    # event route acts as registered process
    event_route[erlang:greetings] {

    	xlogl("L_INFO","Received message: $erl_xbuff(msg=>format)\n");

    	$erl_atom(hello) = "hello";
    	$erl_tuple(reply) = "Erlang";
    	$erl_tuple(reply) = $erl_atom(hello);

    	# reply greeting
    	erl_reply("$erl_tuple(reply)");
    }
    ...

    %% in erlang shell

    (node1@erlang.lan)24> {greetings,'proxy@kamailio.lan'} ! {hello,"Kamailio"}.
    {hello,"Kamailio"}
    (node1@erlang.lan)25> flush().
    Shell got {hello,"Erlang"}
    ok

    > logged info message:
    INFO: <script>: 951:Received message: {"hello", "Kamailio"}
    >

## Event routes

To allow &kamailio; C node to have similar to erlang registered processes we can use event routes. Event routes executed when asynchronous message received from erlang node.

Event route receives message in `$erl_xbuff(msg)` and sender process in `$erl_xbuff(pid)`. Reply message is optional and can be sent with erl_reply.

### Registered pseudo process

To create pseudo erlang registered process in &kamailio; script create event route in form of `event_route[erlang:<my_process_name>]`. Where <my_process_name> is the name of pseudo process.

#### Example of registered process

    ...
    # event route acts as registered process
    event_route[erlang:handler] {

    	xlogl("L_INFO","Received message: $erl_xbuff(msg=>format)\n");

    }
    ...

    %% in erlang shell send message to registered process

    (node1@erlang.lan)12> {handler,'proxy@kamailio.lan'} ! {"hello","Kamailio"}.
    {"hello","Kamailio"}

    > logged info message:
    INFO: <script>: 951:Received message: {"hello", "Kamailio"}
    >

### `event_route[erlang:self]`

The reserved pseudo process name to receive messages sent to &kamailio; C node. The message are sent to non registered process.

#### Example of using default event route

    ...
    # default event route from erlang
    event_route[erlang:self] {

    	xlogl("L_INFO","Received message: $erl_xbuff(msg=>format)\n");

    	if(pv_isset("$erl_xbuff(msg[1])") && $erl_xbuff(msg[1]=>type) == "pid") {
    		xlogl("L_INFO","Echo reply to: $erl_xbuff(msg[1]=>format)\n");
    		erl_send("$erl_xbuff(msg[1])","$erl_xbuff(msg[0])");
    	}
    }
    ...

    %% in erlang shell send message to registered process

    (node1@erlang.lan)12> Pid=rpc:call('proxy@kamailio.lan',erlang,whereis,[self]).
    <14808.9.0>
    (node1@erlang.lan)14> Pid ! ["hello from",self()].
    ["hello from",<0.247.0>]
    (node1@erlang.lan)15> flush().
    Shell got "hello from"
    ok

    > logged info messages:
    INFO: <script>: 653:Received message: ["hello from", <node1@erlang.lan.247.0>]
    INFO: <script>: 656:Echo reply to: <node1@erlang.lan.247.0>]
    >