Thursday, January 18, 2018

OpenSIPS Geo-Distributed Clustering & Data-Exchange

OpenSIPS Clusterer Module


Summary:

OpenSIPS 2.4 now allows users to exchange user data between clustered proxy nodes via proto_bin module. As a result the receiving Proxy can perform an action.

In this blog post I'll try to show how we can exchange that data from the opensips script.

USE CASE: Multi-Proxy cluster sharing User Locations and Querying Cluster to Find Users.




The Slideshow above shows a simple setup where multiple proxies can "Talk" to each other without using any other application as the communication platform.

Previously we could share data as a one-way pipe to SQL, or NoSQL applications. By one-way pipe I mean that OpenSIPS server can deposit data but won't do anything as a recipient. since there is no way to tell each opensips box that you are the recipient and need to do something.

OpenSIPS introduced the Event_route and EBR (Event Based Routing) some time ago but the custom events can not trigger on their own w/o developing some MI script. Obviously, the concept of adding more scripts and tools to make a fully functional distributed OpenSIPS environment is complicated to develop and maintain.

Clusterer module in older versions of OpenSIPS (pre-devel/2.4) was only capable to exchange data from certain module internally i.e dialog, usrloc - user has no control over what data to be sent and how to perform an action when such a data is received.


WHATS NEW

1 - OpenSIPS cluster can broadcast script based Queries and wait for replies, perform action based on reply!
  • Cluster can detect and share IP of a hacker with other nodes to perform some action
  • Update cluster about Location of a user, inquire about location of a user and send call to relevant proxy
  • Cluster can update about an ongoing conference call, other boxes can route calls to the hosting proxy
  • A Central OpenSIPS talking to Database on behalf of rest of the OpenSIPS cluster. SQL statements only reside there rest of the cluster only sends small text to expect a small reply. Useful incase of depositing CDRs.

     If you've multiple FreeSWITCH boxes behind an OpenSIPS and multiple such deployments needing integration then this is going to be perfect to collect an ESL event and Broadcast it from local OpenSIPS to rest of the regions. This could be a game changer for multi-region deployments.


TIME FOR ACTION

Lets see how this all can be done from inside the opensips.cfg
A complete sample config file is available here:
https://github.com/goharahmed/opensips-clusterer

Loading Modules




The "db_mode" param is set to 0 so we don't depend on DB to find other Cluster nodes, its my personal preference you can load all cluster nodes from MySQL DB and run mi-fifo command to reload the new node data.
What I've done is added two core nodes in the config so any new node just needs to point to any one of the core servers and everyone will be aware of the whole cluster topology.

Event_routing module are critical for this to work, they invoke config file script when a certain event is triggered.


Sharing Data

First we need to identify what data needs to be shared across the cluster. In the code snippet below I figure I need to tell other boxes if some hacker is trying to make Bruteforce Registration to users which are not defined in my DB. Also, I share the successfully registered user info.




Here are the exact routes responsible for Broadcasting the message string to the cluster.



Infact these Lines are the real deal here:

        $var(cl_id) = 1;
        $var(msg_str) = "I_LOVE_OPENSIPS";
        cluster_broadcast_req("$var(cl_id)", "$var(msg_str)", "$avp(tag)");

Since we are sharing Data so we need to carefully fill the details as to which cluster this info needs to be routed to and what message to be delivered. The Tag is filled in automatically and is very important for retrieval of any replies.

Remote Proxy Data Retrieval

Once this is executed all Online nodes of the cluster will receive this message in an Event Route "E_CLUSTERER_REQ_RECEIVED"



Remote Proxy Replying Back

The AVP $avp(rcv_msg) will contain the sent string and we can script what to do further with that. Similarly the $avp(source_id) variable will contain the NodeID of the sender proxy so if we need to reply back we can send a reply using the same TAG. It is NOT mandatory for the cluster nodes to reply to each and every broadcasted message btw. They can remain silent if there is nothing to be replied with.



Receiving Reply

