Obtain the software from http://cdrtool.ag-projects.com. The software is
available as a tar archive or as a debian package.
Installing from the tar archive:
Change directory to your web root (/var/www on Debian systems)
tar zxvf cdrtool*.tgz
Installing from the debian package:
dpkg -i cdrtool*.deb
The files will be installed under /var/www/CDRTool directory.
Create CDRTool database
-----------------------
You need MySQL root access with GRANT priviledges from the machine where
CDRTool runs, otherwise copy the files required by setup/setup_mysql.sh to
the MySQL machine and run the script locally.
Change the MySQL password of the cdrtool user from file
setup/create_users.mysql
Then run the database setup script:
/var/www/CDRtool/setup/mysql/setup_mysql.sh
The script performs the following:
1. It adds to the MySQL server a user for cdrtool software
2. It creates a new MySQL database "cdrtool"
3. It creates a default web user admin/admin, you may use
this initial account to login in the web interface
4. It populates the cdrtool database with initial values
PHP setup and Apache setup
--------------------------
Install PHP and dependencies. If you have chosen to install the debian package, the dependencies will be resolved during installation.
Example for Debian systems and php4:
Enable php-mysql module in /etc/php/*/php.ini:
extension=mysql.so
Enable php in apache web server. Configuration example for apache on Debian systems:
/etc/apache/httpd.conf
DirectoryIndex index.phtml index.php index.html index.htm index.shtml index.cgi
AddType application/x-httpd-php .php
AddType application/x-httpd-php .phtml
Make sure php module is insbale in apache configuration. For apache this is done in /etc/apache/modules.conf:
LoadModule php4_module /usr/lib/apache/1.3/libphp4.so
Change AllowOverride None to AllowOverride All
For apache2 us a2enmode php command.
Create a virtual host for cdrtool. Example for apache2:
cp setup/apache2/sites-available/cdrtool.example.com /etc/apache2/sites-enabled
cp setup/apache2/conf.d/cdrtool /etc/apache2/conf.d/
ServerName cdrtool.example.com
DocumentRoot /var/www/
CustomLog /var/log/apache2/cdrtool-access.log combined
ErrorLog /var/log/apache2/cdrtool-errors.log
SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
# To enable SSL:
# a2enmode ssl
# add Listen 443 to ports.conf file
# generate site certificates
# SSLEngine On
# SSLCertificateFile /etc/apache2/ssl/snakeoil-rsa.crt
# SSLCertificateKeyFile /etc/apache2/ssl/snakeoil-rsa.key
Enable the virtual site using:
a2ensite cdrtool.example.com
You may enable ssl using "a2enmod ssl" command. If you use ssl you must also generate a site certificate using the instructions provided by apache2 software.
Create a configuration file
---------------------------
cd /var/www/CDRTool
cp setup/global.inc.new.installation global.inc
Edit global.inc and setup your variables to match your system.
For each different datasource you must instantiate a new class extending one of the existing classes (ser, asterisk or cisco).
global.inc.in contains a more elaborate example for setting up datasources
Enable rating engine
--------------------
The rating engine is used for prepaid applications and as price calculator for postpaid traffic. It provides access to the rating tables and stays in memory (running as a daemon) to avoid reading the rating tables at every rating request. The rating tables can be reloaded without restarting the rating engine.
See the information in the head of the scripts/ratingEngine.php daemon for how to enable prepaid or other rating functionality. For prepaid, an external B2BUA is required, CDRTool provides only the rating and update balance functions.
Set the IP and port where the rating engine listens to and the OpenSER datasource in global.inc:
$RatingEngine=array("socketIP" => IP.address.of.the.private.interface.of.cdrtool.example.com",
"socketPort" => "9024",
"CDRS_class" => "ser_radius");
The MSQL schema for prepaid accounts: setup/mysql/create_prepaid.mysql The network engine has no security features, it must run over a protected network.
Edit /etc/default/cdrtool and set RUN_ratingEngine=yes
Then restart the rating engine:
/etc/init.d/cdrtool restart
High availability
-----------------
Setup heartbeat and MySQL replication.
CRON setup
----------
Some operations must be scheduled to run periodically by cron. Such operations are the scripts that block fraudulous accounts in OpenSER, normalize the call detail records, purge the old SIP traces.
The sample cron file is in /var/www/CDRTool/setup/crontabs/
This is done automatically if you install the debian package.
RADIUS setup
------------
CDRTool works with FreeRadius server from http://www.freeradius.org
apt-get install freeradius freeradius-mysql Create the database for radius tables on MySQL server
mysqladmin -u root create radius
Create RADIUS tables
The paths might differ depending on freeradius installation
cp /usr/share/doc/freeradius/examples/db_mysql.sql.gz .
gunzip db_mysql.sql.gz
mysql -u root radius < /usr/share/doc/freeradius/examples/db_mysql.sql
Patch radacct table for storage of CISCO VSA and rating. Apply a patch to the default radacct table. This will add fields necessary to store Vendor Specific Atributes from Cisco or OpenSER.
It is not possible to mix call details records from CISCO and OpenSER in the same radius table. You need to create multiple radius server profiles and save the CDRs into dedicated tables for each datasource.
Modify the default radacct table for OpenSER by running:
/var/www/CDRTool/setup/radius/OpenSER/radacct-patch.sh
and for CISCO by running:
/var/www/CDRTool/setup/radius/CISCO/radacct-patch.sh
Configure Freeradius to write data into the radacct table:
cp /var/www/CDRTool/setup/radius/OpenSER/sql.conf /etc/freeradius/sql.conf
For large volume of CDRs it is usefull automatically rotate the tables in which the data is written.
/var/www/CDRTool/setup/radius/OpenSER/radius_accounting.*, contain mysql procedures that automatically create monthly tables in the format radacctYYYYMM. To use mysql procedures, your must use MySQL server version 5 or greater and Freeradius server mysql module must be compiled to support CLIENT_MULTI_RESULTS mysql connection flag. This must be done in
src/modules/rlm_sql/drivers/rlm_sql_mysql/sql_mysql.c:
if (!(mysql_sock->sock = mysql_real_connect(&(mysql_sock->conn),
config->sql_server,
config->sql_login,
config->sql_password,
config->sql_db,
atoi(config->sql_port),
NULL,
CLIENT_FOUND_ROWS|CLIENT_MULTI_RESULTS ))) {
Also, if you use MediaProxy for accounting in combination with OpenSER you must use the MediaProxy version that supports the same mysql procedures.
Edit the database connection details in sql.conf and restart Freeradius server.
Add RADIUS clients in clients.conf. Each device sending RADIUS accounting requests must be added to /etc/radddb/clients.conf. Examples:
client 10.0.0.0/8 {
secret=DssUET01
nastype=other
shortname=localnet
}
Enable MySQL accounting in FreeRadius server. Edit radius.conf "sql" must be uncommented or added if missing.
# accounting {
detail
sql
}
Copy /var/www/CDRTool/setup/radius/OpenSER/dictionary.ser to /etc/freeradius
OpenSER setup
-------------
CDRTool version >4.3 have been tested only against OpenSER 1.0 and above.
Enable MySQL storage for subscribers and accounting and Radius accounting. For SIP Tracing you need OpenSER siptrace module. To enable quota you must add an extra column in the subscriber table:
alter table openser.subscriber add column quota int not null;
Entries required in openser.cfg:
loadmodule "acc.so"
modparam("acc", "failed_transaction_flag", 1)
modparam("acc", "report_cancels", 0)
modparam("acc", "report_ack", 0)
modparam("acc", "early_media", 0)
modparam("acc", "log_level", 1)
modparam("acc", "log_flag", 1)
modparam("acc", "log_missed_flag", 1)
modparam("acc", "radius_config", "/etc/openser/radius/client.conf")
modparam("acc", "radius_flag", 1)
modparam("acc", "radius_missed_flag", 1)
modparam("acc", "radius_extra", "Sip-RPid=$avp(s:rpid); \
Source-IP=$si; \
Source-Port=$sp; \
Canonical-URI=$avp(can_uri); \
Billing-Party=$avp(billing_party); \
Divert-Reason=$avp(s:divert_reason); \
X-RTP-Stat=$avp(s:rtp_statistics); \
From-Header=$hdr(from); \
User-Agent=$hdr(user-agent); \
Contact=$hdr(contact); \
Event=$hdr(event); \
SIP-Proxy-IP=$avp(s:sip_proxy_ip)")
Further, you must enable accounting in various parts of the routing script by setting the accounting flag and saving the AVP containing the proxy IP address. It is important to save $avp(can_uri) after the Proxy has performed all possible lookups except DNS. The Canonical-URI will be used for rating the session. Example:
route {
...
setflag(ACCOUNTING_FLAG);
avp_write("SER_IP","$avp(s:sip-proxy)");
avp_write("$ru", "$avp(can_uri)");
}
Copy /var/www/CDRTool/setup/radius/OpenSER/dictionary.ser to /etc/openser/radius/ and uncomment the line:
$INCLUDE /etc/radiusclient-ng/dictionary
SOAP engine
-----------
Warning!
Support for the SOAP engine has been discontinued from version >=5.0.
Note: It depends on the SOAP library from http://pear.php.net/package/SOAP. On Debian systems, this dependency is automatically installed but if CDRTool is installed from the tar archive you must download and install manually this SOAP library.
The SOAP engine can be used by an external provisioning system to access information available in CDRTool (like prepaid accounts).
The rating and other CDRTool functions (like provisioning of prepaid accounts or checking the balance) are available by using SOAP calls. The SOAP calls are translated into requests for the rating engine (which must be up and running, see previous section).
The SOAP functionality including a WSDL file for creating a SOAP client is available in SOAP/WSDL/ directory.
The SOAP server supports authorization, the SOAP clients must connect using an account that has soap_client right assigned into the CDRTool accounts page. The SOAP server uses the Apache web server for transport, it can work with both HTTP and HTTPS. The servers logs all network requests to syslog.
Define in global.inc the SOAP server URL where the client should connect to:
$SOAPServer=array("cdr_source"=>"ser_radius",
"location" =>"https://example.com/CDRTool/SOAP/server.php",
"wsdl" =>"https://example.com/CDRTool/SOAP/WSDL/"
);
A test SOAP client is available in SOAP/client.php. It connects to the server and displays the CDRTool server version.
To prevent a bug in PEAR SOAP server add the following last line in function SOAP_ServerErrorHandler from SOAP/Server.php
function SOAP_ServerErrorHandler($errno, $errmsg, $filename,$linenum, $vars) {
....
unset($soap_server_fault->backtrace);
}
Interaction between rating engine and SOAP:
Function Provisioning B2BUA RatingEngine SOAP/XML
----------------------------------------------------------------------------------------
MaxSessionTime <----------------->
DeductBalance <----------------->
AddBalance ----------------------------------------------------------->
<------------------
CheckBalance ----------------------------------------------------------->
<------------------
ShowAccounts ----------------------------------------------------------->
<------------------
LastMissedCalls ----------------------------------------------------------->
LastPlacedCalls ----------------------------------------------------------->
LastReceivedCalls ----------------------------------------------------------->
OpenSERLocations ----------------------------------------------------------->
MediaProxy setup
----------------
MediaProy can log into CDRTool the IP bandwidth utilization, the codecs and the User Agents. MediaProxy logs this information into the database used by the Radiusserver, the radacct table.
MediaProxy can also correct the session duration of CDRs for which no BYE messages have been received.
The following information is logged:
- InputOctets and OutputOctets
- CodecType (like GSM or G711)
- ApplicationType (text/audio/video)
- User Agent(s)
- Media IP source and IP destination
See MediaProxy documentation for how to enable Radius or database accounting.
Asterisk setup
--------------
Download from cvs the asterisk-addons and patch asterisk to store CDRs in MySQL.
See /var/www/CDRTool/setup/asterisk for more information.
Cisco setup
-----------
Use the CISCO CLI, enter enable mode and configuration from terminal:
>enable
config terminal
aaa new-model
aaa group server radius aaa.router
server RADIUS_SERVER_IP auth-port 1812 acct-port 1813
aaa accounting connection h323 start-stop group radius
gw-accounting h323
gw-accounting h323 vsa
gw-accounting voip
Manual CDR uploads
------------------
If MySQL is down you will miss CDRs written by RADIUS. These CDRs can be reload manually from radius accounting files using the supplied upload scripts in scripts directory (IPNX, OpenSER and CISCO import scripts available).
Q931 Release codes for Cisco
----------------------------
In CDRTool CISCO hexadecimal release codes are automatically mapped to Q931 release codes.
Rating engine
-------------
See RATING file.
Monitoring
----------
Monit can check if the rating engine stopped working and restart it. A sample configuration file for monit is available in setup/monit/monitrc. Edit the IP address and hostname where the rating engine runs and copy /var/www/CDRTool/setup/monit/monitrc /etc/monit/monit.d/cdrtool
Usage statistics
----------------
CDRTool can build usage statistics of the number of online SIP devices from OpenSER, simultaneous number of media streams and relayed IP traffic by MediaProxy.
Define DB_siponline as a new database class in global.inc. Example:
class DB_siponline extends DB_Sql {
var $Host = "db";
var $Database = "openser";
var $User = "openser";
var $Password = "password";
var $Halt_On_Error ="no";
}
Define all media proxy servers in:
/var/www/CDRTool/status/config/media_servers.php
The script that gathers the usage information and builds the graphical statistics is /var/www/CDRTool/scripts/buildStatistics.php
This script runs as a cron job every 5 minutes.
The usage information is cumulated in /tmp/CDRTool-sip-statistics.txt file, which is a plain text file with one line per domain and values separated by tabs. This file can be easily parsed by external scripts to build statistics using other tools like SNMP.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
MYSQL SP
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
/*
LAST UPDATED: 2007-01-04 03:14 CET
CHANGELOG:
- Added database name as parameter to stored procedures
- Fixed the multiple query result in "update_raddact_record_mediaproxy"
- Modus operandi update
- Fixed determination of previous year in "update_raddact_record_mediaproxy"
- Consolidate SET statements to minimize binary log entries
- Fixed bug in update_raddact_record_mediaproxy, the record values were reset
after execution of update on the first table causing failure to update
the previous table
Starting with version CDRTool version 4.9 it is possible to store call
details records in automatically rotated radacct tables by using MySQL
stored procedures.
This implementation has been contributed by
Andrei Magureanu
How to setup auto-rotation
--------------------------
1. Load radius_accounting.proc into the mysql server. MySQL >=5.0
version and SUPER priviledges are required.
2. Patch the Freeradius server mysql client to allow stored procedures.
Instructions can be found in ../freeradius directory. Re-compile and
re-install Freeradius server.
3. Copy radius_accounting.conf to sql.conf to the Freeradius server. Edit
the new sql.conf with the database connection information.
4. Update MediaProxy configuration to use radius accounting, instead of
database accounting (MediaProxy >= 1.8.0 is required)
5. In CDRTool, change global.inc table name to:
"table" => "radacct".date("Ym"),
The modus operandi of the stored procedure
------------------------------------------
Currently, call detail records generated by the OpenSER SIP Proxy are stored into a central radius.radacct table. The radacct table grows and must be manually purged, the purge operation locks the table for writing, which is blocking the application that performs the queries, and this situation is unacceptable.
The radacct tables are populated with data as follows: When a SIP session starts, an INSERT query generated by the Freeradius server inserts data into MySQL a radacctYYYYMM table (e.g. radacct200611). Later, when the SIP session ends, an UPDATE query sets various fields of the previously inserted record. The server that performs the INSERT matches the inserted data based on indexes present in the table. We want to store the data in monthly tables that have a name based on the following syntax:
radacct%Y%m
Examples:
radacct200611 (November table)
radacct200612 (December table)
The stored procedure achieves the following: On INSERT the monthly table is created automatically when necessary. If an INSERT query fails with the mysql code table not available, the right table is created and the INSERT query is performed in the new table. The table name is derived from the current month, which is determined from the AcctStartTime radius attribute. On UPDATE the procedure detects if the UPDATE query has failed because the record does not exist in the current table and updates the record in the previous table by substracting one calendar month, redefining the table name
and retry the query. The table name is derived from the AcctStopTime radius attribute. A example of queries on how the procedures can be used is available at the end of this script.
*/
-- OPTIONAL (COMMENT OUT): DATABASE TO USE
-- USE radius;
-- MUST FOR UNIX BASED SYSTEMS -- (SEE: http://dev.mysql.com/doc/refman/5.0/en/stored-procedure-logging.html)
-- SET GLOBAL log_bin_trust_function_creators = 1;
DELIMITER ;
-- CREATE "BEGINNING OF DEFAULT TABLE NAME" FUNCTION
DROP FUNCTION IF EXISTS `set_radacct_table_name`;
DELIMITER $$
CREATE FUNCTION `set_radacct_table_name`() RETURNS varchar(50)
DETERMINISTIC
BEGIN
DECLARE tblname VARCHAR(50);
SET tblname = 'radacct';
RETURN tblname;
END $$
DELIMITER ;
-- CREATE SUPPORT "CREATE TABLE" PROCEDURE
DROP PROCEDURE IF EXISTS `create_radacct_table`;
DELIMITER $$
CREATE PROCEDURE `create_radacct_table`(IN var_tbl VARCHAR(50))
BEGIN
SET @stbl = CONCAT("CREATE TABLE IF NOT EXISTS ", var_tbl, " (
`RadAcctId` bigint(21) NOT NULL auto_increment,
`AcctSessionId` varchar(255) NOT NULL default '',
`AcctUniqueId` varchar(255) NOT NULL default '',
`UserName` varchar(64) NOT NULL default '',
`Realm` varchar(64) default '',
`NASIPAddress` varchar(15) NOT NULL default '',
`NASPortId` varchar(50) NOT NULL default '',
`NASPortType` varchar(255) NOT NULL default '',
`AcctStartTime` datetime NOT NULL default '0000-00-00 00:00:00',
`AcctStopTime` datetime NOT NULL default '0000-00-00 00:00:00',
`AcctSessionTime` int(12) default NULL,
`AcctAuthentic` varchar(32) default NULL,
`ConnectInfo_start` varchar(32) default NULL,
`ConnectInfo_stop` varchar(32) default NULL,
`AcctInputOctets` bigint(12) default NULL,
`AcctOutputOctets` bigint(12) default NULL,
`CalledStationId` varchar(50) NOT NULL default '',
`CallingStationId` varchar(50) NOT NULL default '',
`AcctTerminateCause` varchar(32) NOT NULL default '',
`ServiceType` varchar(32) default NULL,
`FramedProtocol` varchar(32) default NULL,
`FramedIPAddress` varchar(15) NOT NULL default '',
`AcctStartDelay` int(12) default NULL,
`AcctStopDelay` int(12) default NULL,
`SipMethod` varchar(50) NOT NULL default '',
`SipResponseCode` smallint(5) unsigned NOT NULL default '0',
`SipToTag` varchar(128) NOT NULL default '',
`SipFromTag` varchar(128) NOT NULL default '',
`SipTranslatedRequestURI` varchar(255) NOT NULL default '',
`SipUserAgents` varchar(255) NOT NULL default '',
`SipApplicationType` varchar(255) NOT NULL default '',
`SipCodecs` varchar(255) NOT NULL default '',
`SipRPID` varchar(255) NOT NULL default '',
`SipRPIDHeader` varchar(255) NOT NULL default '',
`SourceIP` varchar(255) NOT NULL default '',
`SourcePort` varchar(255) NOT NULL default '',
`CanonicalURI` varchar(255) NOT NULL default '',
`DelayTime` varchar(5) NOT NULL default '',
`Timestamp` bigint(20) NOT NULL default '0',
`DestinationId` varchar(15) NOT NULL default '',
`Rate` text NOT NULL,
`Price` double(20,4) default NULL,
`Normalized` enum('0','1') default '0',
`BillingId` varchar(255) NOT NULL default '',
`MediaInfo` varchar(32) default NULL,
`RTPStatistics` text NOT NULL,
`FromHeader` varchar(128) NOT NULL default '',
`UserAgent` varchar(128) NOT NULL default '',
`Contact` varchar(128) NOT NULL default '',
PRIMARY KEY (`RadAcctId`),
UNIQUE KEY `sess_id` (`AcctSessionId`(128),`SipFromTag`,`SipToTag`),
KEY `UserName` (`UserName`),
KEY `AcctSessionId` (`AcctSessionId`),
KEY `AcctUniqueId` (`AcctUniqueId`),
KEY `AcctStartTime` (`AcctStartTime`),
KEY `AcctStopTime` (`AcctStopTime`),
KEY `NASIPAddress` (`NASIPAddress`),
KEY `caller_idx` (`CallingStationId`),
KEY `called_idx` (`CalledStationId`),
KEY `canon_idx` (`CanonicalURI`),
KEY `source_ip_idx` (`SourceIP`),
KEY `billing_id_idx` (`BillingId`),
KEY `dest_id_idx` (`DestinationId`),
KEY `sip_req_uri_idx` (`SipTranslatedRequestURI`),
KEY `normalize_idx` (`Normalized`),
KEY `MediaInfo_idx` (`MediaInfo`),
KEY `Realm_idx` (`Realm`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1");
PREPARE ctbl_stmt FROM @stbl;
EXECUTE ctbl_stmt;
DEALLOCATE PREPARE ctbl_stmt;
END $$
DELIMITER ;
-- CREATE "INSERT RECORD" PROCEDURE
DROP PROCEDURE IF EXISTS `insert_radacct_record`;
DELIMITER $$
CREATE PROCEDURE `insert_radacct_record`(
IN var_db_name VARCHAR(20),
IN var_AcctSessionId VARCHAR(255),
IN var_AcctUniqueId VARCHAR(255),
IN var_UserName VARCHAR(64),
IN var_Realm VARCHAR(64),
IN var_NASIPAddress VARCHAR(15),
IN var_NASPortId VARCHAR(50),
IN var_AcctStartTime VARCHAR(20),
IN var_AcctStopTime VARCHAR(20),
IN var_AcctSessionTime INT(12),
IN var_AcctInputOctets BIGINT(12),
IN var_AcctOutputOctets BIGINT(12),
IN var_CalledStationId VARCHAR(50),
IN var_CallingStationId VARCHAR(50),
IN var_AcctTerminateCause VARCHAR(32),
IN var_ServiceType VARCHAR(32),
IN var_FramedProtocol VARCHAR(32),
IN var_FramedIPAddress VARCHAR(15),
IN var_AcctStartDelay INT(12),
IN var_AcctStopDelay INT(12),
IN var_SipResponseCode SMALLINT(5),
IN var_SipMethod VARCHAR(50),
IN var_SipTranslatedRequestURI VARCHAR(255),
IN var_SipToTag VARCHAR(128),
IN var_SipFromTag VARCHAR(128),
IN var_SipRPID VARCHAR(255),
IN var_SourceIP VARCHAR(255),
IN var_SourcePort VARCHAR(255),
IN var_CanonicalURI VARCHAR(255),
IN var_Rate TEXT,
IN var_RTPStatistics TEXT
)
BEGIN
-- SET VARIABLES
SET @v_AcctSessionId = var_AcctSessionId,
@v_AcctUniqueId = var_AcctUniqueId,
@v_UserName = var_UserName,
@v_Realm = var_Realm,
@v_NASIPAddress = var_NASIPAddress,
@v_NASPortId = var_NASPortId;
IF var_AcctStartTime = '0' OR var_AcctStartTime = '' THEN
SET @v_AcctStartTime = NOW();
ELSE
SET @v_AcctStartTime = CAST(var_AcctStartTime AS DATETIME);
END IF;
IF var_AcctStopTime = '0' OR var_AcctStopTime = '' THEN
SET @v_AcctStopTime = CAST('0000-00-00 00:00:00' AS DATETIME);
ELSE
SET @v_AcctStopTime = CAST(var_AcctStopTime AS DATETIME);
END IF;
SET @v_db_name = var_db_name,
@v_AcctSessionTime = var_AcctSessionTime,
@v_AcctInputOctets = var_AcctInputOctets,
@v_AcctOutputOctets = var_AcctOutputOctets,
@v_CalledStationId = var_CalledStationId,
@v_CallingStationId = var_CallingStationId,
@v_AcctTerminateCause = var_AcctTerminateCause,
@v_ServiceType = var_ServiceType,
@v_FramedProtocol = var_FramedProtocol,
@v_FramedIPAddress = var_FramedIPAddress,
@v_AcctStartDelay = var_AcctStartDelay,
@v_AcctStopDelay = var_AcctStopDelay,
@v_SipResponseCode = var_SipResponseCode,
@v_SipMethod = var_SipMethod,
@v_SipTranslatedRequestURI = var_SipTranslatedRequestURI,
@v_SipToTag = var_SipToTag,
@v_SipFromTag = var_SipFromTag,
@v_SipRPID = var_SipRPID,
@v_SourceIP = var_SourceIP,
@v_SourcePort = var_SourcePort,
@v_CanonicalURI = var_CanonicalURI,
@v_Rate = var_Rate,
@v_RTPStatistics = var_RTPStatistics,
@var_y = (SELECT YEAR(@v_AcctStartTime)),
@var_m = (SELECT DATE_FORMAT(@v_AcctStartTime, '%m')),
@var_tbl_begin = (SELECT set_radacct_table_name()),
@var_tbl = CONCAT(@var_tbl_begin, @var_y, @var_m),
@var_tbl_cnt = (SELECT COUNT(TABLE_NAME) AS TBLCNT
FROM information_schema.tables
WHERE TABLE_SCHEMA = @v_db_name
AND TABLE_NAME = @var_tbl);
-- TABLE DOES NOT EXIST
IF @var_tbl_cnt = 0 THEN
-- CREATE RAD TABLE
SET @ctblproc = CONCAT("CALL create_radacct_table(", "'", @var_tbl, "'", ")");
PREPARE ctbl_proc_stmt FROM @ctblproc;
EXECUTE ctbl_proc_stmt;
DEALLOCATE PREPARE ctbl_proc_stmt;
END IF;
-- INSERT RECORD IN NEW TABLE
SET @instmt = CONCAT("INSERT INTO ", @var_tbl, " (
RadAcctId, AcctSessionId, AcctUniqueId,
UserName, Realm, NASIPAddress, NASPortId,
AcctStartTime, AcctStopTime, AcctSessionTime,
AcctInputOctets, AcctOutputOctets, CalledStationId,
CallingStationId, AcctTerminateCause, ServiceType,
FramedProtocol, FramedIPAddress, AcctStartDelay,
AcctStopDelay, SipResponseCode,
SipMethod, SipTranslatedRequestURI, SipToTag,
SipFromTag, SipRPID, SourceIP, SourcePort, CanonicalURI,
Rate, RTPStatistics)
VALUES (NULL, ?, ?, ?, SUBSTRING_INDEX(?, '@',-1),
?, ?, ?, ?, ?, ?, ?, trim(leading 'sip:' from trim(leading 'sips:' from ?)), trim(leading 'sip:' from trim(leading 'sips:' from ?)), ?, ?, ?, ?, ?, ?, ?, ?,trim(leading 'sip:' from trim(leading 'sips:' from ?)), ?, ?, ?, ?, ?, trim(leading 'sip:' from trim(leading 'sips:' from ?)), ?, ? )");
PREPARE add_rad FROM @instmt;
EXECUTE add_rad USING @v_AcctSessionId, @v_AcctUniqueId,
@v_UserName, @v_Realm, @v_NASIPAddress, @v_NASPortId,
@v_AcctStartTime, @v_AcctStopTime, @v_AcctSessionTime,
@v_AcctInputOctets, @v_AcctOutputOctets, @v_CalledStationId,
@v_CallingStationId, @v_AcctTerminateCause, @v_ServiceType,
@v_FramedProtocol, @v_FramedIPAddress, @v_AcctStartDelay,
@v_AcctStopDelay, @v_SipResponseCode, @v_SipMethod,
@v_SipTranslatedRequestURI, @v_SipToTag, @v_SipFromTag,
@v_SipRPID, @v_SourceIP, @v_SourcePort, @v_CanonicalURI,
@v_Rate, @v_RTPStatistics;
DEALLOCATE PREPARE add_rad;
-- CLEAN UP
SET @v_AcctSessionId = null,
@v_AcctUniqueId = null,
@v_UserName = null,
@v_Realm = null,
@v_NASIPAddress = null,
@v_NASPortId = null,
@v_AcctStartTime = null,
@v_AcctStopTime = null,
@v_AcctSessionTime = null,
@v_AcctInputOctets = null,
@v_AcctOutputOctets = null,
@v_CalledStationId = null,
@v_CallingStationId = null,
@v_AcctTerminateCause = null,
@v_ServiceType = null,
@v_FramedProtocol = null,
@v_FramedIPAddress = null,
@v_AcctStartDelay = null,
@v_AcctStopDelay = null,
@v_SipResponseCode = null,
@v_SipMethod = null,
@v_SipTranslatedRequestURI = null,
@v_SipToTag = null,
@v_SipFromTag = null,
@v_SipRPID = null,
@v_SourceIP = null,
@v_SourcePort = null,
@v_CanonicalURI = null,
@v_Rate = null,
@v_RTPStatistics = null,
@var_y = null,
@var_m = null,
@v_db_name = null,
@var_tbl_begin = null,
@var_tbl = null;
END $$
DELIMITER ;
-- CREATE "UPDATE RECORD" PROCEDURE
DROP PROCEDURE IF EXISTS `update_radacct_record`;
DELIMITER $$
CREATE PROCEDURE `update_radacct_record`(
IN var_db_name VARCHAR(20),
IN var_AcctStopTime VARCHAR(20),
IN var_AcctStopDelay INT(12),
IN var_ConnectInfo_stop VARCHAR(32),
IN var_RTPStatistics VARCHAR(255),
IN var_AcctSessionId VARCHAR(255),
IN var_SipToTag VARCHAR(128),
IN var_SipFromTag VARCHAR(128)
)
BEGIN
-- SET VARIABLES
SET @v_db_name = var_db_name,
@var_tbl_begin = (SELECT set_radacct_table_name()),
@v_stoptime = var_AcctStopTime,
@var_month_formatted = (SELECT DATE_FORMAT(@v_stoptime, '%m')),
@var_yst = (SELECT DATE_FORMAT(@v_stoptime, '%Y')),
@var_tbl_month = CONCAT(@var_tbl_begin, @var_yst, @var_month_formatted),
@v_AcctStopTime = CAST(var_AcctStopTime AS DATETIME),
@v_AcctStopDelay = var_AcctStopDelay,
@v_ConnectInfo_stop = var_ConnectInfo_stop,
@v_RTPStatistics = var_RTPStatistics,
@v_AcctSessionId = var_AcctSessionId,
@v_SipToTag = var_SipToTag,
@v_SipFromTag = var_SipFromTag,
@var_tbl_cnt1 = (SELECT COUNT(TABLE_NAME) AS TBLCNT
FROM information_schema.tables
WHERE TABLE_SCHEMA = @v_db_name
AND TABLE_NAME = @var_tbl_month);
IF @var_tbl_cnt1 = 1 THEN
-- WE HAVE A TABLE BASED ON StopTime
-- SO LET'S TRY TO UPDATE
SET @updstmt1 = CONCAT("UPDATE ", @var_tbl_month, " SET
AcctStopTime = ?,
AcctSessionTime = UNIX_TIMESTAMP(?) - UNIX_TIMESTAMP(AcctStartTime),
AcctStopDelay = ?,
ConnectInfo_stop = ?,
RTPStatistics = ?,
Normalized = '0'
WHERE
AcctSessionId = ?
AND ((SipToTag = ? AND SipFromTag = ?) OR (SipToTag = ? AND SipFromTag = ?))
AND ConnectInfo_stop IS NULL;");
PREPARE update_rad1 FROM @updstmt1;
EXECUTE update_rad1 USING @v_AcctStopTime, @v_AcctStopTime,
@v_AcctStopDelay, @v_ConnectInfo_stop, @v_RTPStatistics,
@v_AcctSessionId, @v_SipToTag, @v_SipFromTag,
@v_SipFromTag, @v_SipToTag;
SET @updatedrows = (SELECT ROW_COUNT()),
@updstmt1 = null;
DEALLOCATE PREPARE update_rad1;
ELSE
SET @updatedrows = 0;
END IF;
IF @updatedrows = 0 THEN
-- UPDATE LAST MONTH'S TABLE BASED ON var_AcctStopTime
SET @var_prev_month = (SELECT DATE_FORMAT(DATE_ADD(@v_stoptime, INTERVAL -1 MONTH), '%Y%m')),
@var_tbl_pmonth = CONCAT(@var_tbl_begin, @var_prev_month),
@var_tbl_cnt2 = (SELECT COUNT(TABLE_NAME) AS TBLCNT
FROM information_schema.tables
WHERE TABLE_SCHEMA = @v_db_name
AND TABLE_NAME = @var_tbl_pmonth);
IF @var_tbl_cnt2 = 1 THEN
-- UPDATE PREVIOUS MONTH TABLE
SET @updstmt2 = CONCAT("UPDATE ", @var_tbl_pmonth, " SET
AcctStopTime = ?,
AcctSessionTime = UNIX_TIMESTAMP(?) - UNIX_TIMESTAMP(AcctStartTime),
AcctStopDelay = ?,
ConnectInfo_stop = ?,
RTPStatistics = ?,
Normalized = '0'
WHERE
AcctSessionId = ?
AND ((SipToTag = ? AND SipFromTag = ?) OR
(SipToTag = ? AND SipFromTag = ?));");
PREPARE update_rad2 FROM @updstmt2;
EXECUTE update_rad2 USING @v_AcctStopTime, @v_AcctStopTime,
@v_AcctStopDelay, @v_ConnectInfo_stop, @v_RTPStatistics,
@v_AcctSessionId, @v_SipToTag, @v_SipFromTag,
@v_SipFromTag, @v_SipToTag;
SET @updatedrows = (SELECT ROW_COUNT()),
@updstmt = null;
DEALLOCATE PREPARE update_rad2;
ELSE
SET @updatedrows = 0;
END IF;
END IF;
-- CLEAN UP
SET @v_AcctStopTime = null,
@v_AcctStopDelay = null,
@v_ConnectInfo_stop = null,
@v_RTPStatistics = null,
@v_AcctSessionId = null,
@v_SipToTag = null,
@v_SipFromTag = null,
@v_db_name = null;
END $$
DELIMITER ;
-- CREATE "MEDIAPROXY RECORD UPDATE" PROCEDURE
DROP PROCEDURE IF EXISTS `update_raddact_record_mediaproxy`;
DELIMITER $$
CREATE PROCEDURE `update_raddact_record_mediaproxy`(
IN var_db_name VARCHAR(20),
IN var_AcctSessionTime int(12),
IN var_AcctInputOctets bigint(12),
IN var_AcctOutputOctets bigint(12),
IN var_SipUserAgents VARCHAR(255),
IN var_SipCodecs VARCHAR(255),
IN var_SipApplicationType VARCHAR(255),
IN var_MediaInfo VARCHAR(32),
IN var_Normalized ENUM('0','1'),
IN var_AcctSessionId VARCHAR(255),
IN var_SipToTag VARCHAR(128),
IN var_SipFromTag VARCHAR(128)
)
BEGIN
-- SET VARIABLES
SET @var_tbl_begin = (SELECT set_radacct_table_name()),
@var_prev_month = (SELECT DATE_FORMAT(DATE_ADD(CURRENT_DATE, INTERVAL -1 MONTH), '%Y%m')),
@var_current_month = (SELECT DATE_FORMAT(CURRENT_DATE, '%Y%m')),
@var_tbl = CONCAT(@var_tbl_begin, @var_current_month),
@var_tbl_prev_month = CONCAT(@var_tbl_begin, @var_prev_month),
@v_AcctSessionTime = var_AcctSessionTime,
@v_AcctInputOctets = var_AcctInputOctets,
@v_AcctOutputOctets = var_AcctOutputOctets,
@v_SipUserAgents = var_SipUserAgents,
@v_SipCodecs = var_SipCodecs,
@v_SipApplicationType = var_SipApplicationType,
@v_MediaInfo = var_MediaInfo,
@v_Normalized = var_Normalized,
@v_AcctSessionId = var_AcctSessionId,
@v_SipToTag = var_SipToTag,
@v_SipFromTag = var_SipFromTag,
@v_na = 'n/a',
@v_dbname = var_db_name,
@updatedrows = 0,
@var_tbl_cnt1 = (SELECT COUNT(TABLE_NAME) AS TBLCNT
FROM information_schema.tables
WHERE TABLE_SCHEMA = @v_dbname
AND TABLE_NAME = @var_tbl),
@var_tbl_cnt2 = (SELECT COUNT(TABLE_NAME) AS TBLCNT
FROM information_schema.tables
WHERE TABLE_SCHEMA = @v_dbname
AND TABLE_NAME = @var_tbl_prev_month),
@proc_query = CONCAT("CALL proc_update_raddact_record_mediaproxy (?,?,?,?,?,?,?,?,?,?,?,?,?)");
PREPARE proc_rad_stmt FROM @proc_query;
IF @var_tbl_cnt1 = 1 THEN
-- FOR THE CURRENT MONTH
EXECUTE proc_rad_stmt USING @var_tbl, @v_AcctSessionTime,
@v_AcctInputOctets, @v_AcctOutputOctets,
@v_SipUserAgents, @v_SipCodecs, @v_SipApplicationType,
@v_MediaInfo, @v_Normalized, @v_AcctSessionId,
@v_SipToTag, @v_SipFromTag, @v_dbname;
END IF;
IF @updatedrows = 0 AND @var_tbl_cnt2 = 1 THEN
-- FOR THE PREVIOUS MONTH
EXECUTE proc_rad_stmt USING @var_tbl_prev_month, @v_AcctSessionTime,
@v_AcctInputOctets, @v_AcctOutputOctets,
@v_SipUserAgents, @v_SipCodecs, @v_SipApplicationType,
@v_MediaInfo, @v_Normalized, @v_AcctSessionId,
@v_SipToTag, @v_SipFromTag, @v_dbname;
IF @var_tbl_cnt1 = 1 AND @updatedrows = 0 THEN
-- FOR THE CURRENT MONTH WITH SipToTag = 'n/a'
EXECUTE proc_rad_stmt USING @var_tbl, @v_AcctSessionTime,
@v_AcctInputOctets, @v_AcctOutputOctets,
@v_SipUserAgents, @v_SipCodecs, @v_SipApplicationType,
@v_MediaInfo, @v_Normalized, @v_AcctSessionId,
@v_na, @v_SipFromTag, @v_dbname;
IF @var_tbl_cnt2 = 1 AND @updatedrows = 0 THEN
-- FOR THE PREVIOUS MONTH WITH SipToTag = 'n/a'
EXECUTE proc_rad_stmt USING @var_tbl_prev_month, @v_AcctSessionTime,
@v_AcctInputOctets, @v_AcctOutputOctets,
@v_SipUserAgents, @v_SipCodecs,
@v_SipApplicationType, @v_MediaInfo, @v_Normalized, @v_AcctSessionId,
@v_na, @v_SipFromTag, @v_dbname;
END IF;
END IF;
END IF;
DEALLOCATE PREPARE proc_rad_stmt;
-- CLEAN UP
SET @var_current_month = null,
@var_db_name = null,
@var_tbl_begin = null,
@var_tbl = null,
@var_tbl_cnt = null,
@var_prev_month = null,
@var_tbl_prev_month = null,
@v_AcctSessionTime = null,
@v_AcctInputOctets = null,
@v_AcctOutputOctets = null,
@v_SipUserAgents = null,
@v_SipCodecs = null,
@v_SipApplicationType = null,
@v_MediaInfo = null,
@v_Normalized = null,
@v_AcctSessionId = null,
@v_SipFromTag = null,
@v_SipToTag = null,
@v_na = null,
@v_dbname = null;
END $$
DELIMITER ;
-- CREATE SUPPORT PROCEDURE FOR "update_raddact_record_mediaproxy"
DROP PROCEDURE IF EXISTS `proc_update_raddact_record_mediaproxy`;
DELIMITER $$
CREATE PROCEDURE `proc_update_raddact_record_mediaproxy`(
IN var_tblname VARCHAR(50),
IN var_AcctSessionTime int(12),
IN var_AcctInputOctets bigint(12),
IN var_AcctOutputOctets bigint(12),
IN var_SipUserAgents VARCHAR(255),
IN var_SipCodecs VARCHAR(255),
IN var_SipApplicationType VARCHAR(255),
IN var_MediaInfo VARCHAR(32),
IN var_Normalized ENUM('0','1'),
IN var_AcctSessionId VARCHAR(255),
IN var_SipToTag VARCHAR(128),
IN var_SipFromTag VARCHAR(128),
IN var_dbname VARCHAR(20)
)
BEGIN
-- TABLENAME VARIABLE
SET @var_tbl = var_tblname,
@var_db_name = var_dbname,
@var_tbl_cnt = (SELECT COUNT(TABLE_NAME) AS TBLCNT
FROM information_schema.tables
WHERE TABLE_SCHEMA = @var_db_name
AND TABLE_NAME = @var_tbl);
IF @var_tbl_cnt = 0 THEN
-- TABLE DOESN'T EVEN EXISTS, SO RETURN 0
SET @rcnt = (SELECT 0);
ELSE
SET @radupdstmt = CONCAT("UPDATE ", @var_tbl, " SET
AcctSessionTime = AcctSessionTime + IF(ConnectInfo_stop IS NULL, ?, 0),
AcctStopTime = DATE_ADD(AcctStartTime, INTERVAL AcctSessionTime SECOND),
AcctInputOctets = AcctInputOctets + ?,
AcctOutputOctets = AcctOutputOctets + ?,
SipUserAgents = ?,
SipCodecs = ?,
SipApplicationType = ?,
MediaInfo = ?,
Normalized = ?
WHERE
AcctSessionId = ?
AND SipToTag = ? AND SipFromTag = ?;");
PREPARE update_rad FROM @radupdstmt;
SET @v_AcctSessionTime = var_AcctSessionTime,
@v_AcctInputOctets = var_AcctInputOctets,
@v_AcctOutputOctets = var_AcctOutputOctets,
@v_SipUserAgents = var_SipUserAgents,
@v_SipCodecs = var_SipCodecs,
@v_SipApplicationType = var_SipApplicationType,
@v_MediaInfo = var_MediaInfo,
@v_Normalized = var_Normalized,
@v_AcctSessionId = var_AcctSessionId,
@v_SipToTag = var_SipToTag,
@v_SipFromTag = var_SipFromTag;
EXECUTE update_rad USING @v_AcctSessionTime, @v_AcctInputOctets, @v_AcctOutputOctets,
@v_SipUserAgents, @v_SipCodecs, @v_SipApplicationType,
@v_MediaInfo, @v_Normalized, @v_AcctSessionId, @v_SipToTag, @v_SipFromTag;
SET @rcnt = (SELECT ROW_COUNT());
DEALLOCATE PREPARE update_rad;
END IF;
END $$
DELIMITER ;
/*
-- TEST PROCEDURE THAT INSERTS A RECORD
CALL insert_radacct_record (
'radius','3c3b5ff12bf2-m5udeydrjsuw@snom320-000413241247', '5af53194787eccf1',
'adi@umts.ro', 'adi@umts.ro', '83.149.75.105', '5060', '2006-12-10 12:09:19',
'0', '0', '0', '0', 'sip:3333@umts.ro=3Buser=3Dphone',
'sip:adi@umts.ro', '200', 'Sip-Session', '', '', '0', '0', '200', 'Invite',
'sip:3333@vm01.dns-hosting.info=3Buser=3Dphone', 'as5664a60b', '27qems1o2j',
'208005169', '81.23.228.147', '5060',
'sip:3333@vm01.dns-hosting.info=3Buser=3Dphone', '', ''
);
-- TEST PROCEDURE THAT UPATES A RECORD WITH MEDIAPROXY INFORMATION
CALL update_raddact_record_mediaproxy (
'radius','3','5896','7140','snom320/5.2 + Asterisk', 'GSM', 'Audio', '', '0',
'3c3b5ff12bf2-m5udeydrjsuw@snom320-000413241247', 'as5664a60b','27qems1o2j'
);
-- TEST PROCEDURE THAT UPATES A RECORD
CALL update_radacct_record (
'radius','2006-12-10 12:09:21', '0', '', 'n/a',
'3c3b5ff12bf2-m5udeydrjsuw@snom320-000413241247', 'as5664a60b', '27qems1o2j'
);
*/