# &adminguide;

## Overview

This module offers SIP load balancer functionality and it can be used as SIP traffic dispatcher. There are many load balancing and traffic dispaching algorithms that you can choose from, like: round-robin, weight based load balancing, call load distribution, hashing over SIP message attributes.

The module can be used as a stateless load balancer, it does not depend on any call state tracking module. It requires the TM module if you enable auto-discovery of active/inactive gateways.

It is very lightweight, therefore suitable for handling heavy SIP traffic. The module has a small footprint and ability to load balancing rules from a text plain file makes it suitable for embedded systems.

## Dependencies

### &kamailio; modules

The following modules must be loaded before this module:

- TM - only if active recovery of failed hosts is required.

- database engine - only if you want to load balancing routes from database instead of plain text file. .

### External libraries or applications

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

- none.

## Parameters

### `list_file` (string)

Path to the file with destination sets.

Default value is /etc/kamailio/dispatcher.list or /usr/local/etc/kamailio/dispatcher.list.

#### Set the list_file parameter

    ...
    modparam("dispatcher", "list_file", "/var/run/kamailio/dispatcher.list")
    ...

### `db_url` (string)

If you want to load the sets of gateways from the database you must set this parameter.

Default value is NULL (disable DB support).

#### Set db_url parameter

    ...
    modparam("dispatcher", "db_url", "mysql://user:passwb@localhost/database")
    ...

### `table_name` (string)

If you want to load the sets of gateways from the database you must set this parameter as the database name.

Default value is dispatcher.

#### Set table_name parameter

    ...
    modparam("dispatcher", "table_name", "my_dispatcher")
    ...

### `setid_col` (string)

The column's name in the database storing the gateway's group id.

Default value is setid.

#### Set setid_col parameter

    ...
    modparam("dispatcher", "setid_col", "groupid")
    ...

### `destination_col` (string)

The column's name in the database storing the destination sip URI.

Default value is destination.

#### Set destination_col parameter

    ...
    modparam("dispatcher", "destination_col", "uri")
    ...

### `flags_col` (string)

The column's name in the database storing the flags for the destination URI.

Default value is flags.

#### Set flags_col parameter

    ...
    modparam("dispatcher", "flags_col", "dstflags")
    ...

### `priority_col` (string)

The column's name in the database storing the priority for destination URI.

Default value is priority.

#### Set priority_col parameter

    ...
    modparam("dispatcher", "priority_col", "dstpriority")
    ...

### `force_dst` (int)

If set to 1, force overwriting of destination address (outbound proxy) when that is already set. If set to 0, will return error when the destination address is already set.

Default value is 1.

#### Set the force_dst parameter

    ...
    modparam("dispatcher", "force_dst", 1)
    ...

### `flags` (int)

Various flags that affect dispatcher's behaviour. The flags are defined as a bitmask on an integer value. If flag 1 is set only the username part of the URI will be used when computing an URI based hash. If no flags are set the username, hostname and port will be used. The port is used only if different from 5060 (normal sip URI) or 5061 (in the sips: case).

If flag 2 is set, then failover support is enabled. The functions exported by the module will store the rest of addresses from the destination set in the AVP, and use these AVPs to contact next address if the current-tried destination fails.

Default value is 0.

#### Set the flags parameter

     ...
     modparam("dispatcher", "flags", 3)
     ...

### `use_default` (int)

If the parameter is set to 1, the last address in destination set is used as a final option to send the request to. For example, it is useful when wanting to send the call to an anouncement server saying: "the gateways are full, try later".

Default value is 0.

#### Set the use_default parameter

     ...
     modparam("dispatcher", "use_default", 1)
     ...

### `dst_avp` (str)

The name of the avp which will hold the list with addresses, in the order they have been selected by the chosen algorithm. If use_default is 1, the value of last dst_avp_id is the last address in destination set. The first dst_avp_id is the selected destinations. All the other addresses from the destination set will be added in the avp list to be able to implement serial forking.

You must set this parameter if you want to do load balancing fail over.

Default value is null - don't add AVPs.

#### Set the dst_avp parameter

     ...
     modparam("dispatcher", "dst_avp", "$avp(dsdst)")
     ...

