#!/usr/bin/perl
# -*- perl -*-

=head1 NAME

Munin plugin to monitor the number of users and transactions in Kamailio using 'statistics' table.

=head1 APPLICABLE SYSTEMS

It requires MySQL 'statistics' table created in Kamailio database.
http://siremis.asipto.com/install-charts-panel/

=head1 CONFIGURATION

[kamailio*]
 user root
 group root
 env.mysql <optional-override-of-mysqladmin-path>
 env.mysqlauth -u<User> -p<Password>
 env.kamailiodb <kamailio data base>

It is most usual that root must run the mysql command.

=head2 Proxy config

use rtimer module to run periodically a route. In that route you insert the values in database.

SIP Proxy configuration file:

 loadmodule "rtimer.so"
 loadmodule "sqlops.so"
 loadmodule "cfgutils.so"
 ...
 modparam("rtimer", "timer", "name=tst;interval=300;mode=1;")
 modparam("rtimer", "exec", "timer=tst;route=8")
 modparam("sqlops","sqlcon","ca=>mysql://openser:openserrw@localhost/openser")
 ...
 route[8] {
  sql_query("ca",
  "insert into statistics (time_stamp,random,shm_used_size,shm_real_used_size,
  shm_max_used_size,shm_free_used_size,ul_users,ul_contacts) values ($Ts,
  $RANDOM,$stat(used_size),$stat(real_used_size),$stat(max_used_size),
  $stat(free_size),$stat(location-users),$stat(location-contacts))","ra");
 }

Note: second parameter of sql_query(...) is a single line. Next version, based on SIP-Router.org project will support string parameters broken in multiple lines.

=head2 Database

You have to create a new table in Kamailio (OpenSER) database:

CREATE TABLE `statistics` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `time_stamp` int(10) unsigned NOT NULL default '0',
  `random` int(10) unsigned NOT NULL default '0',
  `shm_used_size` int(10) unsigned NOT NULL default '0',
  `shm_real_used_size` int(10) unsigned NOT NULL default '0',
  `shm_max_used_size` int(10) unsigned NOT NULL default '0',
  `shm_free_used_size` int(10) unsigned NOT NULL default '0',
  `ul_users` int(10) unsigned NOT NULL default '0',
  `ul_contacts` int(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM;

Now all is ready for Kamailio (OpenSER), you can restart it.

=head1 BUGS

None known

=head1 AUTHOR

 Copyright 2012 - Voxtrot <www.voxtrot.com>
 Oussama Hammami <oussamacvoxtrot.com>

=head1 LICENSE

GPLv2

=head1 VERSION

  $Id: kamailio_transactions_users 2012-04-19 16:13 $

=head1 MAGIC MARKERS

  #%# family=manual
  #%# capabilities=autoconf

=cut

use strict;

my $MYSQL = $ENV{mysql} || "mysql";
my $COMMAND    = "$MYSQL $ENV{mysqlauth} $ENV{kamailiodb} -e 'select * from statistics order by id  desc limit 1\\G'";

my %WANTED = ( "ul_users"   => "users",
               "ul_contact" => "contacts", 
               "tm_active"  => "transactions", 
             );

my %VALUE = ( "users"        => 0,
              "contacts"     => 0,
              "transactions" => 0,
            );

my $arg = shift();

if ($arg eq 'config') {
    print_config();
    exit();
} elsif ($arg eq 'autoconf') {
    unless (test_service() ) {
        print "yes\n";
    } else {
        print "no\n";
    }
    exit 0;
}

open(SERVICE, "$COMMAND |")
  or die("Could not execute '$COMMAND': $!");

while (<SERVICE>) {
    my ($k, $v) = (m/(\w+).*?(\d+(?:\.\d+)?)/);
    next unless ($k);
    if (exists $WANTED{$k} ) {
	    $VALUE{$WANTED{$k}}=$v;
    }
}

close(SERVICE);

for my $key (keys %VALUE) {
    print ("$key.value $VALUE{$key}\n");
}

sub print_config {
    print ("graph_title Kamailio transactions and location\n");
    # Arguments to "rrdtool graph". In this case, tell it that the
    # lower limit of the graph is '0', and that 1k=1000 (not 1024).
    print("graph_args  --base 1000 --lower-limit 0\n");
    print("graph_vlabel user/transaction\n");
    print("graph_scale no\n");
    print("graph_category kamailio\n");
    print("graph_info The graph describes the number of users/transaction on kamailio.\n");

	print("users.label users\n");
    print("contacts.label contacts\n");
    print("transactions.label transactions\n");

    print("users.info Average sip users for the five minutes.\n");
    print("contacts.info Average sip contacts for the five minutes.\n");
    print("transactions.info Average sip transactions for the five minutes.\n");

    print("graph_order transactions  users contacts\n");

    print("users.type GAUGE\n");
    print("contacts.type GAUGE\n");
    print("transactions.type GAUGE\n");

    print("users.draw LINE1\n");
    print("contacts.draw LINE1\n");
    print("transactions.draw AREA\n");

    print("users.colour 00CCC9\n");
    print("contacts.colour 8498A0\n");
    print("transactions.colour E6D300\n");

    # Ensure min values (useful when using 'DERIVE' as 'type').
    print("users.min 0\n");
    print("contacts.min 0\n");
    print("transactions.min 0\n");
}


sub test_service {
    system ("$MYSQL --version >/dev/null 2>/dev/null");
    if ($? == 0)
    {
	system ("$COMMAND >/dev/null 2>/dev/null");
	if ($? == 0)
	{
	    print "yes\n";
	}
	else
	{
	    print "no (could not connect to mysql)\n";
	}
    }
    else
    {
	print "no (mysql not found)\n";
    }
    exit 0;
}
