Showing posts with label Asterisk. Show all posts
Showing posts with label Asterisk. Show all posts

Tuesday, December 6, 2011

Freeswitch + mod_skypiax + asterisk on CentOS 5.3

Howto: Freeswitch + mod_skypiax + asterisk on CentOS 5.3
This post describes the experience of installing and configuring skype gateway under CentOS 5.3 with the use of PBX FreeSwitch and external connection to Asterisk.
 When writing, the materials listed at the end of fasting.

Description of actions undertaken

  1. SELinux Installed CENTOS 5.3 + KDE with disabled Firewall and SELinux
  2. Updated packages
  3. Wound up SKYPE user someuser

Installing SKYPE-client

  1. Create a file / etc / yum.repos.d / skype.repo and make it
    [Skype]
    name=Skype Repository name = Skype Repository
    baseurl = http://download.skype.com/linux/repos/fedora/updates/i586/
    gpgkey = file: / / / etc / pki / rpm-gpg / RPM-GPG-KEY-skype
  2. qt4-x11 . At rpm.pbone.net looking for, download and install packages qt4, qt4-x11. I used qt4-4.4.3-1.fc8.i386.rpm and qt4-x11-4.4.3-1.fc8.i386.rpm respectively
    rpm -ivh qt4-4.4.3-1.fc8.i386.rpm qt4-x11-4.4.3-1.fc8.i386.rpm
  3. yum --nogpgcheck install skype
  4. yum install x11vnc

Installing FREESWITCH and mod_skypiax

  1. as root execute:
    yum update -y
    yum install -y subversion autoconf automake libtool gcc-c++ ncurses-devel make libX11-devel Xvfb alsa-utils xorg-x11-fonts*
    cd /usr/src
  2. svn co http://svn.freeswitch.org/svn/freeswitch/t svn co http://svn.freeswitch.org/svn/freeswitch/t runk freeswitch runk freeswitch
    cd freeswitch cd freeswitch
    # ---- HUMAN build / modules.conf.in, remove comment from mod_sofia and mod_skypiax, save ...
    ./bootstrap.sh .
    ./configure
    make && make install && make hd-sounds-install && make hd-moh-install && make samples
  3. Copy the config mod_skypiax and init-script to run FreeSwitch:
    cp /usr/src/freeswitch/src/mod/endpoints/mo cp / usr / src / freeswitch / src / mod / endpoints / mo d_skypiax/configs/skypiax.conf.xml \ d_skypiax / configs / skypiax.conf.xml \
    /usr/local/freeswitch/conf/autoload_conf / Usr / local / freeswitch / conf / autoload_conf igs/ igs /
    cp /usr/src/freeswitch/debian/freeswitch.in cp / usr / src / freeswitch / debian / freeswitch.in it /etc/init.d/freeswitch it / etc / init.d / freeswitch
    sed -i 's/opt/usr\/local/g' /etc/init.d/freeswitch sed-i 's / opt / usr \ / local / g' / etc / init.d / freeswitch
  4. Создаем пользователей и группы Create users and groups
    adduser --home /usr/local/freeswitch -g daemon freeswitch adduser - home / usr / local / freeswitch-g daemon freeswitch
    chown -R freeswitch.daemon /usr/local/freeswitch chown-R freeswitch.daemon / usr / local / freeswitch
    groupadd audio groupadd audio
  5. Заводим пользователя, под которым будет работать Skype: Set up user that will operate Skype:
    adduser --home /home/skype -g audio skype adduser - home / home / skype-g audio skype
  6. Создаем директорию, из которой Skype будет читать свой конфиг: Create a directory from which Skype will read your configuration:
    mkdir -p /home/skype/multi/interface01 mkdir-p / home/skype/multi/interface01
    chown -R skype.audio /home/skype/multi chown-R skype.audio / home / skype / multi

Starting and Configuring SKYPE

  1. Запускаем звуковые модули Start the Sound Modules
    rmmod snd-dummy rmmod snd-dummy
    modprobe snd-dummy modprobe snd-dummy
  2. Запуск окна, где будет запущен скайп Starting window, where it will be launched Skype
    /usr/bin/Xvfb :101 -ac & / Usr / bin / Xvfb: 101-ac &
  3. Запуск скайпа в отдельном окне Running Skype in a separate window
    DISPLAY=:101 /usr/bin/skype --dbpath=/home/skype/multi/interface01 & DISPLAY =: 101 / usr / bin / skype - dbpath = / home/skype/multi/interface01 &
  4. Для тестирования и настройки скайп-клиента запускаем vnc-сервер To test and configure Skype client run vnc-server
    x11vnc -display :101 x11vnc-display: 101
  5. Подключаемся с помощью vnc-клиента (VNC Viewer, например) удаленно к скайпу. Connecting with vnc-client (VNC Viewer, for example) remotely to Skype. Отключаем все события, уведомления. Disable all events and notifications.
  6. Пподключаем mod_skypiax к Public API. Ppodklyuchaem mod_skypiax to the Public API. Для этого нужно собрать и запустить спецальную утилиту из исходников freeswitch : To do this you need to build and run the utility from source spetsalnuyu freeswitch:
    cd /usr/src/freeswitch/src/mod/endpoints/mo cd / usr / src / freeswitch / src / mod / endpoints / mo d_skypiax/configs d_skypiax / configs
    gcc -Wall -ggdb skypiax_auth.c -o skypiax_auth -lX11 gcc-Wall-ggdb skypiax_auth.c-o skypiax_auth-lX11
    ./skypiax_auth :101 . / Skypiax_auth: 101
    Выскочит сообщение у скайпа "Программа хочет использовать Skype", cтавим скайпу галочку "запомнить выбор" Pop up a message from Skype "program wants to use Skype", ctavim Skype tick "remember choice"
  7. На этом настройка Skype-клиента завершена. In this setting Skype-client completed. Осталось только клонировать полученный конфиг для нужного количества Skype-каналов. What remains now is to clone the resulting configuration for the desired number of Skype-channels.
    cd /home/skype/multi cd / home / skype / multi
    for i in $(seq 2 N ); do i=$(printf "%02d" $i); cp -a interface01 interface$i; done for i in $ (seq 2 N); do i = $ (printf "% 02d" $ i); cp-a interface01 interface $ i; done
    где N — нужное количество Skype-каналов. where N - the right amount of Skype-channels.