Once remote proxy replies with the same tag (OpenSIPS internaly differentiates between a Request and a Reply) an event is raised "E_CLUSTERER_RPL_RECEIVED" -

In this Event Route we don't need to do much, this is just collection of replied data. The real work is done elsewhere.



 Finding Location of a User in Cluster

This is approximately how the code will look like for a call where user was not found registered and query was dispatched to whole cluster. The Querying OpenSIPS waits for an event to occur in async mode (wait w/o blocking resources for as long as needed)


That is pretty much all that is required to create a Talking-Cluster of OpenSIPS servers.

WARNING: This is a work in progress from OpenSIPS developers and should be tested heavily before deploying in production. Version 2.4 is expected to be released as stable production release by May-2018 or around. 

Saturday, June 25, 2016

OpenSIPS mi_xmlrpc_ng Interfacing

OpenSIPS 2.2: Creating WebAPI 

OpenSIPS has multiple modules to interact with it in realtime. Sometimes we need to pull information out of the proxy and sometimes we need to insert, or check status of other modules. 

Here is a list of module which can be used to achieve the objective:

MI_DATAGRAMDATAGRAM (unix and network) support for Management Interfacestable
MI_FIFOFIFO support for Management Interfacestable
MI_HTTPHTTP support for Management Interfacestable
MI_JSONJSON support via HTTP GET for Management Interfacebeta
MI_XMLRPC_NGXMLRPC support for Management Interfacebeta

In my last blog on this topic I showed how to use module MI_XMLRPC to monitor the status of OpenSIPS: Read it here. That mi_xmlrpc module is now obsolete and a newer module mi_xmlrpc_ng has taken its place. 

Today we will use the new module with OpenSIPS and see how we can query our server from the internet to do something. 

First we need to know what we require to get started.

1 - HTTPD module, and MI_XMLRPC_NG module installed with OpenSIPS 2.2
2 - Apache2/ httpd running on the Server.

OpenSIPS' HTTPD module is a requirement since this module provides the web related backend to its other modules.

Lets load up this module into our opensips.cfg

loadmodule "httpd.so"
modparam("httpd", "ip", "127.0.0.1")
modparam("httpd", "port", 8887)
modparam("httpd", "buf_size", 524288)
modparam("httpd", "post_buf_size", 4096)

Next we need to load mi_xmlrpc_ng module.

loadmodule "mi_xmlrpc_ng.so"
modparam("mi_xmlrpc_ng", "http_root", "mybox")


The root directory 'mybox' can be anything and it does not represent any folder in the operating system. That infact tells us that when we start up our OpenSIPS the port for http will be 8887, and the web root directory allocated for mi_xmlrpc_ng module would be 'mybox' .

Web API script

Next we need to create the script that will be responsible to collect Requests from internet and then pass them to OpenSIPS, return data if any. 

This script can be written in any language, Pythin, PHP, Perl, GoLang, Ruby, whatever your language of choice for creating a web-api is use is. I'd kept it simple and use PHP.

Complete script link: https://github.com/goharahmed/scripts/blob/master/webapi.php

Copy the script into your Apache2 webroot directory , say file 'webapi.php'

<?php

$opensip_ip = '127.0.0.1';
//Should use the same HTTPD PORT as declared in opensips.cfg
$opensip_xmlrpc_port = '8887';
//Should use the same webroot as declared in mi_xmlrpc_ng module parameters
$xmlrpc_root = 'mybox';

$count = 0;
$method;
$param;
$web_req = 0;
if(isset($_GET) && isset($_GET['method'])){
 foreach($_GET as $key => $value)
 {
  if($key == 'method') { 
   $method = $value;
  }
  if(preg_match("/^param\d$/",$key)) {
   $param[] = $value;

  }
 }
 $web_req = 1;
} else {
 foreach ($argv as $arg) {
  if($count==1)
   $method =  $arg;
  else if($count>1) {  
   $param[] = $arg;
  }
  $count++; 
 }
}
$request = xmlrpc_encode_request($method,$param);
$context = stream_context_create(array('http' => array(
    'method' => "POST",
    'header' => "Content-Type: text/xml",
    'content' => $request
    )));
    
