Sei sulla pagina 1di 11

Asterisk cdr mysql

Business PBX Solutions


Provider

Solution Details
Become an ITSP Now!
Become a serious
competitor in VoIP Immediately
FULL Consultancy,
Installation, Training & Support
Sell Hosted IP PBXs, Biz
Lines, Call Centre
Turnkey Provisioning at
your data center

Details

3CX Software PBX for Windows,


Linux and the Cloud
Open Standards
Software Solution
Easy to Install and
Manage
Auto Configures Phones
& Trunks
Android, iOS, Windows &
Mac clients

Details

*Rates shown do not include E-911 charges or government mandated taxes. Providers offering unlimited calling plans may have
restrictions. Read providers terms and conditions carefully before buying.

Asterisk can store CDR records in a MySQL database, as an alternative to CSV text files and
other database formats.

How to download cdr_mysql


it's integral part of Asterisk 1.8 and higher
You must have mysql and mysql-devel packages installed.

In an RPM-based Linux, you can check presence of MySQL like this:


o rpm -qa | grep mysql
For debian or other dpkg-based systems, check like this:
o dpkg -l mysql-server libmysqlclient*dev
In FreeBSD, you'll find MySQL in the ports
library, /usr/ports/databases/mysql4-server

Compile
it's like standard Asterisk compilation
1.
2.
3.
4.

./configure
make menuselect
make
make install

Check that in make stage that there are no mysql.h errors, which mean you are missing mysqldevel package
[root@localhost asterisk-addons-1.6.2]# make
./mkdep -fPIC -I../asterisk -D_GNU_SOURCE
`ls *.c`
app_addon_sql_mysql.c:23:19: error: mysql.h: No such file or directory
cdr_addon_mysql.c:38:19: error: mysql.h: No such file or directory
cdr_addon_mysql.c:39:20: error: errmsg.h: No such file or directory
res_config_mysql.c:53:19: error: mysql.h: No such file or directory
res_config_mysql.c:54:27: error: mysql_version.h: No such file or directory
res_config_mysql.c:55:20: error: errmsg.h: No such file or directory

If make fails due to complaining about a missing "asterisk.h" file you can either copy this file
from your asterisk directory, or create a soft link ("ln -s ...") for /usr/src/asterisk that points to
your asterisk source directory.
Another way to resolve the missing "asterisk.h" file is to run the ./configure with option "--withasterisk=" like
./configure --with-asterisk=MyAsteriskSourceDir
A sample configuration file, can be found on the cdr_mysql.conf page.
Copy the sample configuration file to /etc/asterisk/cdr_mysql.conf and edit it according to your
requirements. Then edit your modules.conf to load cdr_addon_mysql.so and finally restart
asterisk; before the restart you should, however, check that your cdr table has been created
correctly and is accessible to the username and password you specified.

Table definitions for Asterisk cdr_mysql


This is the database definition you use to install in Mysql to support billing.

Create the database


mysql --user=root --password=password [-h dbhost]

CREATE DATABASE asterisk;


GRANT INSERT
ON asterisk.*
TO asterisk@localhost
IDENTIFIED BY 'yourpassword';
USE asterisk;
CREATE TABLE `bit_cdr` (
`calldate` datetime NOT NULL default '0000-00-00 00:00:00',
`clid` varchar(80) NOT NULL default '',
`src` varchar(80) NOT NULL default '',
`dst` varchar(80) NOT NULL default '',
`dcontext` varchar(80) NOT NULL default '',
`channel` varchar(80) NOT NULL default '',
`dstchannel` varchar(80) NOT NULL default '',
`lastapp` varchar(80) NOT NULL default '',
`lastdata` varchar(80) NOT NULL default '',
`duration` int(11) NOT NULL default '0',
`billsec` int(11) NOT NULL default '0',
`disposition` varchar(45) NOT NULL default '',
`amaflags` int(11) NOT NULL default '0',
`accountcode` varchar(20) NOT NULL default '',
`userfield` varchar(255) NOT NULL default '',
`uniqueid` VARCHAR(32) NOT NULL default '',
`linkedid` VARCHAR(32) NOT NULL default '',
`sequence` VARCHAR(32) NOT NULL default '',
`peeraccount` VARCHAR(32) NOT NULL default ''
);
ALTER TABLE `bit_cdr` ADD INDEX ( `calldate` );
ALTER TABLE `bit_cdr` ADD INDEX ( `dst` );
ALTER TABLE `bit_cdr` ADD INDEX ( `accountcode` );