Setting mod_skypiax

  1. Редактируем конфиг mod_skypiax для нужного количества каналов: Edit the configuration mod_skypiax for the desired number of channels:
    kedit /usr/local/freeswitch/conf/autoload_conf kedit / usr / local / freeswitch / conf / autoload_conf igs/skypiax.conf.xml igs / skypiax.conf.xml
    В параметрах: In parameters:
    • destination указываем экстеншн, куда будет перенаправляться соединение (к примеру - 8889) specify the destination extension, which will be redirected to the connection (for example - 8889)
    • X11-display указываем номер дисплея X-сервера, где запущен скайп-клиент X11-display screen indicates the number of X-server running the Skype client
    • skype_user указываем имя скайп-аккаунта skype_user specify the name Skype-account

  2. Запускаем FREESWITCH и загружаем mod_skypiax Starting FREESWITCH and load mod_skypiax
    /usr/local/freeswitch/bin/freeswitch / Usr / local / freeswitch / bin / freeswitch
    > console loglevel 9 # детализированный отчет > Console loglevel 9 # detailed report
    > load mod_skypiax # загрузка модуля > Load mod_skypiax # module loading
    > sk list # проверка загруженности модуля > Sk list # test load module
    > shutdown # выход > Shutdown # exit
  3. Добавляем mod_skypiax в список модулей, загружающихся во время старта FreeSwitch . Add to the list mod_skypiax modules to be loaded during start FreeSwitch. Для этого в файле /usr/local/freeswitch/conf/autoload_conf To do this in the file / usr / local / freeswitch / conf / autoload_conf igs/modules.conf.xml нужно раскоментировать/добавить строчку igs / modules.conf.xml need to uncomment / add the line
    <load module="mod_skypiax"/> <load module="mod_skypiax"/>
  4. Важным моментом является то, что skype-клиенты должны запускаться до загрузки модуля mod_skypiax , т.е. The important point is that the skype-client should be run before loading the module mod_skypiax, ie перед стартом FreeSwitch . before the start FreeSwitch. Также, остановка уже задействованных mod_skypiax копий Skype приведет к падению FreeSwitch . Also, stop already involved mod_skypiax copies of Skype will lead to a fall FreeSwitch.
  5. Добавляем обработчик для перенаправляемого экстеншена (8889). Add a handler for the redirected Extension (8889).
    В директории /usr/local/freeswitch/conf/dialplan/defa In the directory / usr / local / freeswitch / conf / dialplan / defa ult создаем файл 02_skype.xml следующего содержания: ult create a file 02_skype.xml read:
    <include> <include>
    <extension name="skype_incoming"> <extension name="skype_incoming">
    <condition field="destination_number" expression="^8889$"> <condition field="destination_number" expression="^8889$">
    <action application="set" data="hangup_after_bridge=true"/> <action application="set" data="hangup_after_bridge=true"/>
    <action application="set" data="effective_caller_id_name=Skype"/> <action application="set" data="effective_caller_id_name=Skype"/>
    <action application="bridge" data="sofia/gateway/asterisk/351"/> <action application="bridge" data="sofia/gateway/asterisk/351"/>
    <action application="hangup"/> <action application="hangup"/>
    </condition> </ Condition>
    </extension> </ Extension>
    </include> </ Include>
    В поле <action application="bridge"...> указан экстеншен который будет обрабатываться в asterisk при поступлении вызова, в моем примере это будет экстеншн 351 . In the <action application="bridge"...> specified Extension will be processed in asterisk when a call comes in, in my example it would be extension 351.
    В этом же каталоге находятся примеры других экстеншенов, которые нужно будет закоментировать, что бы нужный нам экстеншен не обрабатывался в другом месте. In the same directory are examples of other extensions that need to be commented out, what would you want us to Extension not to be processed elsewhere. Ту же операцию нужно проделать и в файле /usr/local/freeswitch/conf/dialplan/defa The same procedure should be done in the file / usr / local / freeswitch / conf / dialplan / defa ult.xml ult.xml

Configuring SIP-trunk between Asterisk and FreeSwitch

  1. На сервере c FreeSwitch в директории /usr/local/freeswitch/conf/sip_profiles/e On the server c FreeSwitch in the directory / usr / local / freeswitch / conf / sip_profiles / e xternal создаем файл asterisk.xml следующего содержания: xternal create a file asterisk.xml read:
    <include> <include>
    <gateway name="asterisk"> <gateway name="asterisk">
    <param name="username" value="8889"/> <param name="username" value="8889"/>
    <param name="realm" value="asterisk.example.tld"/> <param name="realm" value="asterisk.example.tld"/>
    <param name="password" value="******"/> <param name="password" value="******"/>
    <param name="register" value="false"/> <param name="register" value="false"/>
    </gateway> </ Gateway>
    </include> </ Include>
    где where
    asterisk — имя шлюза (должно совпадать с указанным в предыдущем шаге); asterisk - the name of the gateway (this should coincide with that in the previous step);
    asterisk.example.tld — имя хоста или IP адрес сервера Asterisk ; asterisk.example.tld - host name or IP address of the server Asterisk;
    8889 — имя пользователя для доступа к серверу Asterisk ; 8889 - The user name to access the server Asterisk;
    ******* — пароль. ******* - Password.
    На сервере Asterisk добавляем в sip.conf следующее: On the server, add to the Asterisk sip.conf as follows:
    [freeswitch] [Freeswitch]
    type=peer type = peer
    host=1.1.1.1 host = 1.1.1.1
    username=8889 username = 8889
    port=5080 port = 5080
    fromdomain=1.1.1.1 fromdomain = 1.1.1.1
    secret=****** secret =******
    Перезагружаем Asterisk Restart Asterisk
    asterisk -x 'sip reload' asterisk-x 'sip reload'