// Dispatchs Request to Local OpenSIPS instance
$server = 'http://'.$opensip_ip.':'.$opensip_xmlrpc_port.'/'.$xmlrpc_root;

//Collect Result from opensips module
$file = file_get_contents($server, false, $context);

//Decode the XML into Array
$response = xmlrpc_decode($file);
if (is_array($response)) {
 
 /* We can filter and sort Output here to do whatever you want to do */
 /* if($method == 'ul_show_contact') {
  Then filter only the required fields to be sent back
 } else if ($method == 'ds_list') {
  Then filter the output to show only the active servers
 }
 */
 if($web_req == 0) {
  RecursiveWrite($response);
 }else if($web_req == 1) {
  print_r(json_encode($response));
  
  
 }
}

function RecursiveWrite($array) {
    foreach ($array as $key => $vals) {
 if(is_array($vals)){
         RecursiveWrite($vals);
 } else {
  print "$key $vals\n";
 }
    }
}

?>
Now, make sure your opensips is restarted to include the new module, make sure your server is able to listen to the web requests. Time to send requests to our OpenSIPS.


Open your browser and paste the following URL to find if a particular suer is Online or Not.

http://YourServerIPHere/webapi.php?method=ul_show_contact&param1=location&param2=gohar@saevolgo.ca


Little Explanation:

method = MI command to query the user location status
param1 = The database table where the User Registrations are stored.
param2 = The AoR to find if Online

You can add as many param as you want , param3, param4...paramN depending if the MI command needs or not.

If a command requires no parameter then don't add any for example:
http://YourServerIPHere/webapi.php?method=lb_list

To get Statistics:
http://YourServerIPHere/webapi.php?method=get_statistics&param1=tm:

OpenSIPS Modules: How to read what command has how many parameters ?

Take example of Load-Balancer module:
The function lb_relaod has no parameters:
 :lb_reload:_reply_fifo_file_
  _empty_line_
So my URL would be:
http://YourServerIPHere/webapi.php?method=lb_reload


But the function lb_resize takes 3 parameteres:
:lb_resize:_reply_fifo_file_
  11   /*dstination id*/
  voicemail  /*resource name*/
  56   /* new resource capacity*/
  _empty_line_
For above the URL would be:
http://YourServerIPHere/webapi.php?method=lb_resize&param1=11&param2=voicemail&param3=56


Thats pretty much all, thanks for reading. 





Monday, March 28, 2016

FreeSWITCH mod_xml_curl With mod_callcenter

FreeSWITCH Loading Queues from Database

This has been a long due post waiting in my drafts for above two years now. This was done right after when I finished loading SIP users from Database in this blog post.

I always found myself at trouble when FreeSWITCH's MOD_XML_CURL was named together with loading configurations but as soon as I gave it a shot it became very easy and interesting. 

Here is how to get started with loading queue from Database in just few minutes. 

Here is what we need to get started:

1 - Database table containing Queue's parameters.
2 - A WebServer containing our DB-to-XML converter code
3 - FreeSWITCH with mod_xml_curl installed and configured.


Creating Table for Queue Parameters 

So, first things first lets create a simple Database table:

root@DBSERVER:# su - postgres
postgres@DBSERVER:~$ psql
psql (9.4.6)
Type "help" for help.

postgres=# \c freeswitch_configs
You are now connected to database "freeswitch_configs" as user "postgres".
freeswitch_configs=#

