root/doc/RATING.txt

Revision 1086, 24.3 kB (checked in by Adrian Georgescu <ag@…>, 2 days ago)

More clarity about destination id lookup

Line 
1
2CDRTool rating engine
3---------------------
4
5CDRTool provides on-the-fly rating of CDRs from multiple data-sources like
6OpenSER, Asterisk or Cisco gateways based on an easy to build rating plan,
7which can be imported from external data sources.
8
9A Call Detail Record (CDR) is one record from the radius radacct table. The
10CDR record contains all information related to a session, like session
11duration, calling, called party and media information. The rating engine
12calculates the price of the session, which is applied in real-time to the
13web output and saved to the database containing the CDRs.
14
15Based on exceptions, different rates may be applied per caller party
16identified by source IP, domain or subscriber.
17
18Rating is applied only after the call has ended. CDRTool considers that a
19call has ended when there is a stop time. In case of missing BYEs, CDRTool
20relies on the fact that MediaProxy will update the CDR with the proper stop
21time information based on the last moment the media stream passed through
22the media proxy.
23
24The rates are linked with profiles corresponding with different time of the
25day, day of the week or holidays. For rating calls, which span multiple
26profiles, the right rate is selected and applied for the call duration
27within each profile. Each customer may be assigned its own dedicated rating
28plans destination id and names. Chained profiles are possible to enable
29exception based rating. Multiple customers may share a common rate list,
30while some destinations may be rated differently, only the differences must
31be provisioned. Multiple time zones are supported for multiple billing
32parties hosted on the same platform.
33
34
35Rating logic
36------------
37
38The following steps are performed to rate a CDR:
39
401. Determination of application type
412. Determination of the billing party
423. Determination of the destination id
434. Determination of the costs
44
45Each step must succeed in order to calculate the price for the session. The
46steps are described in detail below.
47
48
491. Determination of application type
50------------------------------------
51
52The only supported application type is 'audio'.
53
54
552. Determination of the billing party
56-------------------------------------
57
58CDRTool identifies the rating plan associated with a session based on a
59billing party entity, which is calculated on the fly. The calculus is based
60on the first successful match of the BillingPartyId field from the CDR
61database (radacct.UserName for radius data sources) in the following order:
62
631. SIP account user@domain
642. SIP domain of the SIP account
653. Source IP of the SIP session
664. Default (when none of the above matches)
67
68The longest match is done against entries present in the billing_customers
69table. The match yields a set of profiles to be used further depending on
70the type of session and day of the week.
71
72The billing_customers table field that matches the Source IP is called
73gateway. Do not use hostnames for this field. "gateway" or "trusted peer"
74terms are used interchangebly in this document. They both relate to the
75source IP address that generated the SIP session.
76
77
783. Determination of the destination id
79--------------------------------------
80
81CDRTool identifies the destination for which to perform the rating based on
82one of the destination fields from the accounting table. The destination
83field is taken from the first non-empty field in this order:
84
851. CanonicalURI (the destination after all lookups inside the SIP Proxy)
862. SipTranslatedRequestURI (the Request URI as presented by the SIP UA)
873. CalledStationId (the content of the To header)
88
89The CanonicalURI is preferred because the destination field must contain the
90real SIP destination after all possible lookups performed by the SIP Proxy
91as this is something reliable and the dialing user cannot control it.
92OpenSER must be configured to send CanonicalURI Radius attribute when doing
93accounting (instructions are available in INSTALL.txt).
94
95The destination id is then calculated based on the longest match of this
96destination field in the billing_destinations table and the billing party.
97
98The longest match for the chosen destination field is performed by the
99E164_Europe class from cdr_generic.php. It assumes the destination always
100starts with a zero for a national call and with double zero for an
101international call. If your dialing plan is different you must design a
102custom class and function to and defined in global.inc as follows:
103
104$CDRTool['normalize']['E164class']='MyE164Class';
105
106For an example see E164_USA class from cdr_generic.php that matches American
107dialing plan.
108
109
1104. Determination of one time and recurrent costs
111------------------------------------------------
112
113The following steps are taken to rate the calls terminated to PSTN based on
114the destination id and the billing party found in previous steps.
115
1161. Lookup the billing Profile in cdrtool.billing_customers table in the
117   following order: subscriber,domain,gateway (based on $this->dayofweek):
118   (as explained in "Determination of the billing party" above)
119
120   - profile_name1 matches week days [1-5]
121   - profile_name1_alt matches week days [1-5] if no rates for profile_name1
122     are found
123   - profile_name2 matches week-ends [6-0]
124   - profile_name2_alt matches week-ends [6-0] if no rates for profile_name2
125     are found
126   - profile_name2 matches also holidays from billing_holidays table
127   
128   The week starts with 0 (Sunday) and ends with 6 (Saturday)
129
1302. Using the profile_name found, lookup the rate_name based
131   on $this->hourofday in cdrtool.billing_profiles table
132
133   If no rate_name is found for the given profiles a second set of profiles
134   are used, profile_name1_alt and profile_name2_alt.
135
136   - the day may be split in maximum 4 periods
137   - the days starts with hour 0 and ends with hour 24
138   - rate_name1 defines the first interval after hour 0
139   - rate_name2 defines the first interval after rate_name1
140   - rate_name3 defines the first interval after rate_name2
141   - rate_name4 defines the first interval after rate_name3
142
143   When the hour matches an interval use the rate_nameX found to lookup the
144   rate in billing_rates, if no record is found use the rate called
145   'default'
146
1473. Lookup in the cdrtool.billing_rates table the record having same name
148   found at point 2 having billing_rates.destination = destination Id
149   and billing_rates.application = application type found in the steps above.
150
151   - return an array with all the rating values and the duration rated
152
153  No rate will be returned if no destination Id is found. Make sure each
154  possible destination has a corresponding Id and name in destinations
155  table.
156
1574. If the duration rated at point 3 is less than total call duration, apply
158   point 3 again for the remaining call duration in next profile.  A maximum
159   of 10 spans (different rates depending of time of day, day of the week)
160   can be calculated using this mechanism.
161
1625. Lookup the call rate based on time (peak/of-peak, day of week, holiday)
163
1646. Calculate the call Price based on duration. In global.inc there are
165   several variables that affect how the price is calculated.  These
166   settings are global per CDRTool installation but some can be overwritten
167   with per customer values in the billing_customers table.
168
169   $RatingEngine=array(
170           "priceDenominator"        => 10000, // Rates units (global setting)
171           "priceDecimalDigits"      => 4,     // Decimal information (global setting)
172           "minimumDurationCharged"  => 0,     // Rate a minimum of X seconds (per customer)
173           "minimumDuration"         => 0,     // Minimum duration to rate, if call duration is shorter the price is zero (per customer)
174           "durationPeriodRated"     => 60     // Rate is per 60 seconds (global setting)
175           "trafficSizeRated"        => 1024,  // Default we rate per 1 MB (global setting)
176           "reportMissingRates"      => 0      // Send emails to administrator in case of missing rates
177            );
178
179   Pricing formula
180   ---------------
181
182   if min_duration then
183           minimumDurationCharged = min_duration
184   else if minimumDurationCharged set in global inc
185           use minimumDurationCharged from global.inc
186   else
187           minimumDurationCharged = call duration
188
189   if increment then
190                durationForRating = round to the next increment
191   else
192        durationForRating = call duration
193
194   if durationForRating >= minimumDurationCharged then
195                Price = connectCost/priceDenominator+
196           durationRate*durationForRating/durationPeriodRated/priceDenominator+
197           trafficRate/priceDenominator*(inputTraffic+outputTraffic)/8+
198           applicationRate/priceDenominator
199   else
200        Price = 0
201
202
203   ENUM discounts
204   --------------
205
206   The rating engine can apply a discount associated with the ENUM top
207   level domain that returned the final destination.
208
209   Price = Price - Price * ENUM discount /100
210
211   To apply ENUM based discounts, the ENUM TLD must be saved with each CDR
212   and the TLDs with their corespondent discounts must be provisioned in the
213   Rating tables section. See ENUM TLD discounts section for more
214   information.
215
216
2178. Save the calculated price, Billing Party and Destination Id for each call
218   in the CDRs. Having the price stored in database, it is possible to build
219   statistics to display consolidated revenues per country code, network or
220   subscriber.
221       
222   Update the normalized caller and destination for each CDR.
223 
224
225Importing and exporting of rating files
226---------------------------------------
227
228There are different data files needed for rating CDRs. The data files are
229imported into corresponding MySQL tables. The files must be uploaded to
230/var/spool/cdrtool directory.  To load the files into the database run
231the following command:
232
233/var/www/CDRTool/scripts/importRatingTables.php
234
235The import script knows to import the files only once so you may dump
236several files there and safely run the import script from cron. The import
237script detects whether the files have been imported by building a unique key
238out of the filename and the hash of the file content. So you may use the
239same filenames as long as the content differs and viceversa. If the import
240file has changed any records, the rating engine is automatically instructed
241to reload the changes.
242
243Sample csv files are found in the setup directory. The CSV field order is
244described in setup/*.csv sample files. The first element on each line
245specifies the operation will be performed with the current record. The
246operation can be 2 (update/insert), 1 (insert) or 3 (delete).
247
248The updates are performed based on a unique key present in each table:
249
250billing_customers     - cust_idx      (gateway,domain,subscriber)
251destinations          - cust_dest_idx (gateway,domain,subscriber,dest_id)
252billing_profiles      - profile_idx   (gateway,domain,subscriber,name)
253billing_rates         - rate_idx      (gateway,domain,subscriber,name,destination,application)
254billing_rates_history - rate_idx      (gateway,domain,subscriber,name,destination,application,startDate,endDate)
255
256The content of the rating tables can be exported in the Rating tables page.
257
258The import script detects the type of file to import based on its filename.
259
260The filename must comply with the following naming convention:
261
2621. Must start with the name of the table without the billing_
2632. May optionally contain extra characters after the name
2643. Must end with .csv extension
265
266Examples:
267
268- rates.csv or rates20061201.cvs will be loaded into the rates table
269- profiles.csv or profiles20061201.cvs will be loaded into the profiles table
270- destinations200601.csv will be loaded in the destinations table
271- ratesHistory200801.csv will be loaded in the rates_history table
272
273Do not use 'billing_' prefix in front of the file name.
274
275It is advisable to name the files in a consistent manner like tableYYYYMMDD.csv
276
277The results of the import operation is logged in the database and can be
278viewed in the Log section of the web interface and the syslog.
279
280
281MySQL schema
282------------
283
284To see the rating tables and their structures connect to the cdrtool
285database using mysql client.
286
287Run 'show tables' and 'describe table_name':
288 
289billing_customers
290+-------------------+
291| Field             |
292+-------------------+
293| id                |
294| gateway           |
295| domain            |
296| subscriber        |
297| profile_name1     |
298| profile_name1_alt |
299| profile_name2     |
300| profile_name2_alt |
301| timezone          |
302| increment         |
303| min_duration      |
304| country_code      |
305+-------------------+
306
307billing_profiles
308+------------+
309| Field      |
310+------------+
311| id         |
312| gateway    |
313| domain     |
314| subscriber |
315| name       |
316| rate_name1 |
317| hour1      |
318| rate_name2 |
319| hour2      |
320| rate_name3 |
321| hour3      |
322| rate_name4 |
323| hour4      |
324+------------+
325
326billing_rates
327+-----------------+
328| Field           |
329+-----------------+
330| id              |
331| gateway         |
332| domain          |
333| subscriber      |
334| name            |
335| destination     |
336| durationRate    |
337| trafficRate     |
338| application     |
339| connectCost     |
340+-----------------+
341
342billing_rates_history
343+-----------------+
344| Field           |
345+-----------------+
346| id              |
347| gateway         |
348| domain          |
349| subscriber      |
350| name            |
351| destination     |
352| durationRate    |
353| trafficRate     |
354| application     |
355| connectCost     |
356| startDate       |
357| endDate         |
358+-----------------+
359
360destinations
361+------------+
362| Field      |
363+------------+
364| id         |
365| gateway    |
366| domain     |
367| subscriber |
368| dest_id    |
369| dest_name  |
370| asr        |
371+------------+
372
373billing_holidays
374+-------+
375| Field |
376+-------+
377| day   |
378+-------+
379
380prepaid
381+------------------+
382| Field            |
383+------------------+
384| id               |
385| account          |
386| balance          |
387| change_date      |
388| call_lock        |
389| last_call_price  |
390| destination      |
391| active_sessions  |
392| maxsessiontime   |
393| call_in_progress |
394| session_counter  |
395+------------------+
396
397prepaid_history
398+----------+
399| Field    |
400+----------+
401| id       |
402| username |
403| domain   |
404| action   |
405| number   |
406| value    |
407| balance  |
408| date     |
409+----------+
410
411billing_enum_tlds
412+-------------+
413| Field       |
414+-------------+
415| id          |
416| gateway     |
417| domain      |
418| subscriber  |
419| enum_tld    |
420| e164_regexp |
421| discount    |
422+-------------+
423
424
425Web based rating tables management
426----------------------------------
427
428The rating tables can be edited from the web, click on Rating tables link.
429One may insert/update/delete records or apply changes on selections. For
430example it is possible to increase with XX units the rate for a specific
431destination.
432
433Numeric fields support mathematical operators [+-*/], one may update
434using absolute or relative values the fields in the rating tables.
435
436The rates may be copied in bulk and start quickly working with a fresh
437new rating table. Select in the Rates PSTN table by filtering on rate
438name. A new button appears which allows the copy of all selected rates
439into a new set. The rates are copied under the old rate id with _N
440suffix where N is the next available number for which same rate id does
441not exist.
442
443The content of the rating tables can be exported into comma separated
444files. The CSV format has the same structure as the import file, is
445fairly easy to modify an exported batch file into an external
446application and load it back into CDRTool.
447
448Note
449
450When $RatingEngine['split_rating_table'] is true, after changing the rates
451in the web interface or by importing them, you must run the script
452scripts/splitRatingTables.php to split the central billing_rates table into
453individual tables for each rate id. You do not need this feature if you have
454less than 100K rates in your system.
455
456
457ENUM TLD discounts
458------------------
459
460To apply discounts based on ENUM certain conditions must be met.
461
4621. The username part of the result of the ENUM lookup must be numeric and
463   contain a fully qualified E164 number, optional with a numeric prefix.
464
465   Example:
466
467   The user dialed 020800001, the SIP Proxy has normalized the destination
468   based on local policy by stripping 0 and adding country code 31 to obtain
469   the fully qualified E164 number 3120800001, than it performed an ENUM
470   lookup under top level domain e164.example.com for +3120800001. The ENUM
471   server responsable for e164.example.com returned a response with the
472   destination sip:01131208000011@gateway.example.com
473
474   In the CDR, ENUMtld is stored as e164.example.com
475
476   The rating logic checks if the TLD exists in the billing_enum_tlds table.
477   If it does, the rating engine tries to match the regexp field against the
478   username part of the destination from the ENUM response, which has been
479   saved in the Canonical URI. The match must return a fully qualified E164
480   number otherwise the call is considered to have ended to a no E164
481   destination and the call will be free of charge.
482
4832. In the ENUM tld table you must provision (for the example above):
484
485    - TLD: e164.example.com
486    - Regexp: 011([1-9][0-9]{7,})
487    - Discount: 25
488
489   The paranthezis of the Regexp field indicate the E164 number returned by
490   the match and discount is a percentage that will be substracted form the
491   total price of the call. The formula is described in the PSTN rating
492   section.
493
494
495Reloading rating tables
496-----------------------
497
498The rating engine loads some of the rating tables in the memory, when the
499tables change a reload is needed. Reload of rating tables is possible
500without stopping the daemon by connecting to it and issuing the reload
501command. The init.d script can also be used for reloading the rating engine
502with the current values from the rating database.
503
504There are 3 ways of reloading the rating tables:
505
506a. Each change executed in the WEB interface for rate management may update
507the rating tables. If there is a change made to the database that requires a
508reload the link 'Reload rating tables' appears in red color on web page.
509Click on the link to execute the reload.
510
511b. Telnet to the IP address and port number specified for the Rating engine
512in global.inc. Type help to see the list of commands available. Locate the
513reload rates command and execute it followed by \n. You may see the result
514of the command in syslog. The results displayed by syslog will show how many
515entries have been reloaded from the rating table.
516
517c. Run /etc/init.d/cdrtool reload command
518
519
520Troubleshooting
521---------------
522
523To examine the rate information for a rated call click on the Id field on
524the leftmost column. (Java script support in browser is required). A blue
525area will open under the CDR line containing more information about the SIP
526session.
527
528If you see no price in the CDR or no rating information appears in the call
529details it means that either no destination was found in the destinations
530table or no rate has been associated with that destination. Make sure that
531for each entry in the destinations table there is a corespondent entry in
532the rates table. CDRTool rating engine can send warning emails if it finds
533missing entries in the rating tables if the system where CDRTool runs is
534properly configured to send emails and the e-mail notification addresses are
535set in global.inc:
536 
537$CDRTool['provider']['toEmail']  = "support@example.com";
538$CDRTool['provider']['bccEmail'] = "cdrtool@example.com";
539
540To log to syslog about missing rates or incorrect setup of the rating tables
541enable 'reportMissingRates' in $CDRTool['rating'] section of global.inc
542
543
544Renormalizing CDRs and historical rating
545----------------------------------------
546
547Sometime is useful to be able to change the rates for calls that have been
548already normalized and rated, for example after changing the rating tables
549you wish to apply the changes for the previous month for a customer.
550
551To re-rate the CDRs do the following:
552
5531. Change the current rates by using cvs files/WEB interface or add rates
554   valid for specific dates/destinations in the rates_history table
555
5562. Re-normalize the calls to be re-rated by either selecting ReNormalize
557   check-box in the search screen or by changing the Normalized field in the
558   CDR MySQL table (e.g. radacct):
559
560   Examples:
561
562   a) Re-rate calls for this month (2004-12) SIP domain example.com:   
563   UPDATE radacct set Normalized = '0' where Realm = 'example.com'
564   and AcctStartTime >= '2004-12-01'
565
566   b) Re-rate calls for SIP subscriber sip01@example.com:       
567   UPDATE radacct set Normalized = '0' where UserName = 'sip01@example.com'
568
5693. Apply rating again using command:
570
571   /var/www/CDRTool/scripts/normalize.php
572
573Notes
574
575Renormalization process can take long time during which your database
576(radacct table) will be intermitently locked. Perform this operation
577only during low traffic periods.
578
579It is advisable to re-rate only the CDRs for destinations that have
580different rates. To do this, select a filter in the CDR search screen, if
581the selection is right re-run the query by selecting Re-normalize button.
582
583After renormalization, the monthly usage information used by the quota
584system will be out of date. At the next run of the quotaCheck script, a full
585table scan will be performed. See QuoatSystem.txt for more information about
586quota.
587
588Holidays must be added as individual days YYYY-MM-DD in table
589billing_holidays. The profile applied for holidays is the same as for
590week-ends. Holidays are global and cannot be specified per customer.
591
592Renormalization process does not affect the balance of prepaid users.
593Prepaid is a real time un-reversible process, it goes in one direction. The
594prepaid balance is changed only by placing a call or adding credit to it.
595There are several reasons for this:
596
597- The balance before and after each CDR is not known to be able to roll it
598  back at a later time
599- Re-rating correctly is mathematically not possible for prepaid users that
600  have calls in progress
601- If the prices are higher than previously debited and end up with a
602  negative balance, the software cannot force the user to pay more
603  retroactively
604
605Re-normalization for the purpose of re-rating is useful only for postpaid
606accounts where you send an invoice at the end of the month and your can
607change things back and forth. If you need to perform manual credit/debit
608operations to some prepaid users because of faulty pricing, you can edit in
609CDRTool in the prepaid table the balance by using + or -.
610
611
612Known limitations
613-----------------
614
615The rating engine does not calculate prices based on the outbound carriers
616or outbound gateways, the rating plan is is assigned by the calling party
617and not by called party.
618
619Price discounts (except those based on ENUM tld) must be applied outside
620CDRTool, in the billing system that prints the actual invoices. CDRTool has
621no possibility to rate only calls after X minutes per month for subscriber
622Y, all calls are rated uniformly.
623
624
625Performance
626-----------
627
628Rating is part of the normalization process that happens every time a query
629is executed in the web interface or when the rating engine is contacted by
630the SIP Proxy or by the User Agent that performs the prepaid application.
631
632The following tests have been performed between two machines with 3 GHz CPU
633and 1 GB memory located on the same LAN having a round trip time of 0.2 ms.
634
635The rating tables have been populated durring the tests with:
636
637Aug 11 11:25:43 sip03 CDRTool[4945]: Loaded 8135 destinations
638Aug 11 11:25:43 sip03 CDRTool[4945]: Loaded 6 profilesPSTN
639Aug 11 11:25:43 sip03 CDRTool[4945]: Loaded 4 holidays
640Aug 11 11:25:44 sip03 CDRTool[4945]: Loaded 7273 prepaid accounts
641
642Tests results for the postpaid application:
643
644Clients         Rating command                  Execution speed
645----------------------------------------------------------------
6461               ShowPrice                       390/s per client
6475               ShowPrice                       100/s per client
64810              ShowPrice                       60/s per client
649
650
651Tests results for the prepaid application
652
653Clients         Rating command                  Execution speed
654----------------------------------------------------------------
6551               MaxSessionTime/DebitBalance     250/s per client
6565               MaxSessionTime/DebitBalance     80/s per client
65710              MaxSessionTime/DebitBalance     40/s per client
658
659Client means either a SIP Proxy entity or a CDRTool server, which performs
660the normalization process.
661
662The rates are read directly from MySQL from version 6.1 instead of
663beeing cached as they are found based on a known index.
664
665To monitor the connections to the rating engin server telnet to
666the rating engine port and issse the ShowClients command. Example output:
667
668ShowClients
669
670Clients:
671
6721. 91.20.228.143:32837
6732. 85.1.86.71:57945
6743. 91.20.228.146:35098
6754. 91.20.228.150:34285
6765. 91.20.228.129:55090
6776. 91.20.228.164:34147
678
679Requests:
680
68112 requests from 91.20.228.129
68211 requests from 91.20.228.150
6838 requests from 85.11.86.71
6842 requests from 91.20.228.164
685
686Statistics:
687
688Total requests: 33
689Uptime: 169 seconds
690Load: 0.20/s
Note: See TracBrowser for help on using the browser.