### `grp_avp` (str)

The name of the avp storing the group id of the destination set. Good to have it for later usage or checks.

You must set this parameter if you want to do load balancing fail over.

Default value is null - don't add AVP.

#### Set the grp_avp parameter

     ...
     modparam("dispatcher", "grp_avp", "$avp(dsgrp)")
     ...

### `cnt_avp` (str)

The name of the avp storing the number of destination addresses kept in dst_avp AVPs.

You must set this parameter if you want to do load balancing fail over.

Default value is null - don't add AVP.

#### Set the cnt_avp parameter

     ...
     modparam("dispatcher", "cnt_avp", "$avp(dscnt)")
     ...

### `dstid_avp` (str)

The name of the avp storing the destination unique ID used for call load based dispatching.

You must set this parameter if you want to do load balancing on call load (alg 10).

Default value is null - don't add AVP.

#### Set the dstid_avp parameter

     ...
     modparam("dispatcher", "dstid_avp", "$avp(dsdstid)")
     ...

### `attrs_avp` (str)

The name of the avp storing destination's attributes value.

Default value is null - don't add AVP.

#### Set the attrs_avp parameter

     ...
     modparam("dispatcher", "attrs_avp", "$avp(dsattrs)")
     ...

### `hash_pvar` (str)

String with PVs used for the hashing algorithm 7.

You must set this parameter if you want do hashing over custom message parts.

Default value is null - disabled.

#### Use $avp(i:273) for hashing:

     ...
     modparam("dispatcher", "hash_pvar", "$avp(i:273)")
     ...

#### Use combination of PVs for hashing:

     ...
     modparam("dispatcher", "hash_pvar", "hash the $fU@$ci")
     ...

### `setid_pvname` (str)

The name of the PV where to store the set ID (group ID) when calling ds_is_from_list() with no parameter.

Default value is null - don't set PV.

#### Set the setid_pvname parameter

     ...
     modparam("dispatcher", "setid_pvname", "$var(setid)")
     ...

### `attrs_pvname` (str)

The name of the PV where to store the attributes of matching address when calling ds_is_from_list().

Default value is null - don't set PV.

#### Set the attrs_pvname parameter

     ...
     modparam("dispatcher", "attrs_pvname", "$var(attrs)")
     ...

### `ds_ping_method` (string)

With this method you can define, with which method you want to probe the gateways. Pinging gateways feature depends on ds_ping_interval parameter.

Default value is OPTIONS.

#### Set the ds_ping_method parameter

     ...
     modparam("dispatcher", "ds_ping_method", "INFO")
     ...

### `ds_ping_from` (string)

With this Method you can define the "From:"-Line for the request, sent to the failed gateways. This method is only available, if compiled with the probing of failed gateways enabled.

Default value is sip:dispatcher@localhost.

#### Set the ds_ping_from parameter

     ...
     modparam("dispatcher", "ds_ping_from", "sip:proxy@sip.somehost.com")
     ...

### `ds_ping_interval` (int)

With this parameter you can define the interval for sending a request to a gateway marked as inactive upon a failed request routing to it. This parameter is only used, when the TM-Module is loaded. If set to 0, the pinging of inactive gateway is disabled.

Default value is 0.

#### Set the ds_ping_interval parameter

     ...
     modparam("dispatcher", "ds_ping_interval", 30)
     ...

### `ds_probing_threshold` (int)

If you want to set a gateway into inactive mode, there can be a specific number of failed requests until it will change from "active" to "inactive". It is using the state "trying", that allows selection of gateway but indicates there was a failure previously with the gateway. The number of attempts can be set with this parameter. This parameter can be modified via ser config framework.

Default value is 1 (set inactive with first failure).

#### Set the ds_probing_threshhold parameter

     ...
     modparam("dispatcher", "ds_probing_threshhold", 10)
     ...

### `ds_ping_reply_codes` (string)

This parameter defines the valid response codes, which are accepted as a valid reply to the PING-Method. It is a list separated by colons, whery you may define either a single code (e.g. "code=202" would accept 202 as an additional, valid response) or a class of responses, you want to accept (e.g. "class=2" would accept everything from 200 to 299 as valid response). This parameter can be modified via ser config framework.