CREATE TABLE queues (
queue_id  serial primary key,
name VARCHAR(255) not null,
strategy VARCHAR(100) default 'longest-idle-agent',
moh_sound VARCHAR(255) default 'local_stream://moh',
announce_sound VARCHAR(255) default NULL,
announce_frequency VARCHAR(5) default NULL,
time_base_score VARCHAR(255) DEFAULT 'queue' ,
tier_rules_apply VARCHAR(25) DEFAULT 'false',
tier_rule_wait_second VARCHAR(4) DEFAULT '300',
tier_rule_wait_multiply_level VARCHAR(5) DEFAULT 'true',
tier_rule_no_agent_no_wait VARCHAR(255) DEFAULT 'false',
discard_abandoned_after VARCHAR(5) DEFAULT '60',
abandoned_resume_allowed VARCHAR(5) DEFAULT 'false',
max_wait_time VARCHAR(25) DEFAULT '0',
max_wait_time_with_no_agent VARCHAR(10) DEFAULT '0',
max_wait_time_with_no_agent_time_reached VARCHAR(10) DEFAULT '0',
record_template VARCHAR(255) DEFAULT NULL
);


Once Table is created you can go ahead and create some queues in it via INSERT statements.


Setting up WebServer


Alright, we've some queues defined into our database table. Now, is the time to create a web service which will query the Database and pull required configurations. Once configurations are found for a queue we will put them nicely into the required XML format and reply back.

Take the PHP sample code from my github repo:
https://github.com/goharahmed/saevolgo/blob/master/getconfig.php

Configure the Database IP, Port, User, and Password as required and make sure there is no error in it.
Once this is ready and running we can query to this web service and see that it returns an Error XML if no queue name is passed to it.

Test it:
http://ip.of.webserver:port/freeswitch/getconfig.php?CC-Queue=MyQueueName

If everything is configured properly and Queue: MyQueueName exists then it should print a fine XML - if that doesn't happen then check your PHP code, PHP PDO extension for PGSQL and verify that port is accessible and webserver is running. 


Configuring MOD_XML_CURL


Assuming mod_xml_curl is installed on your FreeSwitch server now its time to configure its module xml_curl to pull configurations from webserver instead of local file.

root@FREESWITCH1:# cd /usr/local/freeswitch/conf
root@FREESWITCH1:conf# cd autoload_configs/
root@FREESWITCH1:autoload_configs# vim xml_curl.conf.xml


<configuration name="xml_curl.conf" description="cURL XML Gateway">
  <bindings>
    <binding name="configuration">         
      <param name="gateway-url" value="http://WEBSERVER/freeswitch/getconfig.php" bindings="configuration"/>
    </binding>
  </bindings>
</configuration>

Ensure that there are no other configuration binding to conflict here.

Save and exit. Go inside freeswitch console and reload mod_xml_curl

root@FREESWITCH1:# fs_cli
fs_cli>reload mod_xml_curl 
+OK Reloading XML
+OK module unloaded
+OK module loaded

All set, now we are ready to load Queues from Database directly. To test things out issue this command

freeswitch@internal> callcenter_config queue load MynewQueue
+OK
freeswitch@internal> callcenter_config queue list
name|strategy|moh_sound|time_base_score|tier_rules_apply|tier_rule_wait_second|tier_rule_wait_multiply_level|tier_rule_no_agent_no_wait|discard_abandoned_after|abandoned_resume_allowed|max_wait_time|max_wait_time_with_no_agent|max_wait_time_with_no_agent_time_reached|record_template
support@default|longest-idle-agent|local_stream://moh|system|false|300|true|false|60|false|0|0|5|
MynewQueue|longest-idle-agent||queue|false|0|false|true|60|false|0|0|5|
+OK

To debug XML Curl

freeswitch@internal> xml_curl debug_on
OK

freeswitch@internal> callcenter_config queue load NOTMYQUEUE
-ERR Invalid Queue not found!

2016-03-28 19:32:21.128783 [CONSOLE] mod_xml_curl.c:323 XML response is in /tmp/3337e053-077c-4f39-9c3f-0805c4896851.tmp.xml
freeswitch@internal

root@FREESWITCH1:# cat /tmp/3337e053-077c-4f39-9c3f-0805c4896851.tmp.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="freeswitch/xml">
<section name="result"><result status="not found" />
</document>


Conclusion


So, now we see how simple it is to pull configurations from Database - for a practice try this all with Conferences

Wednesday, August 21, 2013

RTPproxy Revisited [Kamailio 4.0]