Calls to Skype

  1. Сначала в файле sip.conf в Asterisk создаем пользователя (или несколько пользователей) под которым в FS будет принимать входящие вызовы. First, in the file sip.conf in Asterisk create a user (or multiple users), under which in the FS will accept incoming calls. В качестве примера пусть будет 8890 . As an example, let it be 8890. При наборе этого номера на SIP-телефоне звонок будет переадресовываться на сервер FS и коммутироваться на нужного нам skype-пользователя. When dialing this number on the SIP-phone call will be forwarded to the server FS and commute on the right we skype-user. Если хотим, что бы Asteisk обрабатывал DTMF сигналы, то прописываем дополнительно параметр dtmfmode=inband. FS когда совершает BRIDGE If you want, what would Asteisk handles DTMF signals, then prescribe additional parameter dtmfmode = inband. FS when committing BRIDGE   двух каналов режет out-of-band dtmf-сигналы, пропуская только inband и нужно, что бы Asterisk обрабатывал inband сигналы. two channels cut out-of-band dtmf-tones, letting through only inband and need that would Asterisk handles inband signals. По умолчанию Asterisk обрабатывает out-of-band. By default, Asterisk handles out-of-band.
  2. В конфиг-файле /freeswitch/conf/autoload_configs/acl.co In the configuration file / freeswitch / conf / autoload_configs / acl.co nf.xml нужно разрешить входящие вызовы с сервера Asterisk, для чего в блоке domains добавляем строку <node type="allow" cidr="xxx.xxx.xxx.xxx/32"/> , где xxx.xxx.xxx.xxx - IP адрес сервера Asterisk nf.xml need to allow incoming calls from the server, Asterisk, for which the block domains to add the line <node type="allow" cidr="xxx.xxx.xxx.xxx/32"/>, where xxx.xxx.xxx.xxx - IP address of Asterisk
  3. В каталоге /freeswitch/conf/sip_profiles/internal/ создаем файл asterisk.xml с описанием параметров подключения к asterisk: In the directory / freeswitch / conf / sip_profiles / internal / create a file asterisk.xml describing the parameters to connect to asterisk:
    <include> <include>
    <gateway name="asterisk_in"> <gateway name="asterisk_in">
    <param name="username" value=" 8890 "/> <param name="username" value=" 8890 "/>
    <param name="realm" value=" xxx.xxx.xxx.xxx "/> <param name="realm" value=" xxx.xxx.xxx.xxx "/>
    <param name="password" value=" password_for_8890 "/> <param name="password" value=" password_for_8890 "/>
    <param name="register" value="true"/> <param name="register" value="true"/>
    <param name="retry-seconds" value="30"/> <param name="retry-seconds" value="30"/>
    <param name="ping" value="25"/> <param name="ping" value="25"/>
    </gateway> </ Gateway>
    </include> </ Include>
    где username - имя юзера, password - пароль для юзера, realm - IP адрес сервера Asterisk where username - user name, password - password for the user, realm - IP address of the Asterisk
  4. В каталоге /freeswitch/conf/dialplan/public/ создаем файл 02_skype.xml в котором описываем правила перенаправления поступающих вызовов на Skype-абонентов. In the directory / freeswitch / conf / dialplan / public / 02_skype.xml create a file which describes the rules for redirecting incoming calls to a Skype-subscribers. В простом случае это будет выглядеть примерно так: In the simplest case, it will look like this: <include> <include>
    <extension name="skype_someuser"> <extension name="skype_someuser">
    <condition field="destination_number" expression="^8890$"> <condition field="destination_number" expression="^8890$">
    <action application="bridge" data="skypiax/ANY/ someuser "/> <action application="bridge" data="skypiax/ANY/ someuser "/>
    </condition> </ Condition>
    </extension> </ Extension>
    </include> </ Include>
    где в поле <action...> вместо someuser указывается skype-аккаунт нужного нам пользователя where in the field instead <action...> someuser indicated skype-account you want us to User

Sources:

  1. http://habrahabr.ru/blogs/voip/68399/
  2. http://wiki.freeswitch.org/wiki/Skypiax # A n_example_of_Skypiax_and_FreeSWITCH_inst n_example_of_Skypiax_and_FreeSWITCH_inst allation_on_CentOS.2C_from_scratch allation_on_CentOS.2C_from_scratch
  3. http://fedorasolved.org/multimedia-solut ions/installing-skype ions / installing-skype

Using the Asterisk Database (AstDB)

Using the Asterisk Database (AstDB)

Having fun yet? It gets even better!
Asterisk provides a powerful mechanism for storing values called the Asterisk database (AstDB). The AstDB provides a simple way to store data for use within your dialplan.

Tip

For those of you with experience using relational databases such as PostgreSQL or MySQL, the Asterisk database is not a traditional relational database. It is a Berkeley DB Version 1 database. There are several ways to store data from Asterisk in a relational database. Check out Chapter 12, Relational Database Integration for a more about relational databases.
The Asterisk database stores its data in groupings called families, with values identified by keys. Within a family, a key may be used only once. For example, if we had a family called test, we could store only one value with a key called count. Each stored value must be associated with a family.

Storing Data in the AstDB