Default value is (only 200 OK is accepted).

#### Set the ds_ping_reply_codes parameter

     ...
     modparam("dispatcher", "ds_ping_reply_codes", "class=2;code=403;code=488;class=3")
     ...

### `ds_probing_mode` (int)

Controls what gateways are tested to see if they are reachable. If set to 0, only the gateways with state PROBING are tested; if set to 1, all gateways are tested; if set to 2, only gateways in inactive state with probing mode set are tested. If set to 1 and there is a failure of keepalive to an active gateway, then it is set to TRYING state.

Default value is 0.

#### Set the ds_probing_mode parameter

     ...
     modparam("dispatcher", "ds_probing_mode", 1)
     ...

### `ds_hash_size` (int)

The value to be used as power of two to set the number of slots to hash table storing data for call load dispatching (e.g., value 8 will create a hash table with 256 slots). It must be greater than 0 to enable call load dispatching feature (alg 10).

Default value is 0.

#### Set the ds_hash_size parameter

     ...
     modparam("dispatcher", "ds_hash_size", 9)
     ...

### `ds_hash_expire` (int)

Expiration time in seconds to remove the load on a destination if no BYE was received meanwhile.

Default value is 7200.

#### Set the ds_hash_expire parameter

     ...
     modparam("dispatcher", "ds_hash_expire", 3600)
     ...

### `ds_hash_initexpire` (int)

Expiration time in seconds to remove the load on a destination if no 200 for INVITE was received meanwhile and state updated with ds_load_update().

Default value is 7200.

#### Set the ds_hash_initexpire parameter

     ...
     modparam("dispatcher", "ds_hash_initexpire", 60)
     ...

### `ds_hash_check_interval` (int)

Time interval in seconds to scan internal hash table with call load dispatching data for expired items.

Default value is 30.

#### Set the ds_hash_check_interval parameter

     ...
     modparam("dispatcher", "ds_hash_check_interval", 60)
     ...

### `outbound_proxy` (str)

SIP URI of outbound proxy to be used when sending pings.

By default no outbound proxy is defined.

#### Set the outbound_proxy parameter

     ...
     modparam("dispatcher", "outbound_proxy", "sip:outbound.example.com")
     ...

## Functions

### `ds_select_dst(set, alg)`

The method selects a destination from addresses set. It returns true if a new destination is set. The selected address is set to dst_uri field (aka the outbound proxy address or the $du variable), not being visible in the SIP request.

If the bit 2 in 'flags' parameter is set, the rest of the addresses from the destination set is stored in AVP list. You can use 'ds_next_dst()' to use next address in order to achieve serial forking to all possible destinations.

Meaning of the parameters is as follows:

- set - the id of the set from where to pick up destination address. It is the first column in destination list file. The parameter can be an integer or a variable holding an integer.

- alg - the algorithm used to select the destination address. The parameter can be an integer or a variable holding an interger.

  - 0 - hash over callid

  - 1 - hash over from URI.

  - 2 - hash over to URI.

  - 3 - hash over request-URI.

  - 4 - round-robin (next destination).

  - 5 - hash over authorization-username (Proxy-Authorization or "normal" authorization). If no username is found, round robin is used.

  - 6 - random (using rand()).

  - 7 - hash over the content of PVs string. Note: This works only when the parameter hash_pvar is set.

  - 8 - use first destination (good for failover).

  - 9 - use weight based load distribution. You have to set the attribute 'weight' per each address in destination set.

  - 10 - use call load distribution. You have to set the attribute 'duid' (as an unique string id) per each address in destination set. Also, you must set parameters 'dstid_avp' and 'ds_hash_size'.

    The algorithm can be used even with stateless proxy mode, there is no SIP dialog tracking depending on other modules, just an internal lightweight call tracking by Call-Id, thus is fast and suitable even for embedded systems.

    The first destination selected by this algorithm is the one that has the least number of calls associated. The rest of the destination list is taken in order of the entries in set - anyhow, until a re-route to next destination happens, the load on each address can change.

    This algorithm can be used only for dispatching INVITE requests as it is the only SIP method creating a SIP call.

  - X - if the algorithm is not implemented, the first entry in set is chosen.