Time and again I see people getting stuck on RTPproxy integration with Kamailio. I recently got another opportunity to put RTPproxy in between the User Phones and Kamailio setup as depicted in the following diagram.



That is similar to what I've posted earlier on this topic. In this post I will try be more verbose and write each and every step I did to have RTPs flowing.

I assume you've a Kamailio installed and working and configurations file from Asipto Knowledge Base by Daniel and that there are TWO NICs configured with Public IP and Private IP as shown in the diagram above.

The important thing which I'm looking for from the configuration is the WITH_NAT tag. follow the code and see how the NAT is handled. route[NATMANAGE] is called at almost all important routes.

The overall idea is;

1- Install RTPproxy
2- Start RTPproxy in Bridged mode
3- Make Kamailio aware of multiple NICs
4- Add Private IP asterisks in dispatcher
5- Create a new route RTPPROXY to engage RTP-proxy whenever needed
6- Call in the RTPPROXY route in the NATMANAGE route.
7- Important Things to take care of.

So lets start following the steps.

1- Installing RTPproxy

root@Kamailio:~# cd /usr/src/
root@Kamailio:~# wget http://b2bua.org/chrome/site/rtpproxy-1.2.1.tar.gz
root@Kamailio:~# tar zxvf rtpproxy-1.2.1.tar.gz
root@Kamailio:~# cd rtpproxy-1.2.1/
root@Kamailio:~# ./configure
root@Kamailio:~# make
root@Kamailio:~# make install

Setup LSB script for RTP-proxy
root@Kamailio:~# cp debian/rtpproxy-default.ex /etc/default/rtpproxy
edit the default file and put in the parameters.
root@Kamailio:~# vim /etc/default/rtpproxy

2- Start RTPproxy in Bridged mode


DAEMON_OPTS="-F -s udp:127.0.0.1:7722 -l 77.66.55.44/192.168.1.244 -d DBUG:LOG_LOCAL0 -u root"

Save and Exit

root@Kamailio:~# cp debian/rtpproxy.init /etc/init.d/rtpproxy
root@Kamailio:~# chmod a+x /etc/init.d/rtpproxy

Open up the file

root@Kamailio:~# vim /etc/init.d/rtpproxy

see that the DAEMON field points to the file in /usr/bin/rtpproxy

DAEMON=/usr/bin/rtpproxy

Lets copy the RTPproxy binary to that location.

root@Kamailio:~# cp rtpproxy /usr/bin/rtpproxy

Start up RTPproxy

root@Kamailio:~# /etc/init.d/rtpproxy start

verify that rtpproxy is running and listening on the specified 7722 

root@Kamailio:~# netstat -pln | grep rtpp
udp        0      0 127.0.0.1:7722          0.0.0.0:*                           6554/rtpproxy
Thats all.

3- Making Kamailio aware of multiple NICs


Lets move on to step 3 involving Kamailio configurations.

root@Kamailio:~# vim /usr/local/etc/kamailio/kamailio.cfg

Insert the following line in global parameters section, just under where we define "listen=" or "port=" 

mhomed=1

That will ensure that Kamailio uses its Private IP to communicate with Asterisks on Private subnet. Don't forget this.

We also need to put this line on the top definitions of kamailio.cfg file so kamailio use the NAT functions.

#!define WITH_NAT

4- Adding Asterisks to dispatcher


Now Add Private IP asterisks in dispatcher: Follow my post on adding dispatcher to the plain configurations from here: http://saevolgo.blogspot.com/2011/11/how-to-increasing-voip-services.html

5- Writing some Kamailio routing logic for RTPPROXY

That was easy, now the real thing the addition of RTPPROXY route which I modified a little bit from the last link mentioned.

To have the code working I have used the SQLOPS module configured to query kamailio.dispatcher table as the AVPOPS module was already busy.

NOTE: Using the DB query is a costly operation BUT it allows me to detect if Kamailio is sending call to Dispatcher listed IPs or not. I have a mix of Asterisks on Private Subnet and on Public Subnet and if the Asterisk dispatcher has chosen or the call is coming from is a Private IP then engage RTPproxy. This detection is handled by IPOPS module and its function is_ip_rfc1918()