To store a new value in the Asterisk database, we use the Set() application,[85] but instead of using it to set a channel variable, we use it to set an AstDB variable. For example, to assign the count key in the test family with the value of 1, write the following:
exten => 456,1,Set(DB(test/count)=1)If a key named count already exists in the test family, its value will be overwritten with the new value. You can also store values from the Asterisk command line, by running the command database put family key value. For our example, you would type database put test count 1.

Retrieving Data from the AstDB

To retrieve a value from the Asterisk database and assign it to a variable, we use the Set() application again. Let’s retrieve the value of count (again, from the test family), assign it to a variable called COUNT, and then speak the value to the caller:
exten => 456,1,Set(DB(test/count)=1)
exten => 456,n,Set(COUNT=${DB(test/count)})
exten => 456,n,SayNumber(${COUNT})
You may also check the value of a given key from the Asterisk command line by running the command database get family key. To view the entire contents of the AstDB, use the database show command.

Deleting Data from the AstDB

There are two ways to delete data from the Asterisk database. To delete a key, you can use the DB_DELETE() application. It takes the path to the key as its arguments, like this:
; deletes the key and returns its value in one step
exten => 457,1,Verbose(0, The value was ${DB_DELETE(test/count)})
You can also delete an entire key family by using the DBdeltree() application. The DBdeltree() application takes a single argument―the name of the key family―to delete. To delete the entire test family, do the following:
exten => 457,1,DBdeltree(test)To delete keys and key families from the AstDB via the command-line interface, use the database del key and database deltree family commands, respectively.

Using the AstDB in the Dialplan

There are an infinite number of ways to use the Asterisk database in a dialplan. To introduce the AstDB, we’ll show two simple examples. The first is a simple counting example to show that the Asterisk database is persistent (meaning that it survives system reboots). In the second example, we’ll use the BLACKLIST() function to evaluate whether or not a number is on the blacklist and should be blocked.
To begin the counting example, let’s first retrieve a number (the value of the count key) from the database and assign it to a variable named COUNT. If the key doesn’t exist, DB() will return NULL (no value). In order to verify if a value exists in the database or not, we will introduce the ISNULL() function that will verify whether a value was returned, and if not, we will initialize the AstDB with the Set() application, where we will set the value in the database to 1. The next priority will send us back to priority 1. This will happen the very first time we dial this extension:
exten => 678,1,Set(COUNT=${DB(test/count)})
exten => 678,n,GotoIf($[${ISNULL(${COUNT})}]?:continue)
exten => 678,n,Set(DB(test/count)=1)
exten => 678,n,Goto(1)
exten => 678,n(continue),NoOp()
Next, we’ll say the current value of COUNT, and then increment COUNT:
exten => 678,1,Set(COUNT=${DB(test/count)})
exten => 678,n,GotoIf($[${ISNULL(${COUNT})}]?:continue)
exten => 678,n,Set(DB(test/count)=1)
exten => 678,n,Goto(1)
exten => 678,n(continue),NoOp()
exten => 678,n,SayNumber(${COUNT})
exten => 678,n,Set(COUNT=$[${COUNT} + 1])
Now that we’ve incremented COUNT, let’s put the new value back into the database. Remember that storing a value for an existing key overwrites the previous value:
exten => 678,1,Set(COUNT=${DB(test/count)})
exten => 678,n,GotoIf($[${ISNULL(${COUNT})}]?:continue)
exten => 678,n,Set(DB(test/count)=1)
exten => 678,n,Goto(1)
exten => 678,n(continue),NoOp()
exten => 678,n,SayNumber(${COUNT})
exten => 678,n,Set(COUNT=$[${COUNT} + 1])
exten => 678,n,Set(DB(test/count)=${COUNT})
Finally, we’ll loop back to the first priority. This way, the application will continue counting:
exten => 678,1,Set(COUNT=${DB(test/count)})
exten => 678,n,GotoIf($[${ISNULL(${COUNT})}]?:continue)
exten => 678,n,Set(DB(test/count)=1)
exten => 678,n,Goto(1)
exten => 678,n(continue),NoOp()
exten => 678,n,SayNumber(${COUNT})
exten => 678,n,Set(COUNT=$[${COUNT} + 1]
exten => 678,n,Set(DB(test/count)=${COUNT})
exten => 678,n,Goto(1)
Go ahead and try this example. Listen to it count for a while, and then hang up. When you dial this extension again, it should continue counting from where it left off. The value stored in the database will be persistent, even across a restart of Asterisk.
In the next example, we’ll create dialplan logic around the BLACKLIST() function, which checks to see if the current Caller ID number exists in the blacklist. (The blacklist is simply a family called blacklist in the AstDB.) If BLACKLIST() finds the number in the blacklist, it returns the value 1, otherwise it will return 0. We can use these values in combination with a GotoIf() to control whether the call will execute the Dial() application:
exten => 124,1,GotoIf($[${BLACKLIST()]?blocked,1)
exten => 124,n,Dial(${JOHN})

exten => blocked,1,Playback(privacy-you-are-blacklisted)
exten => blocked,n,Playback(vm-goodbye)
exten => blocked,n,Hangup()
To add a number to the blacklist, run the database put blacklist number 1 command from the Asterisk command-line interface.

How to build an Asterisk Cluster

How to build an Asterisk Cluster


Intuit is conducting a first online-workshop via WebEx about building a Asterisk-Cluster.
This first workshop focuses on a Active-Passive setup.
(The next workshop will cover a large Active-Active setup with multiple Asterisk, DB and Load Balance servers.)

Details:

Date/Time: Friday, 20. May 2009 at 8 AM, GMT +8 (Kuala Lumpur Time... )
Duration: 2 hours (depends on how many questions we have..)
Topics covered:
- How to choose your hardware (Servers and PSTN equipment, we will use a FoneBridge from Redfone)
- How to prepare your OS for cluster (we use Debian 5 in the workshop)
- Asterisk standard vanilla installation (we will use our install script)
- Explain the concept of DRBD and Heartbeat
- Configure DRBD and Heartbeat
- Test the cluster
- Discussion
Cost: FOC (you can buy me a beer if you are in Kuala Lumpur)
Please e-mail me or Marco if you want to join the seminar and we will send you the meeting-invite!
Marco: marco@intuitinnovations.com
Daniel: daniel@intuitinnovations.com
Cheers
Daniel



Asterisk High Availability HOWTO with Heartbeat and Redfone fonebridge

Overview
The following is a brief HOWTO for installing High-Availability Asterisk using Open Source tools combined with fail-over capable & intelligent hardware (the fonebridge).
The heartbeat utility is used in a 'Passive-Active' scenario but could easily be modified to do 'Active-Active'.

Background
Some of our more demanding customers in the Call Center and Banking Industry are loathe to accept an implementation with no mechanism for fail-over and high-availability so this is the hardware/software combination we are using to meet their demands.

Client Background
The following scenario was used for a medium sized call center operation with about 60 analog stations, and a single T1 PRI.

Hardware
  • 2 x 1U Supermicro Servers (P4, 512Mb, Dual Gig Eth, Dual SATA with RAID 0)
  • 1 x Redfone Quad T1 fonebridge to terminate PRI connectivity, power channel banks and provide fail-over capability between the two Supermicros.
  • 1 x T1 PRI
  • 3 x Adtran 750 FXS channel banks to drive analog phones
  • 2 x UPS/Surge Protectors

Software
  • Fedora Core 4
  • Asterisk, zaptel, libpri from CVS head
  • Linux HA software suite from Ultramonkey. They have RPMs for RHE3 that install fine on Fedora Core 4
  • Each server is a mirror image of the other in terms of Asterisk configs and software.

Software Install
After a standard install of FC4, Asterisk, zaptel, libpri we installed all of the packages from Ultramonkey pretty much following their guidelines: http://www.ultramonkey.org/3/installation-rh.el.3.html
You may have a few dependencies issues, mainly perl libs, but we were able to satisfy all of them by using Yum. If you are running Apt you should be able to accomplish the same thing.

Configuring Hearbeat
After installing heartbeat there are only three files that need to be modified for your environment. They are ha.cf, haresources and authkeys. They should all be placed in the /etc/ha.d/ directory. The files should be absolutely identical on all machines that are part of your Asterisk high-availability cluster. We only have two servers running but you could easily scale to more using the exact same configurations. These are our config files. All comment lines have been removed but as you can see they are short and simple.

ha.cf
debugfile /var/log/ha-debug
logfile /var/log/ha-log
logfacility local0
keepalive 200ms
deadtime 2
warntime 1
initdead 120
udpport 694
bcast eth0
node asterisk1
node asterisk2

haresources
asterisk1 10.10.10.110 fonulator asterisk

authkeys
auth 1
1 sha1 SuPerS&cretP@$$werd

Operation
Each Asterisk server has a unique IP address which is part of the LAN segment. This could be a NATed network or Internet facing with public IP addresses. Heartbeat manages the monitoring of the hardware state of each machine over Ethernet or serial port or a combination of both (recommended) and assigns the Virtual IP to the Asterisk server which is currently in an active state. Example;

Asterisk1= 10.10.10.100
Asterisk2= 10.10.10.120
Virtual IP= 10.10.10.110 (see haresources)

With Heartbeat it is important that your node names are identical to the host names reflected in #uname -n. You also may need to manually add IP/hosts statements to your /etc/hosts file so each machine knows how to reach the other via IP.

Following the rules in haresources, Heartbeat will assign machine name asterisk1 as the primary server when both systems start up. It will then start the following scripts; fonulator (this is the little script that configures the fonebridge) and asterisk which starts the Asterisk server. These are both standard startup scripts placed in /etc/init.d/ .
If the Primary server suffers a hardware fault or simply stops responding to the heartbeats going between the two nodes asterisk2 will execute /etc/init.d/fonulator start to reconfigure the fonebridge on the fly and begin redirecting traffic to asterisk2 followed by /etc/init.d/asterisk start to start the Asterisk server.

Results
With heartbeat, IP takeover occurs in under a second. The fonulator utility re-configures the fonebridge in just about the same amount of time and then depending on your hardware platform and the complexity of apps running in Asterisk it can take between 5-15 seconds for Asterisk to start up on your secondary server, load all config files, clear alarms and be ready to process calls. Total fail-over time about 15-20 seconds.

Resources
Ultramonkey http://www.ultramonkey.org (High Avail software packages)
Linux HA http://www.linux-ha.org (The High Availability Linux Project)
Redfone http://www.red-fone.com (Maker of the Quad T1/E1 fonebridge)

How to do Load-Balancing for Asterisk with OpenSIPS

Bogdan-Andrei Iancu has posted information about how to do load balancing for SIP traffic:

When trying to cluster Asterisk boxes to gain scalability and more performance, there is now a new simple and efficient solution for doing it.

OpenSIPS/OpenSER 1.5 can now implement traffic routing based on load. Shortly, when OpenSIPS routes calls to a set of destinations, it is able to keep the load status (as number of ongoing calls) of each destination and to choose to route to the less loaded destination (at that moment). OpenSIPS is aware of the capacity of each destination - it is preconfigured with the maximum load accepted by the destinations.

This is an idea Load-Balancer to front your Asterisk cluster. A nice tutorial about how to do LB for your Asterisk is available:

http://www.opensips.org/index.php?n=Resources.DocsTutLoadbalancing

Asterisk File Locations

Asterisk File Locations

• /etc/asterisk/ - Asterisk configuration files

• /usr/lib/asterisk/modules/ - all loadable modules: codecs, channels,formats etc.

• /var/lib/asterisk/ - contains the astdb, sounds, images, firmware and keys

• /var/spool/asterisk/ - temporary files and voicemail files

• /var/run/ - contains the process ID (PID) for running processes,including Asterisk

• /var/log/asterisk/ - Asterisk log files

• /var/log/asterisk/cdr-csv/ - Asterisk call detail records

• /etc/zaptel.conf/  - low level configuration for the hardware interface

• /etc/asterisk/zapata.conf/ - configuration for Asterisk’s interface to the hardware

• /var/lib/asterisk/agi-bin/      -  AGI directory

• /etc/asterisk/meetme.conf/ - Configuration file for MeetMe simple conference rooms

Thursday, November 24, 2011

A2Billing 1.6.0 Stable install script

#!/bin/sh

DATETAG=`date +%Y%m%d%H%k%M%S`

echo "This is the Ubuntu A2Billing setup script"
echo ""

# Step1: Removing A2billing Old files

rm -f -R /var/www/html/a2billing/
rm -f -R /var/www/html/customer/
rm -f -R /var/lib/asterisk/agi-bin/a2billing.php
rm -f -R /var/lib/asterisk/agi-bin/libs_a2billing/
rm -f -R /var/lib/asterisk/agi-bin/lib/
rm -f -R /etc/asterisk/additional_a2billing_iax.conf
rm -f -R /etc/asterisk/additional_a2billing_sip.conf
rm -f /etc/asterisk/a2billing.conf
rm -f /etc/a2billing.conf
rm -f -R /var/www/html/agent/
rm -f -R /var/www/html/common/
rm -f -R /usr/src/a2billing/

# Drop the old database (if it exists)
mysqladmin drop mya2billing -u root -pxxxxx


# Step2: A2billing installation
cd /usr/src
mkdir a2billing
cd a2billing
wget http://www.asterisk2billing.org/downloads/A2Billing_1.6.0.tar.gz
tar -xzf A2Billing_1.6.0.tar.gz
chown -R root:root /usr/src/a2billing


mysql -u root -pxxxxx < /usr/src/a2billing/DataBase/mysql-5.x/a2billing-createdb-user.sql
mysql mya2billing -u root -pxxxxx < /usr/src/a2billing/DataBase/mysql-5.x/a2billing-schema-v1.4.0.sql

mysql mya2billing -u root -pxxxxx </usr/src/a2billing/DataBase/mysql-5.x/UPDATE-a2billing-v1.4.0-to-v1.4.1.sql
mysql mya2billing -u root -pxxxxx </usr/src/a2billing/DataBase/mysql-5.x/UPDATE-a2billing-v1.4.1-to-v1.4.2.sql
mysql mya2billing -u root -pxxxxx </usr/src/a2billing/DataBase/mysql-5.x/UPDATE-a2billing-v1.4.2-to-v1.4.3.sql
mysql mya2billing -u root -pxxxx </usr/src/a2billing/DataBase/mysql-5.x/UPDATE-a2billing-v1.4.3-to-v1.4.4.sql
mysql mya2billing -u root -pxxxxx </usr/src/a2billing/DataBase/mysql-5.x/UPDATE-a2billing-v1.4.4-to-v1.4.4.1.sql
mysql mya2billing -u root -pxxxxx </usr/src/a2billing/DataBase/mysql-5.x/UPDATE-a2billing-v1.4.4.1-to-v1.4.5.sql
mysql mya2billing -u root -pxxxxx </usr/src/a2billing/DataBase/mysql-5.x/UPDATE-a2billing-v1.4.5-to-v1.5.0.sql
mysql mya2billing -u root -pxxxxx </usr/src/a2billing/DataBase/mysql-5.x/UPDATE-a2billing-v1.5.0-to-v1.5.1.sql
mysql mya2billing -u root -pxxxxx </usr/src/a2billing/DataBase/mysql-5.x/UPDATE-a2billing-v1.5.1-to-v1.6.0.sql

# Step3: A2billing web interfaces installation

cp -rf /usr/src/a2billing/customer /var/www/html/a2customer
chmod 777 /var/www/html/a2customer/templates_c
cp -rf /usr/src/a2billing/agent /var/www/html
chmod 777 /var/www/html/agent/templates_c
cp -rf /usr/src/a2billing/admin /var/www/html/a2billing
chmod 777 /var/www/html/a2billing/templates_c
cp -Rf /usr/src/a2billing/common /var/www/html

cp /usr/src/a2billing/AGI/a2billing.php /var/lib/asterisk/agi-bin/
cp -rf /usr/src/a2billing/common/lib /var/lib/asterisk/agi-bin/
chmod +x /var/lib/asterisk/agi-bin/a2billing.php
chown -R asterisk:asterisk /var/lib/asterisk/agi-bin

# Step4: A2billing configuration files
cp /usr/src/a2billing/a2billing.conf /etc/asterisk
chown asterisk:asterisk /etc/asterisk/a2billing.conf
ln -sf /etc/asterisk/a2billing.conf /etc/a2billing.conf

sed -i "s/\(port *= *\)\(.*\)/\13306/" /etc/asterisk/a2billing.conf
sed -i "s/\(user *= *\)\(.*\)/\1a2billinguser/" /etc/asterisk/a2billing.conf
sed -i "s/\(password *= *\)\(.*\)/\1a2billing/" /etc/asterisk/a2billing.conf
sed -i "s/\(dbname *= *\)\(.*\)/\1mya2billing/" /etc/asterisk/a2billing.conf


mkdir -p /var/lib/asterisk/mohmp3/acc_1
mkdir -p /var/lib/asterisk/mohmp3/acc_2
mkdir -p /var/lib/asterisk/mohmp3/acc_3
mkdir -p /var/lib/asterisk/mohmp3/acc_4
mkdir -p /var/lib/asterisk/mohmp3/acc_5
mkdir -p /var/lib/asterisk/mohmp3/acc_6
mkdir -p /var/lib/asterisk/mohmp3/acc_7
mkdir -p /var/lib/asterisk/mohmp3/acc_8
mkdir -p /var/lib/asterisk/mohmp3/acc_9
mkdir -p /var/lib/asterisk/mohmp3/acc_10
chmod 777 /var/lib/asterisk/mohmp3/acc_*
chown -R asterisk:asterisk /var/lib/asterisk/mohmp3/

# A2billing Extra sounds
cd /usr/src/a2billing/addons/sounds
./install_a2b_sounds.sh

# Step6: Asterisk files
cd /etc/asterisk/
touch additional_a2billing_iax.conf
touch additional_a2billing_sip.conf
touch extensions_a2billing.conf

echo "#include additional_a2billing_sip.conf" >> /etc/asterisk/sip_custom.conf
echo "#include additional_a2billing_iax.conf" >> /etc/asterisk/iax_custom.conf
echo -e >> /etc/asterisk/extensions_custom.conf
echo "#include extensions_a2billing.conf" >> /etc/asterisk/extensions_custom.conf

# Step7: A2billing file permissions
chmod 666 /etc/asterisk/additional_a2billing_iax.conf
chmod 666 /etc/asterisk/additional_a2billing_sip.conf
chmod 666 /etc/asterisk/extensions_a2billing.conf
chown -R asterisk:asterisk /etc/asterisk/
chown -R asterisk:asterisk /var/www/html/common
chown -R asterisk:asterisk /var/www/html/a2billing
chown -R asterisk:asterisk /var/www/html/a2customer
chown -R root:root /var/www/agent
chown -R asterisk:asterisk /var/lib/asterisk/


# Cronjobs

echo "
# Automatically added for A2Billing
0 * * * * php /usr/src/a2billing/Cronjobs/a2billing_alarm.php
0 12 * * * php /usr/src/a2billing/Cronjobs/a2billing_archive_data_cront.php
0 10 21 * * php /usr/src/a2billing/Cronjobs/a2billing_autorefill.php     
#Batch process at 00:20 each day                                               
20 0 * * * php /usr/src/a2billing/Cronjobs/a2billing_batch_process.php   
#Bill DID usage at 00:00 each day                                              
0 0 * * * php /usr/src/a2billing/Cronjobs/a2billing_bill_diduse.php      
#Remind users of low balance every day at 06:00                                
0 6 * * * php /usr/src/a2billing/Cronjobs/a2billing_check_account.php    
#Generate Invoices at 7am everyday                                             
#0 7 * * * php /usr/src/a2billing/Cronjobs/a2billing_invoice2_cront.php   
#0 7 * * * php /usr/src/a2billing/Cronjobs/a2billing_invoice_cront.php    
#Check if balance below preset value, and email user if so.                    
1 * * * * php /usr/src/a2billing/Cronjobs/a2billing_notify_account.php   
#Charge subscriptions at 06:05 on the 1st of each month                        
0 6 1 * * php /usr/src/a2billing/Cronjobs/a2billing_subscription_fee.php 
#Update currencies at 01:00 each day                                           
0 1 * * * php /usr/src/a2billing/Cronjobs/currencies_update_yahoo.php    
" >> /var/spool/cron/asterisk                                                  

# Create Log Files
# Log files and Permissions

mkdir -p  /var/log/a2billing

touch /var/log/asterisk/a2billing-daemon-callback.log
touch /var/log/a2billing/a2billing-daemon-callback.log       
touch /var/log/a2billing/cront_a2b_alarm.log                 
touch /var/log/a2billing/cront_a2b_autorefill.log            
touch /var/log/a2billing/cront_a2b_batch_process.log
touch /var/log/a2billing/cront_a2b_bill_diduse.log
touch /var/log/a2billing/cront_a2b_subscription_fee.log
touch /var/log/a2billing/cront_a2b_currency_update.log
touch /var/log/a2billing/cront_a2b_invoice.log
touch /var/log/a2billing/cront_a2b_check_account.log
touch /var/log/a2billing/a2billing_paypal.log
touch /var/log/a2billing/a2billing_epayment.log
touch /var/log/a2billing/api_ecommerce_request.log
touch /var/log/a2billing/api_callback_request.log
touch /var/log/a2billing/a2billing_agi.log

chown asterisk:asterisk /var/log/asterisk/a2billing-daemon-callback.log
chown -R asterisk:asterisk /var/log/a2billing

Install Dahdi on Ubuntu

apt-get install -y build-essential openssh-server bison flex apache2 php5 php5-curl php5-cli php5-mysql php-pear php-db php5-gd curl sox libncurses5-dev libssl-dev libmysqlclient15-dev mpg123 libxml2-dev mono-vbnc

add netjet to  /etc/modprobe.d/blacklist.conf
add wctdm opvxa1200 to /etc/modules

#chan_mobile
apt-get install bluez-utils  bluetooth
apt-get install bluez-utils bluez-hcidump
apt-get install libbluetooth-dev

#app_fax spandsp
apt-get install libspandsp-dev libtiffxx0c2 libtiff4-dev libspandsp2 libjpeg62-dev  libtiff-tools


cdr_odbc
apt-get install unixodbc unixodbc-dev unixodbc-bin


cdr_radius
apt-get install libradiusclient-ng2 libradiusclient-ng-dev

cdr_tds
apt-get install freetds-common freetds-dev libct4 libsybdb5

chan_alsa
apt-get install libasound2-dev libasound2


chan_console
apt-get install libportaudio-dev libportaudio0 libportaudio-dev

chan_gtalk
apt-get install libiksemel-dev libiksemel-utils libiksemel3

chan_h323
chan_jingle
apt-get install libiksemel-dev libiksemel-utils libiksemel3
chan_nbs
chan_usbradio
codec_speex
apt-get install libspeex-dev speex  libspeexdsp1 libspeexdsp-dev
codec_resample
apt-get install libresample1-dev libresample1 resample

res_http_post
apt-get install libgmime2.4-cil-dev

res_srtp
apt-get install libsrtp0-dev libsrtp0

format_mp3
svn export http://svn.digium.com/svn/thirdparty/mp3/trunk addons/mp3

Testing DTMF with Asterisk

SIP DTMF Detection Problems
If you are having problems sending DTMF digits and are using a SIP phone, make sure the dtmfmode they have set is the same on the phone and in Asterisk. Also make sure you are not sending both inband and out-of-band (rfc2833) tones.


DTMF in band or out of band
as i have already mentioned i am new in Voip ans SIP protocol and i would like to know what is the difference between sending DTMF sounds in band and DTMF out of band.please help because i could not understand from the sites i found when i googled it.
Sending the DTMF codes out-of-band (OOB) means that codec used by the audio cannot mangle the DTMF codes beyond recognition.

Some codec (G.729a) don't have the fidelity needed to maintain the dual frequencies of a single DTMF tone. Sending the DTMF OOB means the other side will recognize the DTMF even if it doesn't "sound" right.


Testing DTMF with Asterisk

The D option to the Dial command transmits DTMF tones, with a 'w' causing a pause:
 Dial(<num>@<peer>,180,D(w*w1w3)) 

Manually extract and post DTMF digits

Q: I'm trying to make asterisk detect some DTMF digits during a call and post them (can't use WaitExten or Features.conf).
A: I would suggest that you implement that in logger.c and configure a line to send logs to an HTTP POST (via logger.conf), with the pbx_substitute_variables_helper function, using the ${CURL()} function directly. You may need to "preload => func_curl.so" in modules.conf, but that will work well. Or use a simple log watcher:
 
tail -n0 -f /var/log/asterisk/debug | \
   grep 'DTMF digit: [0-9#*]' | \
   your_custum_filter

Debian Install Asterisk etc

cd /usr/src
wget http://downloads.digium.com/pub/asterisk/releases/asterisk-1.6.2.6.tar.gz
wget http://downloads.digium.com/pub/telephony/dahdi-linux-complete/releases/dahdi-linux-complete-2.2.1+2.2.1.tar.gz
wget http://downloads.digium.com/pub/asterisk/releases/asterisk-addons-1.6.2.0.tar.gz
wget http://downloads.asterisk.org/pub/telephony/libpri/releases/libpri-1.4.10.2.tar.gz    
 
tar -zxvf asterisk-1.6.2.6.tar.gz
tar -zxvf dahdi-linux-complete-2.2.1+2.2.1.tar.gz
tar -zxvf asterisk-addons-1.6.2.0.tar.gz
tar -zxvf libpri-1.4.10.2.tar.gz     

Install Dahdi -
**** START - ONLY REQ for dahdi version below 2.3 ****
cd /usr/src/dahdi-linux-complete-2.2.1+2.2.1/linux/include/dahdi
edit dahdi_config.h

REPLACE :
#ifndef _DAHDI_CONFIG_H
#define _DAHDI_CONFIG_H
   
#ifdef __KERNEL__
#include <linux/version.h>
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,18)
#include <linux/config.h>
#else       
#include <linux/autoconf.h>
#endif
#endif

WITH :
#ifndef _DAHDI_CONFIG_H
#define _DAHDI_CONFIG_H

#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/module.h>
#include <linux/proc_fs.h>

#ifdef __KERNEL__
#include <linux/version.h>
#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,18)
#include <linux/config.h>
#endif
#endif

 
cd /usr/src/dahdi-linux-complete-2.2.1+2.2.1/linux/drivers/dahdi/wcb4xxp
Modify base.c
Remove #include <linux/autoconf.h>

cd ..
cd wct4xxp
Modify vpm450m.c
Remove
#else
#include <linux/autoconf.h>
**** END - ONLY REQ for dahdi version below 2.3 ****
 
cd /usr/src/dahdi-linux-complete-2.2.1+2.2.1 
make clean 
make 
make install 
make config <-- creates startup scriptsmodprobe dahdi_dummy

Install libpri -
cd /usr/src/libpri-1.4.10.2
make clean
make
make install


Install Asterisk -
cd /usr/src/asterisk-1.6.2.6
sed -i 's/PROC=@HOST_CPU@/PROC=arm/g' /usr/src/asterisk-1.6.2.6/makeopts.in
make clean
./configure  - this checks for all required pkgs before it can compile - Must be clean - will see Asterisk logo if OK
make menuconfig - this will allow you to select options to install with Asterisk

make

If the building ran fine, you should read on the screen:
+--- Asterisk Build Complete ---
+ Asterisk has successfully been built, and
+ can be installed by running:
+
+ make install
+--------------------

make install

You should then read something like:
+-- Asterisk Installation Complete ---+
...
...

make samples - To install sample config files

Having Asterisk to start at boot is as simple as running, in the /asterisk-1.6.2.1 folder, run the command:
 
make config

which will choose the right init files for your distribution, and copy them in /etc/asterisk
For your information, those files are located in the contrib/init.d/ folder

Install asterisk-addons
cd /usr/src/asterisk-addons-1.6.2.0
./configure
make menuselect
make
make install
make samples (use only for a fresh install, might overwrite your config!)
ln -s /lib/modules/`uname -r`/ /lib/modules/`uname -r`/asterisk
depmod


TEST ASTERISK
=============
As the superuser root, from whatever folder you are in, run:
asterisk
asterisk -rvvvvv
Asterisk will load it’s modules and it’s configuration, you should then read:
Asterisk Ready.
*CLI>
this is the command line interface of Asterisk, to logout run the command:
*CLI> core stop now