freeswitch container from scratch using DIND

In this post, I’m going to demonstrate how to build a docker container from a scratch image that will run FreeSWITCH. I’ve always liked scratch because it’s the most minimal docker image available, and in my mind, that really meshes well with the entire concept of docker containers. But I’ll give a bit of my background with scratch and why I’ve used it.

Scratch is simple with Go

I’ve worked with docker containers as microservices for many years now. And I’ve used go to build 99% of microservices I’ve ever written. Go and docker seem to go hand in hand when building microservices. When building microservices written in go, the most practical docker image is scratch.

Scratch works great for software written in go because go doesn’t have any dependencies on external libraries. You can compile your go code for the target environment and add the binary to your container based on scratch. Depending on the size of your go code, you’ll end up with a container that’s only a few megabytes.


# compile your go app:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o myapp


FROM scratch
ADD myapp /
CMD ["/myapp"]

Build your container and run it:

docker build . -t myapp:latest
docker run --rm --name myapp myapp:latest

Not so simple with FreeSWITCH

I’ve talked about how easy it is to use scratch with software written in go. But when you are dealing with software written in C which require external libraries, like FreeSWITCH, it becomes difficult to use the scratch image. The reason for this is, scratch doesn’t come with any libraries at all. This means if you want to use scratch for something like FreeSWITCH, you must include those externally linked libraries in your docker container.

Thankfully, the external libraries FreeSWITCH requires are readily available when you install it on Debian. They will automatically be installed when you use the SignalWire apt-get repo. But finding and adding those external libraries into your docker container isn’t so easy.