loadmodule "ipops.so"
loadmodule "sqlops.so"
modparam("sqlops","sqlcon","ca=>mysql://openser:openserrw@localhost/kamailio")

Then declare the route:

# RTPProxy control
route[RTPPROXY] {
        if (is_method("INVITE")){
                sql_query("ca", "select destination from dispatcher where destination like '%$dd%'","ra");
                if($dbr(ra=>rows)>0){
                        $avp(duip)=$(du{s.select,-2,:});
                        if (is_ip_rfc1918("$avp(duip)")) {
                                xlog("L_INFO", "Call is going to private IPv4 Media Server Engage RTPProxy Now\n");
                                #rtpproxy_manage("crwie","192.168.1.244");
                                rtpproxy_manage("rwie");
                        }

                }
                else if(ds_is_from_list()){
                        if (is_ip_rfc1918("$si")) {
                                xlog("L_INFO", " Call is coming from a private IPv4 Media Server Engage RTPProxy Now\n");
                                #rtpproxy_manage("crwei","77.66.55.44");
                                rtpproxy_manage("rwei");

                        }
                }else if(!ds_is_from_list()){
                          rtpproxy_manage("rwie");

                }
      }
}

6- Using RTPPROXY route

Add the RTPPROXY route just where the FLT_NATS and FLB_NATB flags are tested.

        if (!(isflagset(FLT_NATS) || isbflagset(FLB_NATB))){
                return;
        }
                route(RTPPROXY);


Now Save and Exit the kamailio.cfg file.

Restart Kamailio.

root@Kamailio:~# /etc/init.d/kamailio stop
root@Kamailio:~# /etc/init.d/kamailio start

7- Helpful Things to know

Asterisk needs to have the peer declared for kamailio using its Private IP.

[Kamailio]
type=friend
host=192.168.1.244
port=5060
disallow=all
allow=gsm
allow=g729
allow=alaw
allow=ulaw
context=SBC-Incoming
canreinvite=no
insecure=port,invite
nat=force_rport,comedia
qualify=yes
directrtpsetup=no

See that I've used "directrtpsetup=no" so that Asterisk don't decide to go direct with the End caller.

Use xlog lines in kamailio.cfg file to follow the call.

The way I always setup my whole environment is that Kamailio handles the REGISTRATIONs and only INVITES are load-balanced to Asterisks or FreeSWITCHes where they receive the call from Kamailio peer and execute dialplan applications and IF call needs to dial out they dial the destination back to kamailio.
Kamailio needs to detect the call coming FROM the Media-Servers (ds_is_from_list() function)

So I know when a user calls in and when the call comes in from the media-servers.

Always try to first have an echo test working for calls. I use Asterisk application Echo() and when I dial in from user I get my own audio echoed back and I know that atleast my audio path is complete. This never tells you that your setup is 100% perfect but it is a good way to know if you're headed right direction.


Wireshark is a great Friend. Use it to examine everything in depth. No matter what I do I always need Wireshark to visually see what is going on with the SIP packets, that gives me everything I need to know to make things right.

root@Kamailio200:~# tcpdump -i any -s 0 -w rtp-calls.pcap -vvv
tcpdump: listening on any, link-type LINUX_SLL (Linux cooked), capture size 65535 bytes
1666 packets captured
Download this "rtp-calls.pcap" file and open it up in Wireshark. Click "Telephony"  from the menu bar and select "VoIP Calls"


Hit the Flow button and you'll see beautiful arrows showing the direction of SIP and RTP packets.


On the very Left Hand side is my Soft Phone's Public IP address, then 77.66.55.44 is kamailio's WAN side, and suddenly we see 192.168.1.244 which is Private IP of Kamailio communicating with an Asterisk on 192.168.1.36
The Bold arrows labeled RTP are flowing in both direction means all Perfect.

Thats all for one day. Hope to have some comments and questions on this soon.