If the bit 2 in 'flags' is set, the rest of the addresses from the destination set is stored in AVP list. You can use 'ds_next_dst()' to use next address to achieve serial forking to all possible destinations.

This function can be used from REQUEST_ROUTE, FAILURE_ROUTE.

#### `ds_select_dst` usage

    ...
    ds_select_dst("1", "0");
    ...
    $var(a) = 4;
    ds_select_dst("1", "$var(a)");
    ...

### `ds_select_domain(set, alg)`

The method selects a destination from addresses set and rewrites the host and port from R-URI. The parameters have same meaning as for ds_select_dst().

If the bit 2 in 'flags' is set, the rest of the addresses from the destination set is stored in AVP list. You can use 'ds_next_domain()' to use next address to achieve serial forking to all possible destinations.

This function can be used from REQUEST_ROUTE, FAILURE_ROUTE.

### `ds_next_dst()`

Takes the next destination address from the AVPs with id 'dst_avp_id' and sets the dst_uri (outbound proxy address).

This function can be used from REQUEST_ROUTE, FAILURE_ROUTE.

### `ds_next_domain()`

Takes the next destination address from the AVPs with id 'dst_avp_id' and sets the domain part of the request URI.

This function can be used from REQUEST_ROUTE, FAILURE_ROUTE.

### `ds_mark_dst([state])`

Mark the last used address from destination set as inactive ("i"/"I"), active ("a"/"A"), disabled ("d"/"D") or trying ("t"/"T"). Apart of disabled state, a destination can be set in probing mode by adding ("p"/"P") flag. With this function, an automatic detection of failed gateways can be implemented. When an address is marked as inactive or disabled, it will be ignored by 'ds_select_dst' and 'ds_select_domain'.

The parameter state is optional, when it is missing, then the destination will be marked inactive (i.e., same as 'i').

Possible values for state parameter:

- "a" or "A" - the last destination should be set to active and the error-counter should set to "0".

- "i" or "I" - the last destination should be set to inactive and will be ignored in future requests.

- "t" or "T" - the last destination should be set to temporary trying state and failure counter is incremented. When the failure counter reaches the threshold, the destination will be set inactive.

- "p" and "P" - this has to be used in addition to one of the previous flags - the last destination will be set to probing. This mean the destination will be pinged with SIP OPTIONS requests from time to time to detect if it is up running or down.

This function can be used from REQUEST_ROUTE, FAILURE_ROUTE.

#### `ds_mark_dst` usage

    ...
    failure_route[tryagain] {
    ...
       if(t_check_status("500"))
          ds_mark_dst("ip"); # set to inactive and probing
    ...
    }
    ...

### `ds_is_from_list([groupid])`

This function returns true, if the current request comes from a host in the given group of the dispatcher-list; otherwise false.

Parameter groupid is optional, when it is missing, then the matching will be done against all addresses in all groups. Upon a match, the variable specified by 'setid_pvname' parameter will be set to groupid of matching address and the attributes will be set in variable specified by 'attrs_pvname'. The parameter can be an integer or a variable holding an integer value.

This function can be used from ANY_ROUTE.

#### `ds_mark_dst` usage

    ...
    if(ds_is_from_list("10")) {
        ...
    }
    ...

### `ds_load_update()`

Updates the load state:

- if it is a BYE or CANCEL - remove the load from destination address used to forward the INVITE

- if it is a reply to INVITE - set internal state to confirmed for call load structure when reply code is 2xx.

This function can be used from REQUEST_ROUTE, FAILURE_ROUTE, BRANCH_ROUTE and ONREPLY_ROUTE.

### `ds_load_unset()`

Remove the call load for the destination that routed the call.

This function can be used from REQUEST_ROUTE, FAILURE_ROUTE, BRANCH_ROUTE and ONREPLY_ROUTE.