I spent a bit of time building FreeSWITCH in a container based on a Debian image. Then I stumbled upon the SignalWire repo which contained a handy script ( to find all the linked libraries FreeSWITCH depends on. I borrowed (and modified) the script quite a bit to fit my needs. Once I was able to build FreeSWITCH in a Debian based container, I wanted to take it a step further and use scratch. I learned about Docker-In-Docker (DinD) at some point along the way.

DinD is a method to use a single Dockerfile to run multiple docker images in order to build a single container. With DinD, I used a Debian 10 image to install FreeSWITCH, run the script to build a binary image which included all linked libraries, then copy the binary over to scratch where everything will run. You end up with a 44M image that runs FreeSWITCH in docker!

The container listed <none> is the DinD container which uses Debian 10. The size of the FreeSWITCH container is significantly smaller.
Dockerfile using DinD

If you’re interested in trying this yourself, I’ve posted my work on github at

kamailio: controlling presence with new module `pua_json`

I recently submitted a new module to the kamailio project which adds an interface to update/control presence records using json. Effectively, you can turn on/off a phone’s Busy Lamp Field (BLF) by sending an http request containing json body to kamailio. The following is a quick guide on how to set up kamailio to accept http requests and update presence using two modules: xhttp and pua_json.

xhttp module

To setup kamailio to listen for http requests, you need to listen on a tcp interface.  I’ve setup kamailio to listen on localhost because I don’t need to expose this service outside of the local machine. So in my kamailio.cfg, I have:

# allow http requests

# load the module
loadmodule "
pua_json module

The pua_json requires no configuration parameters at this time. It simply exposes a function to update presentity from a json object. You will probably want the json module loaded so you can parse and validate some of the json. And you will need to properly configure all your presence modules to handle SIP SUBSCRIBEs, etc…

# load modules
loadmodule ""
loadmodule ""
the event route

The last piece of the setup is the xhttp event_route which is used to handle the http requests containing json object. This is a simple example of such a route:

event_route[xhttp:request] {
    if ($hu != "/presence/") {
        xlog("L_INFO", "invalid request [$hu]");
        xhttp_reply("404", "Not Found", "text/html", "");
     $var(call-id) = $(rb{json.parse,Call-ID});
     xlog("L_INFO", "$var(call-id)|log|[$hu] payload $rb");
     if ($(rb{json.parse,Event-Package}) == "dialog") {
        xlog("L_INFO", "$var(call-id)|log|received $(rb{json.parse,Event-Package}) update for $(rb{json.parse,From}) $rb");
    xhttp_reply("200", "OK", "text/html", "$rb");

The route basically checks to make sure the http endpoint matches `/presence/` and only executes presence updates for “dialog” events. I showed an example of how to parse the Call-ID using the json module as well.

the curl request

Once you have kamailio configured, you are ready to send a curl request to test presence!
Turn on a hold light with a request like so:

curl -d '{"Call-ID":"park+01@test03.vxs.local","Event-Category":"presence","Event-Name":"update","Event-Package":"dialog","Expires":"3600","To":"sip:user01@test03.vxs.local","To-User":"user01","To-Realm":"test03.vxs.local","From":"sip:park+01@test03.vxs.local","From-User":"park+01","From-Realm":"test03.vxs.local","State":"confirmed"}' http://localhost:8080/presence/

Turn off a hold light with a request like (the only difference from above, is the “state” in this request):

curl -d '{"Call-ID":"park+01@test03.vxs.local","Event-Category":"presence","Event-Name":"update","Event-Package":"dialog","Expires":"3600","To":"sip:user01@test03.vxs.local","To-User":"user01","To-Realm":"test03.vxs.local","From":"sip:park+01@test03.vxs.local","From-User":"park+01","From-Realm":"test03.vxs.local","State":"terminated"}' http://localhost:8080/presence/

If you have a phone subscribed to “park+01@test03.vxs.local” you should see the BLF color change when the state is confirmed, and then change back to the original color after the 2nd curl request.

kamailio high availability using keepalived

This is a quick post on how to use keepalived to setup high-availability on two kamailio machines. In this setup there will be a “primary” and “secondary” node. Each node will be running kamailio and keepalived with a “shared” or sometimes referred to as a “floating” IP address.
The idea is that each node will be running health checks on itself and the other node. If a node detects kamailio as being down, it will move the “floating” IP address to itself and become the MASTER node.
After the IP address is moved, all SIP traffic will be automatically directed to the new MASTER node. Both kamailio nodes should be running almost identical routing configs in order to ensure traffic is routed properly after fail-over. This setup was tested on Debian9 with kamailio version 5.10.

We will use the following example IP address setup:

node 1 IP Address:
node 2 IP Address:
“floating” IP Address:

In order for this example to work, you need to enable binding to a non-local IP address. On each node run to enable this setting:
$ echo 1 > /proc/sys/net/ipv4/ip_nonlocal_bind

To permanently save this setting, add the following line to a file like /etc/sysctl.d/99-non-local-bind.conf
net.ipv4.ip_nonlocal_bind = 1

We will want kamailio to bind to the floating IP address and also to allow SIP OPTION pings from each of the other nodes. So you will want something like this in your kamailio.cfg:

#!substdef "!NODE01!!g"
#!substdef "!NODE02!!g"

# bind to local IP and "floating" IP
listen=udp: # on node 2, use here

# main request routing logic
route {

  # allow pings from other node
  if (is_method("OPTIONS") && ($si == "NODE01" || $si == "NODE02")) {



Start kamailio and make sure it’s running.

Next we will setup keepalived. To install everything we need run:
$ apt-get install libipset3 sipsak keepalived

We will be using sipsak with a custom bash script to report the “health” of each node. Add the following bash script to node 1 at /etc/keepalived/


return_code=0 # success

# check local instance
timeout 2 sipsak -s sip:$node01:5060
if [[ $exit_status -eq 0 ]]; then
  echo "sip ping successful to node01 [$node01]"
  exit $return_code

# local instance failed, check remote
timeout 2 sipsak -s sip:$node02:5060
if [[ $exit_status -eq 0 ]]; then
  echo "sip ping successful to node02 [$node02]"

echo "return code [$return_code]"

exit $return_code

Make sure the file is executable:
$ chmod +x /etc/keepalived/
The script on node 1 checks the health of kamailio locally first (by sending a SIP OPTION ping), if it fails, it checks the health of node 2. If node 1 is healthy, it reports success to keepalived by returning 0. If node 1 is not healthy and node 2 is healthy, it reports a failure to keepalived by returning 1.

And add the following bash script to node 2 at /etc/keepalived/


return_code=1 # fail

# check remote instance fist
timeout 2 sipsak -s sip:$node01:5060
if [[ $exit_status -eq 0 ]]; then
  echo "sip ping successful to node01 [$node01]"
  exit $return_code

# remote instance failed, check local
timeout 2 sipsak -s sip:$node02:5060
if [[ $exit_status -eq 0 ]]; then
  echo "sip ping successful to node02 [$node02]"

echo "return code [$return_code]"

exit $return_code

Make sure the file is executable:
$ chmod +x /etc/keepalived/
The script on node 2 checks the health of kamailio on node 1 (remotely) first, if it fails, it checks the health of node 2 (locally). If node 1 is healthy, it reports a “local” failure to keepalived by returning 1. If node 1 is not healthy and node 2 is healthy, it reports a “success” to keepalived by returning 0.

keepalived will promote the node to MASTER based on the return code reported by the bash scripts. You can get more creative and add more logic if you’d like, but for the purposes of this post, I kept it simple.

Last we will configure keepalived by editing the following file on node 1: /etc/keepalived/keepalived.conf

vrrp_script check_sip {
  script "/etc/keepalived/"
  interval 6 # check every 6 seconds

vrrp_instance VI_SBC {
  state MASTER
  interface eth0
  virtual_router_id 51
  advert_int 1
  authentication {
    auth_type PASS
    auth_pass 11111
  virtual_ipaddress { dev eth0
  track_script {

And on node 2: /etc/keepalived/keepalived.conf

vrrp_script check_sip {
  script "/etc/keepalived/"
  interval 6 # check every 6 seconds

vrrp_instance VI_SBC {
  state BACKUP
  interface eth0
  virtual_router_id 51
  advert_int 1
  authentication {
    auth_type PASS
    auth_pass 11111
  virtual_ipaddress { dev eth0
  track_script {

The settings above basically say to check health of each node every 6 seconds. If the node should become master, enable the floating IP (

Start keepalived service on each node and watch the syslog. As long as kamailio is running and responsive to the SIP OPTION pings on node 1, it will be MASTER. You can test by turning off kamailio on node 1 and watching the IP move to node 2. Use the following command to check for the IP address:
$ ip addr show


Kamailio and FreeSWITCH on the same server with NSQ and JANSSON-RPC

This post will demonstrate how to run FreeSWITCH and Kamailio on a single server.
FreeSWITCH will handle authentication and act as registrar while Kamailio will handle presence updates using the NSQ module. You might be wondering why this setup would be useful. The reason we found, is that FreeSWITCH is not so great at handling presence updates. It relies heavily on SQL queries, and when you are dealing with 800+ user-agents all doing presence, FreeSWITCH can’t really keep up. You also may be wondering why not have Kamailio act as registrar. The reason FreeSWITCH will be registrar is we had a system in place already (single FreeSWITCH instance) and it would require too large of a change to move authentication to Kamailio. So this exact setup may not be so useful for many, it does contain helpful hints on how to run Kamailio and FreeSWITCH together on a single server, it also demonstrates use of NSQ and the JANSSON-RPC module.

In order for FreeSWITCH and Kamailio to run on a single server, both services must bind to different ports on a single interface or on separate interfaces altogether. In this setup, I have FreeSWITCH setup to bind SIP on the loopback interface (, RTP on the public facing interface and Kamailio binding to the public facing interface ( I used the dispatcher module to detect if FreeSWITCH is up or down.
Here is my dispatcher.list:

#setid sipdest flags priority attrs
1 sip: 2 0 duid=1

Next you’ll have to setup a FreeSWITCH sofia profile to bind to loopback for SIP and public interface for RTP:

<configuration name="sofia.conf" description="Sofia">
    <profile name="local">
        <param name="sip-ip" value=""/>
        <param name="sip-port" value="5060"/>
        <param name="rtp-ip" value=""/>

I named the profile local but you can obviously name it whatever you like. That’s it for the FreeSWITCH side of things, make sure your profile is loaded by doing:
fs_cli -x "sofia status profile local"

You should see in output:

URL                     sip:mod_sofia@
BIND-URL                sip:mod_sofia@;transport=udp,tcp

Now it’s time to setup Kamailio, I’ll highlight some important sections and attach the entire kamailio.cfg at the end of post.
First thing I like to do in my kamailio.cfg is setup the global definitions that will be used later (that way the script is more portable):

# - defines
#!define DBURL "postgres://kamailio:kamailio@localhost/kamailio"
#!define JANSSON_RPC "conn=presence;addr=localhost;port=8080;priority=10;weight=10"
#!define LISTEN

The DBURL is required for presence and NSQ modules, so you will need to provision your database with the appropriate tables. Now define the module parameters, the ones I will highlight are related to NSQ:

modparam("nsq", "db_url", DBURL)
modparam("nsq", "consumer_workers", 1)
modparam("nsq", "topic_channel", "presence:kamailio")
modparam("nsq", "max_in_flight", 200)
modparam("nsq", "lookupd_address", "nsqlookup01")
modparam("nsq", "pua_mode", 1)

The topic_channel tells Kamailio to listen for messages on the presence topic and uses the kamailio channel. The lookupd_address tells kamailio to how to find the producers. If you are unfamiliar with NSQ, I suggest you check out the documentation (

I setup a JANSSON-RPC server running on the localhost (written in golang) which checks for active calls when a user-agent subscribes and sends an NSQ message to Kamailio in the event the To-User is actually on a call. Here we define the JANSSON-RPC server:

modparam("janssonrpc-c", "result_pv", "$var(jsrpc_result)")
modparam("janssonrpc-c", "server", JANSSON_RPC)

The result_pv is used to receive results from the RPC request. In our case, we don’t care about the result since our NSQ module will receive a message on result.

Now let’s check out the route section of our config. You’ll notice one of the first thing that happens in our config is CHECK_SOURCE_IP

    if ($si == "") {
    } else {

Since we should only be receiving requests from FreeSWITCH on the loopback, we can easily determine “who” is sending our SIP packet. I set a flag here, FLAG_FROM_FREESWITCH, which is very important later on. If the packet is not from FreeSWITCH, we do some NAT handling:

    if (is_method("REGISTER")) {
        if (nat_uac_test("19")) {
    } else {
        if (nat_uac_test("3")) {
        if (has_body("application/sdp") && nat_uac_test("8")) {

We handle NAT for REGISTERs in a specific way here because we must send the correct contact header to FreeSWITCH, otherwise FreeSWITCH will get contact header containing a private IP and will not know how to route INVITEs to the user-agent.

Next we handle the SIP SUBSCRIBE:

route[SUBSCRIBE] {
    if (is_method("SUBSCRIBE")) {
        if (!t_newtran()) {

        if ($tU == $null) {
            xlog("L_INFO", "$ci|stop|ignoring subscribe with empty TO username from a $ua");
            sl_send_reply(400, "Missing TO username");

        if ($fU == $null) {
            xlog("L_INFO", "$ci|stop|ignoring subscribe with empty FROM username from a $ua");
            sl_send_reply(400, "Missing FROM username");

        # do an RPC request to check for Active calls
        if ($rU != $null) {
            # forward message-summary SUBSCRIBEs to FreeSWITCH
            if ($hdr(Event) == "message-summary") {
                xlog("L_INFO", "$ci|log|CHECKING MESSAGE SUMMARY");
            } else {
                xlog("L_INFO", "$ci|log|CHECKING PRESENCE");
                janssonrpc_notification("presence", "Server.QueryPresence", '[{"CallId":"' + $ci + '","FromUser":"' + $fU + '","FromDomain":"' + $fd + '","ToUser":"' + $rU + '","ToDomain":"' + $rd + '"}]');

        if (!handle_subscribe()) {
            xlog("L_INFO", "$ci|stop|unsupported subsribe");


We are validating the SUBSCRIBE, then checking the event type. If it’s a message-summary event, we add a record-route header and forward it to FreeSWITCH. (We could handle message-summary using NSQ but right now it’s easier for FreeSWITCH to handle it and doesn’t put a strain on FreeSWITCH)
If it’s not a message-summary event, we send an RPC request to our service which should know if the To-User is on a call or not, if they are on a call, our RPC server sends an NSQ message to the presence topic.
You’ll notice the next section is for handling NSQ messages:

# receive presence updates from NSQ and update watchers
event_route[nsq:consumer-event-presence-update] {
    $var(call-id) = $(nsqE{nsq.json,Call-ID});
    xlog("L_INFO", "$var(call-id)|log|payload $nsqE");
    if ($(nsqE{nsq.json,Event-Package}) == "dialog") {   
        if($sht(p=>$var(call-id)) != $(nsqE{nsq.json,State}) || $(nsqE{nsq.json,Flush-Level}) != $null) {
             xlog("L_INFO", "$(nsqE{nsq.json,Call-ID})|log|received $(nsqE{nsq.json,Event-Package}) update for $(nsqE{nsq.json,From}) state $(nsqE{nsq.json,State})");
             $sht(p=>$(nsqE{nsq.json,Call-ID})) = $(nsqE{nsq.json,State});
             pres_refresh_watchers("$(nsqE{nsq.json,From})", "$(nsqE{nsq.json,Event-Package})", 1);
        } else {
            xlog("L_INFO", "$var(call-id)|log|received duplicate $(nsqE{nsq.json,Event-Package}) update for $(nsqE{nsq.json,From}) state $(nsqE{nsq.json,State})");
            xlog("L_INFO", "$var(call-id)|log|payload $nsqE");
    } else {
       xlog("L_INFO", "$var(call-id)|log|received $(nsqE{nsq.json,Event-Package}) update for $(nsqE{nsq.json,From}) $nsqE");
       pres_refresh_watchers("$(nsqE{nsq.json,From})", "$(nsqE{nsq.json,Event-Package})", 1);

The NSQ message must be json format and contain the required fields for the presence module to send an update. I’ll save those details for another post.

Let’s go back up to the main routing block of our config now.

    # handle SUBSCRIBE requests

    # handle requests within SIP dialogs

    # handle retransmissions
    if(t_precheck_trans()) {

    if (is_method("INVITE|REFER")) {

    if (is_method("NOTIFY") && $hdr(event) == "check-sync" && isflagset(FLAG_FROM_FREESWITCH)) {
        xlog("L_INFO", "$ci|log|Rebooting phone [$ru]\n");
        t_on_reply("REPLY_FROM_DEVICE"); # handle NAT

After handling SUBSCRIBEs, we check for in-dialog request and route them. We add a record_route header if INVITE or REFER. Then we handle NOTIFYs with check-sync events specially. This allows us to remotely reboot phones which support the feature.

The next portion is important when forwarding a REGISTER to another registrar:

    if (!isflagset(FLAG_FROM_FREESWITCH) && is_method("REGISTER")) {

If we do not add a path header to the REGISTER before forwarding to FreeSWITCH, FreeSWITCH will not know to send INVITEs to user-agents through Kamailio.

The last part of our main routing block does some final checks to decide how/where to send the packet.


Our dispatch route checks if the SIP signal is from FreeSWITCH, if so, fix NAT on replies to it. If not from FreeSWITCH (e.g. from outside user-agent), send to FreeSWITCH:

route[DISPATCH] {
    if (isflagset(FLAG_FROM_FREESWITCH)) {
        t_on_reply("REPLY_FROM_DEVICE"); # handle NAT
    } else if (!ds_select_dst("1", "0")) {
        #if we are here that means no destination is available. We notify the user by 404 and exit the script.
        xlog("L_NOTICE", "No destination available!");
        send_reply("404", "No destination");

And here is the relay route:

route[RELAY] {
    if (is_method("INVITE")) {
        if(!t_is_set("failure_route")) t_on_failure("MANAGE_FAILURE");

    if (!t_relay()) {

And that’s it!
Here is the full kamailio.cfg


Setup an SMTP server with user authentication using postgres, postfix, and dovecot on Debian 8

Please note: this tutorial assumes postgres is already setup and configured on the machine.
Install & configure the dovecot and postfix:

apt-get install dovecot-core dovecot-pgsql postfix -y

Provision the smtp database in postgres:

su -c "psql -c \"CREATE USER smtp WITH PASSWORD 'smtp';\"" postgres
su -c "psql -c \"CREATE DATABASE smtp WITH OWNER=smtp;\"" postgres

Encrypt you password using doveadm tool and SHA512-CRYPT:

doveadm pw -s SHA512-CRYPT -p test1234 -r 100000

Create the SQL file with your one test user:

cat > smtp.sql<<EOT
    id SERIAL,
    username VARCHAR(128) NOT NULL,
    password VARCHAR(512) NOT NULL,
    constraint username_key unique (username)
insert into users (username, password) values ('emailuser01', '************************');


Import your SQL table and test user:

psql -h localhost -d 'smtp' -U smtp -W < smtp.sql

Configure dovecot
Open /etc/dovecot/conf.d/10-master.conf in your favorite text editor and uncomment the following:

  # Postfix smtp-auth
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666

Enable SQL and login auth:

sed -i "s/auth_mechanisms = plain/auth_mechanisms = plain login/g" /etc/dovecot/conf.d/10-auth.conf
sed -i "s/\!include auth-system.conf.ext/#\!include auth-system.conf.ext/g" /etc/dovecot/conf.d/10-auth.conf
sed -i "s/#\!include auth-sql.conf.ext/\!include auth-sql.conf.ext/g" /etc/dovecot/conf.d/10-auth.conf

Disable the default password scheme

sed -i "s/default_pass_scheme/#default_pass_scheme/g" /etc/dovecot/dovecot-sql.conf.ext

Enable SHA512-CRYPT and set database parameters

cat >>/etc/dovecot/dovecot-sql.conf.ext<<EOT
default_pass_scheme = SHA512-CRYPT
driver = pgsql
connect = host=localhost dbname=smtp user=smtp password='smtp'
password_query = select username as user, password from users where username = '%n';


Restart dovecot

service dovecot restart

Configure postfix to use dovecot for sasl

postconf -e 'smtpd_sasl_type = dovecot'
postconf -e 'smtpd_sasl_auth_enable = yes'
postconf -e 'smtpd_recipient_restrictions = permit_sasl_authenticated,permit_mynetworks,reject_unauth_destination'
postconf -e 'smtpd_sasl_path = private/auth'

Enable submission for clients on port tcp/587

sed -i "s/\#submission/submission/g" /etc/postfix/

Restart postfix

service postfix restart

Email client setup example

Now configure your mail client to use the SMTP server. For this example we will say the mail client is postfix and the smtp server we just setup has an IP of emailuser01:test1234 > /etc/postfix/sasl_passwd
postmap hash:/etc/postfix/sasl_passwd
cat >>/etc/postfix/ <<EOT

smtp_sasl_auth_enable = yes
smtp_sasl_mechanism_filter = plain, login
smtp_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
relayhost =


Restart postfix

service postfix restart

Send test email

echo "TEST" > testemail
mail -s "TEST EMAIL" < testemail

RTPEngine with Kamailio as Load-balancer and IP Gateway

This post explains how to setup Kamailio as an SBC and IP Gateway. We are using Debian 8 in this example. It uses Kamailio’s dispatcher module to distribute calls to Asterisk. It uses RTPEngine to proxy media to & from the public internet across the LAN to Asterisk.
This is a powerful setup as you can easily scale out using a single public IP address.
Here is the IP layout we will be implementing:

Kamailio Public (eth0)
Kamailio Private (eth0)
Asterisk machine 1 -
Asterisk machine 2 -

Setup Debian and iptables to act as IP Gateway:

# edit /etc/sysctl.conf
enabled net.ipv4.ip_forward=1

# add iptables rules
iptables -F
iptables -t nat -F

iptables -P INPUT ACCEPT

iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i eth1 -s -j ACCEPT
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Install RTPEngine + Kamailio with RTPEngine Module.


Download kamailio.cfg

Download sip.conf

Download /etc/default/ngcp-rtpengine-daemon

Kamailio: High-Availability/Failover with Corosync and Pacemaker on Debian 7

In this setup, we will have 2 Kamailio servers, referred to as ‘nodes’. One will be active and one will standby. There is a 3rd ‘floating’ IP that is moved to which ever node is active. Kamailio should be configured to use the floating IP. In this example, the nodes are:


Floating IP:

First, add both nodes to /etc/hosts    kam01    kam02

Install corosync and pacemaker:

apt-get install ntp corosync pacemaker -y

Generate /etc/corosync/authkey:


Copy corosync-key  to kam02:

scp -P 22 /etc/corosync/authkey root@kam02:/etc/corosync

Enable corosync on kam01 & kam02:

sed -i "s/START=no/START=yes/g" /etc/default/corosync

Enable pacemaker service in corosync:

cat > /etc/corosync/service.d/pcmk << EOF
service {
  name: pacemaker
  ver: 1

Add corosync config:

cat >/etc/corosync/corosync.conf<<EOF
totem {
        version: 2
        transport: udpu
        interface {
                member {
                member {
                ringnumber: 0
                mcastport: 5405

logging {
        to_logfile: yes
        logfile: /var/log/corosync/corosync.log
        debug: off
        timestamp: on
        logger_subsys {
                subsys: AMF
                debug: off

Start corosync and pacemaker:

service corosync start
service pacemaker start

Configure corosync, changes will propagate to other node. Make sure to disable stonith:

crm configure property stonith-enabled=false
crm configure primitive FAILOVER-IP ocf:heartbeat:IPaddr2 params ip="" nic="eth0" cidr_netmask="" op monitor interval="10s"
crm configure primitive KAM-HA lsb:kamailio op monitor interval="30s"
crm configure group KAM-HA-GROUP FAILOVER-IP KAM-HA
crm configure colocation KAM-HA-GROUP-COLO inf: FAILOVER-IP KAM-HA
crm configure order KAM-HA-ORDER inf: FAILOVER-IP KAM-HA
crm configure property no-quorum-policy=ignore

You need no-quorum-policy=ignore for a 2 node cluster. If you messed up during the crm configure part, you can start over using these commands:

crm configure property stop-all-resources=true
crm configure erase

It’s sometimes useful to see what resource agents are available, you can check with these commands:

crm ra list lsb
crm ra list systemd # (if using systemd init system)
crm ra list ocf heartbeat
crm ra list ocf pacemaker

If you need to migrate services and floating IP to other node you can run:

crm resource migrate KAM-HA-GROUP kam02

If you need edit specific parameters in the config, you can export it to xml, make the changes and re-import them:

cibadmin --query > tmp.xml
vi tmp.xml
cibadmin --replace --xml-file tmp.xml


RTPProxy: Compiling & Installing on Debian 8

cd /usr/src/
git clone
cd rtpproxy
make install

cp scripts/rtpproxy.init.debian /etc/init.d/rtpproxy
chmod +x /etc/init.d/rtpproxy
sed -i "s/DAEMON=\/usr\/bin\/rtpproxy/DAEMON=\/usr\/local\/bin\/rtpproxy/g" /etc/init.d/rtpproxy

cat > /etc/default/rtpproxy <<EOT
# Defaults for rtpproxy
# I like to use same user as Kamailio when running on Kamailio box
# replace with your network interface IP address

# The control socket.
# To listen on an UDP socket, uncomment this line:

# Additional options that are passed to the daemon.



/etc/init.d/rtpproxy start

FreeSWITCH: High call volume alert script

I was tasked to come up with a way to monitor for high call volume in FreeSWITCH. I came up with this here is a simple script that will check the channel count and email me if it’s greater than $MAX_CALLS



CHANNEL_COUNT=$(/usr/bin/fs_cli -x "show channels count" | awk '/total/ {print $1}')

if [ $CHANNEL_COUNT -gt $MAX_CALLS ]; then
        # From
        # Subject
        SUBJECT="High Call Volume"
        # To

        /usr/bin/mailx "-aFrom:$FROM" -s "$SUBJECT" "$TOEMAIL"<<END
This is an email alert to notify you that the server has reached $CHANNEL_COUNT calls.


Kamailio: Compiling & Installing on Debian 8

Here we will compile and install Kamailio from GIT master branch and create our own systemd service configuration file.

# install dependencies
apt-get install libpq-dev pkg-config build-essential bison make libperl-dev git linux-headers-$(uname -r) libunistring-dev flex libjson-c-dev libevent-dev 

# download & compile
cd /usr/src
git clone git:// kamailio-git
cd kamailio-git

# include your own modules, these are what i compile
make include_modules="db_postgres debugger usrloc dispatcher registrar auth auth_db avp avpops tm rr pv sl maxfwd nathelper textops siputils uac uac_redirect db_text xlog sanity htable app_perl path ctrl tls ctl mi_fifo kex permissions dmq dialog websocket xhttp textopsx sdpops kazoo tmx uuid presence presence_xml presence_dialoginfo presence_mwi outbound" cfg

make all

make install

# add kam group/user
groupadd -g 6001 kamailio
useradd -u 6001 -g 6001 -d /usr/local/kamailio -M -s /bin/false kamailio

# create custom directories for kamailio
mkdir -p /usr/local/kamailio/{run,etc,tmp}

# create kamailio default file
cat >/etc/default/kamailio <<EOT

# create systemd file
cat >/etc/systemd/system/kamailio.service<<EOT
Description=Kamailio (OpenSER) - the Open Source SIP Server

# ExecStart requires a full absolute path
ExecStart=/usr/local/sbin/kamailio -P \$PIDFILE -f \$CFGFILE -m \$SHM_MEMORY -M \$PKG_MEMORY -u \$USER -g \$GROUP
ExecStopPost=/bin/rm -f \$PIDFILE



# enable kamailio service
systemctl enable kamailio

# if you change the systemd file you can reload changes with:
systemctl daemon-reload

# set permissions to /usr/local/kamailio
chown kamailio:kamailio -R /usr/local/kamailio

Please note, by default, Kamailio will install it’s configuration files in /usr/local/etc/kamailio, modules in /usr/local/lib64/kamailio, and binaries in /usr/local/sbin