Sunday, July 28, 2013

Linux IPSec VPN-2: Amazon Cloud Sever & Linksys Router

This is a post in response to a comment made earlier on my previous blog post on Linux IPSec Setup asking for assistance. So here's what I could possibly do to help the needy.

This is a setup which I assisted one of my friend in creating a VPN between a Static IP Linksys Router and an Amazon cloud based server. Since we all know that Amazon cloud servers don't actually have a static public IP assigned to them instead they've a One-to-One NAT mechanism at the best so this becomes a bit trickier for anyone new to the OpenSWAN or IPSec in Linuxes.

Regardless of the Operating System the openswan package needs to be installed on the server properly. Please refer to other blogs or Google in order to install ipsec service. See this references in this link:

The topology we'll be working on is defined in the diagram below.


Now get to the configurations.

The ipsec.conf file contains these:

config setup
        interfaces=%defaultroute
        klipsdebug=all
        plutodebug=all
        protostack=netkey
        nat_traversal=yes
conn Linksys
        type=tunnel
        left=10.2.147.164
        leftnexthop=%defaultroute
        leftsubnet=10.2.147.164/26
        right=120.121.122.123
        rightnexthop=%defaultroute
        rightsubnet=192.168.4.0/24
        auth=esp
        keyexchange=ike
        authby=secret
        pfs=yes
        auto=start

And ipsec.secrets contains this:

10.2.147.164 120.121.122.123 : PSK  "y0ur_S3cret_PSK_k3y"

Lets quickly get to the Linksys router and adjust the router according to the following settings.

Move to the VPN tab after logging in to the Linksys router.




Save the settings and restart vpn on both ends. Your VPN should start rocking by now. Ping from the 192.168.4.0/24 LAN to the Amazon IPSec Server's Private IP and it should be replying.

Please always read logs on both the router and the linux server very carefully and figure out what they are trying to communicate. Without any logs I probably would never had created this VPN.

I hope it be of some help to someone. Have a great day.

Wednesday, July 24, 2013

NIC Bonding in CentOS 6.4,Ubuntu 12.04, and Vyatta 6.6

Its late night here and unexpectedly I'm high on motivation to do something except working hence just shifting my procrastination energy into writing this blog.

I've previously blogged a post on setting up an Active/Passive HA setup for Linux servers, so this on is one step further into one server. By one step further into the server I mean to have some form of High Availability on Network Interfaces.

Link Aggregation, NIC Bonding, NIC teaming, Interface Bonding are various names it is known as. Read some basics on it visit this wikipedia link.

My basic motivation for creating NIC Bonding on my servers was to create a self healing topology in which a single cable or interface failure do not impact any service at all. Since I've redundant powers, servers, switches, and routers setup from my very own hands so I know how this will add up in my setup. Removing one cable from the server keeps the server accessible and hence all services working perfectly fine.

The additional benefit which I can benefit from NIC bonding is link "Aggregation". The two 1Gbps interface will and can combine to give me an aggregated speed of 2Gbps. That is something I still need to test and probably post my findings on its reality sometime by transferring huge chunks of data.

WARNING: I had to reboot one of my server as I had an interface already configured so a service restart didn't work properly and the same IP remained configured on eth0 and bond0 and hence caused temporary access issue. Just to be sure have a KVM/ILOM remote access ready while doing this setup.

Lets move forward.

Creating NIC Bond interface on CentOS 6.4

[root@ASTERISK-A ~]# vim /etc/sysconfig/network-scripts/ifcfg-bond0

and insert the following fairly simple to understand lines.

DEVICE=bond0
IPADDR=192.168.15.10
NETMASK=255.255.255.0
GATEWAY=192.168.15.45
USERCTL=no
BOOTPROTO=none
ONBOOT=yes
DNS1=192.168.15.45

Now remember, we need to have atleast two NIC present on the server to be part of the bond. This could be three Gig Interfaces if you've them available in order to achieve a 3Gbps link.

Edit the Interfaces going to be part of this bond.