#### `ds_load_unset` usage

    ...
    route {
        ...
    	if(is_method("BYE|CANCEL"))
            ds_load_update();
        ...
    	ds_select_dst("1", "10");
        ...
    }

    onreply_route {
        ...
        if(is_method("INVITE")
    	{
            if(status=~"2[0-9][0-9]")
                ds_load_update();
            else if(status=~"[3-7][0-9][0-9]")
                ds_load_unset();
        }
        ...
    }
    ...

## MI Commands

### `ds_set_state`

Sets the status for a destination address (can be use to mark the destination as active or inactive).

Name: ds_set_state

Parameters:

- _state_ : state of the destination address

  - a: active

  - i: inactive

  - t: trying

  - d: disabled

  The states a, i or t can be followed by p to set probing mode (e.g. 'ap', 'ip' or 'tp').

- _group_: destination group id

- _address_: address of the destination in the _group_

MI FIFO Command Format:

    		:ds_set_state:_reply_fifo_file_
    		_state_
    		_group_
    		_address_
    		_empty_line_

### `ds_list`

It lists the groups and included destinations.

Name: ds_list

Parameters: none

MI FIFO Command Format:

    		:ds_list:_reply_fifo_file_
    		_empty_line_

### `ds_reload`

It reloads the groups and included destinations. For algorithm 10 (call load distribution), old internal list of active calls is destroyed (because it is bould to the previous list of gateways), meaning that the module is starting to count active calls again from 0.

Name: ds_reload

Parameters: none

MI DATAGRAM Command Format:

    		":ds_reload:\n."

## Exported RPC Commands

### `dispatcher.set_state`

Sets the state for a destination address (can be use to mark the destination as active or inactive).

Name: dispatcher.set_state

Parameters:

- _state_ : state of the destination address

  - a: active

  - i: inactive

  - t: trying

  - d: disabled

  The states a, i or t can be followed by p to set probing mode (e.g. 'ap', 'ip' or 'tp').

- _group_: destination group id

- _address_: address of the destination in the _group_

Example:

    ...
    # prototype: &sercmd; dispatcher.set_state _state_ _group_ _address_
    &sercmd; dispatcher.set_state ip 2 sip:127.0.0.1:5080
    ...

### `dispatcher.list`

Lists the groups and included destinations.

Name: dispatcher.list

Parameters: none

Example:

    		&sercmd; dispatcher.list

### `dispatcher.reload`

Reloads the groups and included destinations. The command is disabled for call load based dispatching (algorithm 10) since removal of destinations may leave the list of active calls with broken references.

Name: dispatcher.reload

Parameters: none

Example

    		&sercmd; dispatcher.reload

## Installation and Running

### Destination List File

Each destination point must be on one line. First token is the set id (an integer value), followed by destination address (s string value in SIP URI format).

Optionally, these fields can be followed by:

- flags (listed by index - can be bitwise mask of values): 0 (value 1) - inactive destination; 1 (value 2) - temporary trying destination (in the way to become inactive if it does not reply to keepalives - there is a module parameter to set the threshold of failures); 2 (value 4) - admin disabled destination; 3 (value 8) - probing destination (sending keep alives);

- priority: sets the priority in destination list (based on it is done the initial ordering inside the set)

- attributes: extra filed in form of name1=value1;...;nameN=valueN. There are some predefined names that are used of weight and call load dispatching.

Line format is:

    ...
    setid(int) destination(sip uri) flags(int,opt) priority(int,opt) attrs(str,opt)
    ...

Full line example:

    ...
    1 sip:127.0.0.1:5080 0 0 duid=abc;my=xyz
    ...

For database, each element of a line resides in a different column. Next is a dispatcher.list file example:

#### dispatcher list file

    ...

    ...

### &kamailio; config file

Next picture shows a sample usage of the dispatcher module.

#### &kamailio; config script - sample dispatcher usage

    ...

    ...

## Event routes

### `dispatcher:dst-down`

When defined, the module calls event_route[dispatcher:ds-down] when a destination goes down (becomes probing). A typical use case is to update NMC equipment as to the status of a destination.

    ...
    event_route[dispatcher:dst-down] {
        xlog("L_ERR", "Destination down: $rm $ru ($du)\n");
    }
    ...

### `dispatcher:dst-up`

When defined, the module calls event_route[dispatcher:ds-up] when a destination that was previously down (probing) comes up. A typical use case is to update NMC equipment as to the status of a destination.

    ...
    event_route[dispatcher:dst-up] {
        xlog("L_ERR", "Destination up: $rm $ru\n");
    }
    ...