Please note that the rights granted in GRANT above is the _least_ the asterisk user will need.
To allow the user to do more than just add new data to the table, see the MySQL manual on
the topic
for trunk version since 29 Dec 2007 must be:
GRANT INSERT, SELECT ...
because cdr_addon_mysql now do DESC 'cdr'; for check tables fields.
Hint: Copy and paste this SQL command into a text file, save it under an appropriate name,
then execute the following command:
mysql --user=username --password=password databasename < nameoftextfile
Voila! The table is created for you. (:biggrin:)
An interesting note: on versions prior to v1.2, the name of the table, 'cdr', is hard-coded into the
mysql interface, so if the table is created under a different name, the mysql CDR backend will
not work. In v1.2 the table name is configurable via the "table=" option in cdr_mysql.conf
Yet another note: It probably isn't a good idea to use the InnoDB engine. Asterisk keeps
autocommit turned on by default; therefore, each INSERT query is its own transaction. This will
cause the query to take significantly longer to execute. On my personal computer, the "clock
time" penalty is about 4-7 times that of MyISAM on a default Ubuntu install. Please also note
that the CDR table does not require the features that the InnoDB engine provides.

Extending CDR
MySQL to supports adaptive columns natively in Asterisk 1.6
Dec. 2007: While reading the SVN commit logs I noticed that tilghman has committed a change
to allow MySQL to write to arbitrary column names. This has been present in the ODBC
driver for some time but not in the MySQL driver. It is currently only available in trunk (what will
become 1.6) but hopefully someone will write a backport. (Might want to start here: Bug
11642). Tilghman has has more details on his blog.
cdr_addon_mysql

Module has been completely revamped, with some options in the config file
no longer used and an additional new section called [aliases]. Please read
the sample config to familiarize yourself with these changes.
Module now permits arbitrary columns to be created and populated, just like
cdr_adaptive_odbc, simply by adding the column to the table and defining
the corresponding CDR() variable. Aliases may be used to define
relationships between differently-named variables and columns (such as the
calldate column and the start CDR variable).
The calldate column, as defined in the sample configuration, uses the start
time of the call, as opposed to the old behavior of using the end time.
However, you may get the old behavior for calldate, simply by changing the
alias to "end => calldate".
Standard columns may also be excluded now, simply by dropping the
column name from the table, renaming the column, or aliasing the cdrname
from a nonexistent variable (e.g. foo => amaflags).

[some_context]
;dial trunk
exten => _X.,1,Dial(SIP/trunk/${EXTEN})
;exten h must be in same context!
exten => h,1,noop("extended CDR")
exten => h,n,set(CDR(hangupcause)=${HANGUPCAUSE})
;
hangupcause
exten => h,n,set(CDR(peerip)=${CHANNEL(peerip)})
; like
10.0.0.5 if behind nat
exten => h,n,set(CDR(recvip)=${CHANNEL(recvip)})
; like
194.79.52.192 - public ip
exten => h,n,set(CDR(from)=${CHANNEL(from)})
; like
sip:1111@sip.proxy.cz
exten => h,n,set(CDR(uri)=${CHANNEL(uri)})
; like
sip:1111@10.0.0.5
exten => h,n,set(CDR(useragent)=${CHANNEL(useragent)})
;
useragent like Aastra_57i
exten => h,n,set(CDR(codec1)=${CHANNEL(audioreadformat)})
;
codec *
exten => h,n,set(CDR(codec2)=${CHANNEL(audiowriteformat)})
;
exten => h,n,set(CDR(llp)=${CHANNEL(rtpqos,audio,local_lostpackets)})
; lost
packets by local end **
exten => h,n,set(CDR(rlp)=${CHANNEL(rtpqos,audio,remote_lostpackets)}) ; lost
packets by remote end
exten => h,n,set(CDR(ljitt)=${CHANNEL(rtpqos,audio,local_jitter)})
; the
same for jitter
exten => h,n,set(CDR(rjitt)=${CHANNEL(rtpqos,audio,remote_jitter)})

Storing the Unique ID


Q: It would appear that the "uniqueid" field is not being populated in the MySQL CDR DB. Is
this an obsolete field or is a bug?
A: You need to define MYSQL_LOGUNIQUEID at compile time for it to use that field.
You have two options in /usr/src/asterisk-addons:
1. Either add CFLAGS+=-DMYSQL_LOGUNIQUEID to the Makefile.
Note that recently (around Asterisk 1.4.18 or before) this has changed to ASTCFLAGS+=DMYSQL_LOGUNIQUEID
2. Or instead add a #define MYSQL_LOGUNIQUEID to the top of cdr_addon_mysql.c.
Finally perform the usual make clean, make, make install. Be sure to check the Makefile for the
presence of this flag after having done a CVS update! You will most probably also want to index
the uniqueid field in your cdr table to improve performance.
You will also have to add a `uniqueid` column in your mysql database after the `accountcode`
column:
ALTER TABLE `bit_cdr` ADD `uniqueid` VARCHAR(32) NOT NULL default ''
after `accountcode`;
What would I need all this for? For example you are running an AGI script and would like to be
able to related AGI data with the CDR table. The problem is that the AGI script will lose
connection to the call as soon as the caller hangs up, so you'll need a way to find the correct
cdr entry (that'll also be created only after the call has been completed).
Attention! The uniqueid field is not guaranteed to be unique across the different CDR
entries, even though the name suggests exactly that. In fact Uniqueid has never been
guaranteed to be unique across all CDRs: It is only unique across a channel, and a channel
may have multiple CDRs.

If you get the following error while compiling


cdr_mysql:
/usr/bin/ld: cannot find -lz
Make sure you have the zlib-devel package installed.

See also

Asterisk billing
Asterisk CDR csv conversion mysql
Asterisk CDR csv mysql import
Asterisk CDR csv mysql Perl import
Asterisk CDR Master.csv postgresql Perl import
Asterisk cdr odbc
Asterisk config cdr_mysql.conf
Asterisk voicemail database
Asterisk queue_log on MySQL
What is CDR

Asterisk CDR en MySQL


Publicado en 19 noviembre, 2012 por

Gonzalo

Para llevar un completo control de todos los eventos de llamadas en Asterisk o


hacer un sistema de facturacin no hay como CEL (Channel Event Logging). Sin
embargo para ciertas tareas puede ser ms que suficiente almacenar los CDR (Call
Detail Record) de Asterisk en una BBDD MySQL.
Desde la versin 1.8 ya viene incluido y no hace falta descargarse las addons.
Simplemente necesitamos instalar la dependencia libmysqlclient-dev y mysqlserver si la BBDD va a ir en el mismo servior y al compilar asterisk seleccionar la
opcin Add-ons > [*]cdr_mysql

Yo voy a tener la BBDD en otro servidor (192.168.3.3). As que la creamos.


1- Nos conectamos a MySQL:
# mysql -u root -p
2- Creamos la database:
mysql> CREATE DATABASE asteriskCDR;

3- Creamos un usuario asterisk para esta database asteriskCDR:


mysql> GRANT INSERT ON asteriskCDR.* TO asterisk@localhost IDENTIFIED BY
'password';

4- Creamos la tabla:
mysql> USE asteriskCDR;
Database changed

mysql> CREATE TABLE `cdr` (


`calldate` datetime NOT NULL default '0000-00-00 00:00:00',
`clid` varchar(80) NOT NULL default '',
`src` varchar(80) NOT NULL default '',
`dst` varchar(80) NOT NULL default '',
`dcontext` varchar(80) NOT NULL default '',
`channel` varchar(80) NOT NULL default '',
`dstchannel` varchar(80) NOT NULL default '',
`lastapp` varchar(80) NOT NULL default '',
`lastdata` varchar(80) NOT NULL default '',
`duration` int(11) NOT NULL default '0',
`billsec` int(11) NOT NULL default '0',
`disposition` varchar(45) NOT NULL default '',
`amaflags` int(11) NOT NULL default '0',
`accountcode` varchar(20) NOT NULL default '',
`userfield` varchar(255) NOT NULL default '',
`uniqueid` VARCHAR(32) NOT NULL default '',
`linkedid` VARCHAR(32) NOT NULL default '',
`sequence` VARCHAR(32) NOT NULL default '',
`peeraccount` VARCHAR(32) NOT NULL default ''
);

Una vez hecho esto ponemos como ndices para optimizar la bsqueda por estos
campos:
ALTER TABLE `cdr` ADD INDEX ( `calldate` );
ALTER TABLE `cdr` ADD INDEX ( `dst` );
ALTER TABLE `cdr` ADD INDEX ( `accountcode` );

5- Si queremos le damos permiso para acceder solo desde nuestra PBX Asterisk
(192.168.3.2):

GRANT ALL ON asteriskCDR.* TO asterisk@'192.168.3.2' IDENTIFIED BY


'nuestro passwd';

Para que se pueda acceder a la BBDD desde otro servidor puede que necesitemos
configurar nuestra database editando el archivo /etc/mysql/my.cnf y cambiando la
opcin bind-address = 127.0.0.1 por bind-address = 0.0.0.0 y reiniciando el
servidor service mysql restart.
A continuacin configuramos nuestra PBX Asterisk (192.168.3.2) para guardar los
CDR en esa database.
Editamos el archivo /etc/asterisk/cdr_mysql.so y ponemos algo tal que as:

[global]
hostname=192.168.3.3 ;ip de nuestra database. Si fuese local pondramos
localhost
dbname=asteriskCDR
table=cdr
password=el que sea
user=asterisk
port=3306
sock=/tmp/mysql.sock

[columns]
;static "" => ;alias => alias start => calldate
alias callerid => clid
;alias src => src
;alias dst => dst
;alias dcontext => dcontext
;alias channel => channel
;alias dstchannel => dstchannel
;alias lastapp => lastapp
;alias lastdata => lastdata
;alias duration => duration
;alias billsec => billsec
;alias disposition => disposition
;alias amaflags => amaflags
;alias accountcode => accountcode
;alias userfield => userfield
;alias uniqueid => uniqueid

Salvamos el archivo y comprobamos desde el CLI> que tenemos soporte para el


mdulo cdr_mysql.so
CLI> module show like cdr_mysql.so
Module Description Use Count
cdr_mysql.so MySQL CDR Backend 0
1 modules loaded

Para que empiece a grabar los CDR en la database descargamos y cargamos el


mdulo:
CLI> module unload cdr_mysql.so
== Unregistered 'mysql' CDR backend

CLI> module load cdr_mysql.so


Loaded cdr_mysql.so
== Parsing '/etc/asterisk/cdr_mysql.conf': == Found
-- Found alias start for column calldate
-- Found alias callerid for column clid
Loaded cdr_mysql.so => (MySQL CDR Backend)

Y comprobamos que est todo bien:


CLI> cdr mysql status
Connected to asteriskCDR@192.168.3.3, port 3306 using table cdr for 1
hours, 1 minutes, 49 seconds.
Wrote 2 records since last restart.

CLI> cdr show status

Call Detail Record (CDR) settings


---------------------------------Logging: Enabled
Mode: Simple
Log unanswered calls: No

* Registered Backends
------------------mysql
csv
cdr-custom

y tiene que aparecer entre los Registered Backends mysql.


Listo

NOTA sobre uniqueid


Para habilitar uniqueid hay que seguir este How-To:
http://www.voip-info.org/wiki/view/Asterisk+cdr+mysql
Los nicos campos escribibles son:
${CDR(accountcode)} The channels account code (read-write).

${CDR(uniqueid)} The channels unique id.


${CDR(userfield)} The channels uses specified field (read-write).