[root@ASTERISK-A ~]# vim /etc/sysconfig/network-scripts/ifcfg-eth0

DEVICE=eth0
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes

[root@ASTERISK-A ~]# vim /etc/sysconfig/network-scripts/ifcfg-eth1

DEVICE=eth1
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
USERCTL=no
MASTER=bond0
SLAVE=yes

Now its time to setup some parameters for the 007-Bond Interface.

[root@ASTERISK-A ~]# vim /etc/modprobe.d/bonding.conf

Write the lines below in the file,save and exit.
alias bond0 bonding
options bond0 mode=1 miimon=100 arp_interval=100 arp_ip_target=192.168.15.45,192.168.15.5,192.168.15.20


The above configuration is used by the "bonding" Linux kernel module. The options are important here:

mode=1 : Set the bonding method to Active backup. 
miimon=100 : Set the MII link monitoring frequency to 100 milliseconds. This determines how often the link state of each slave is inspected for link failures.
arp_interval=100 : Set the ARP link monitoring frequency to 100 milliseconds (You can setup any keeping your network equipment in mind). This is important to be there.
arp_ip_target=192.168.15.45, 192.168.15.5 : Use the 192.168.15.5 (router ip) and 192.168.15.45 IP addresses to use as ARP monitoring peers when arp_interval is > 0. This is used determine the health of the link to the targets. Multiple IP addresses must be separated by a comma. At least one IP address must be given (usually I set it to router IP) for ARP monitoring to function. The maximum number of targets that can be specified is 16.

Thats all. Just restart the networking service and if you've any ethernet interface configured then you might need to shutdown that interface and start the network service again.

[root@ASTERISK-A ~]# /etc/init.d/network restart

Creating NIC Bond interface on Ubuntu 12.04

On Ubuntu Server the steps for configuring are 90% the same except that we need to install the package which gets the bonding kernel module.

root@OpenSIPS-A:~# apt-get install ifenslave

We just need to edit one file here.

root@OpenSIPS-A:~# vim /etc/network/interfaces

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual
        bond-master bond0

auto eth1
iface eth1 inet manual
        bond-master bond0

auto bond0
iface bond0 inet static
mtu 9000
        address 192.168.15.30
        netmask 255.255.255.0
        network 192.168.15.0
        broadcast 192.168.15.255
        gateway 192.168.15.45
        dns-nameservers 192.168.15.45
        bond-miimon 100
        bond-downdelay 200
        bond-updelay 200
        bond-mode active-backup
        bond-slaves none

To make sure that the bonding kernel module is loaded on reboots edit the file /etc/modules
add the word "bonding" at the end save, and exit. To Load bonding module right away execute the following command:

root@OpenSIPS-A:~# modprobe bonding

Now restart the networking service and bond0 interface should be up and ready. 

root@OpenSIPS-A:~# /etc/init.d/networking restart

             Creating NIC Bond interface on Vyatta 6.6

Vyatta is one of my favorite subject, huge thanks to Mr. Asim Ansari who introduced me to it back in 2010 and I've been using it and loving it ever since. There are other cool stuff Vyatta is doing for me which I'll cover later on. Lets see how to create a Bond Interface on Vyatta.

vyatta@FW-A:~$ configure
vyatta@FW-A# set interfaces bonding bond0 address 192.168.15.45/24
vyatta@FW-A# set interfaces bonding bond0 arp-monitor interval 100
vyatta@FW-A# set interfaces bonding bond0 mode adaptive-load-balance
vyatta@FW-A# set interfaces bonding bond0 mtu 9000
vyatta@FW-A# set interfaces ethernet eth0 bond-group bond0
vyatta@FW-A# set interfaces ethernet eth1 bond-group bond0
vyatta@FW-A# commit
vyatta@FW-A# save


WARNING: Once again ensure that the eth0 and eth1 are not assigned with IP address already, if so please delete them before assigning that ethX interface to bond-group. 

Thats all for tonight, I'm sleepy now and should take rest while you guys enjoy having good time with your servers and setups.

Recommended Articles: