Trunks Down and sending an Alert Email (anything like this available?)

discusz
Posts: 62
Member Since:
2007-02-22

This could be taken as a Feature request.

Is there away to send out an alert Email letting you know when a Trunk goes down, loses its registry. Something happened to all my SIP/IAX trunks (they were working late last nite) as I was tesing my Las Vegas DID with a friend who is iun vegas right now, this morning all my trnks could not register (babytel, FWD, Vegas, and Edmonton trunk) I made no changes on my firewall in ages. I could see the requests going out but nothing ever came back in.. I think my firewall lost its mind or something.. rebooted that and everything came up except babytel, they could not see my request making it to them except for my pings. He had me change my proxy for them sip server and it worked immediately., changed it it back and it worked on the old IP as well.

According to the Asterisk Info page on my box all the trunks were unreachable *yet I could ping them. (only thing that did not work would of been Outbond UDP I would guess)

Anyways is someone working on an Alert module that will send an EMAIL, SMS etc when a trunk goes down.

I may see if I can accomplish an alert module (pending time) if someone does not have one on the go.

I think this would be an invaluable tool. I knew something was wrong when my wife went to call Expedia to confirm out flight in about 10 hrs and we got all circuits are busy (that and I only had FWD setup for 8xx numbers and not mt PSTN or babytel (opps) but if I did i would have not really known my trunks were all down.

Anyways long winded..

Jim



sidimustaf
Posts: 28
Member Since:
2006-06-04
don't see it right not in CE version

If i'm allowed to say this,

I think that's the way where the TrixboxPRO version is headed, when i look at the status page, and see that they can see the exact status on your trunks.

I do believe, that that's the direction the the PRO and CC version is headed, and the not the CE version,

Taking not that FreeBPX is heading the other direction, maybe, u can ask those guys over there to add it as a scripted feature..

Or as your noted, roll up your sleeves, and start scripting away..
Nice idea anyway, i would sure like to have a feature like that....
but afterall, i'm not a coder, so wouldn't know where to start...

keep us up todate, if u find such tool, or coded one yourself..



mvsystems
Posts: 1120
Member Since:
2006-06-05
Sounds like you should

Sounds like you should submit a feature request to FreePbx for that.

--

Tim Booth FtOCC
MaineVoIP Systems
VisionCom
Portland, Maine



philippel
Posts: 700
Member Since:
2006-05-31
There is another thread

There is another thread requesting something similar and the discussion is to do this monitoring from inside your box or outside. If your box gets cut off, then you won't be able to get the message out.

FreePBX already does some monitoring of Trunks on the System Status page and this is done realtime when the status page is up. We plan on moving some of that into a daemon where the same information would be obtained to be passed to the status page when active, so it would be reasonable to allow that daemon to also provide errors and alerts. It's actually an extension to the Notification Panel. Today you can get emails about new module updates. That will become more general with other notifications as well. It's just a simple matter of developing the interface to allow you to setup what you want to hear about and the daemon that we discussed....

So ... as far as the direction that FreePBX is going (by reflection, CE) ... yes it is going that way and you can already see the beginnings of that in the System Status console with the Trunk info and the Notifications panel.

--

Philippe Lindheimer, FreePBX® Project Leader
http://freepbx.org - #freepbx on irc.freenode.net
http://freepbx.org/forums - The FreePBX® Forum
OTTS Training - Apr 27-29, Huntsville, AL



ddwyer
Posts: 401
Member Since:
2006-06-03
pull money from pocket

my suggestion is find a developer and pull cash from pocket and pay fro somebody to develop - give back to the community why should somebody else do this work for you for free?



techieg
Posts: 279
Member Since:
2006-06-13
Ironic and Contradicting

ddwyer - FYI, that is why it is called "opensource". If it gets done, it is for the benefit of us all. You asked "why should somebody else do this work for you for free?" but then tell the same person to do the work and provide it to others for free...ironic and contradicting. And somebody is bringing TB CE to you for free, I am quite sure you did not ask them why they did the work for you fo free. If you can help out, just do that, but if you can't then step aside for those who can.



mustardman
Posts: 1289
Member Since:
2006-06-18
In 0.27 of FOP they added

In 0.27 of FOP they added Timer Alarms (popup when a button timer exceeds a defined interval). Not sure exactly what this is but perhaps it could be used in conjunction with Linux monitoring software.



phonebuff
Posts: 445
Member Since:
2007-02-15
Monitoring ---

All, I use Nagios from a hosted server to watch my boxes. But I usally watch the FW and the Trixbox. Always figured that if I could not get to the boxes OS (ssh) then things were down. I actually like the idea of watching the status of the trunks.

For those of you not into Server Monitoring you also should check out a product called Servers Alive.

.........



discusz
Posts: 62
Member Since:
2007-02-22
I have being trying to write

I have being trying to write something.. but since I am heading to Las Vegas in about 4 hours this will have to wait until i get back.. I have already gotten to the point where I can get the status of a trunk via a perl script, I just have to add some logic in that if the trunk is down, check to see if there is actual internet connectivity (ping or what have you (ping gateway or even the voip providers sip/iax server)

My problem was not that my internet was down. something went weird.. all SIP/IAX trunks went down, i want to know about this. since I havea PSTN line still (I will never get rid of it in favor of a VOIP line) I will then call my cell or something like that.

here is some of the output I currently have.

perl trunkalert.pl
============================================================
SIP Trunk information
============================================================
There is 1 Registered sip trunks

============================================================
IAX2 Trunk information
============================================================
There are 2 Registered IAX2 trunks

its not much but not bad for a short while

This sort of function is definately needed (I can see in a business sense) its still a good thing to have for the casual user as well like me, I dont sell, build etc Trixbox's, jsut want to know my lines are working when I need them to be.

if anyone has any ides on getting this done fire them my way and I will see what I can do., this will more than likely be a cron even for the 1st method, or maybe someone will take this to then next level, a module for TrixBox



discusz
Posts: 62
Member Since:
2007-02-22
here is a quick test when i

here is a quick test when i take down my babytel SIP trunk (change the IP in /etc/hosts) so it wont register.

perl trunkalert.pl
============================================================
SIP Trunk information
============================================================
houston we have a problem
There is a sip trunk not registering

============================================================
IAX2 Trunk information
============================================================
There are 2 Registered IAX2 trunks

As soon as I change tghe /etc/hosts file back to the proper IP I have for my Babytel setup.. I quicking run my perl script and it will change to registered...

Next on to the Mail out function./ Right now this would probably work for 1 SIp and 1 IAX trunks once the email function is there..



discusz
Posts: 62
Member Since:
2007-02-22
well I have mail sort of

well I have mail sort of working when my SIP trunk goes down. (sending locally) its not sending to my normal account so I have to figure that one out.... 1am here, head to the airpoint in a couple of hours. . I might get a bit more work done before I leave.

jim



ddwyer
Posts: 401
Member Since:
2006-06-03
everybody is standing aside

everybody is standing aside that is the true irony of opensource. enough said



ocon
Posts: 1
Member Since:
2006-12-04
Use it as example

Take a look at this, this checks if your IP is still the same in DynDNS, than checks for 2 iax trunks and 2 sip trunks, in case of changes or errors, sends a notification Email, just use it as example and add it to cron or to /etc/cron.hourly

#!/bin/bash
#
# Este script verifica la IP publica actual, de ser distinta
# a la registrada en el Host Dinamico, la actualiza y manda
# un correo de Aviso con la Nueva IP.
# Tambien Verifica que los troncales SIP e IAX esten conectados
# en caso de algun error, envia correo de advertencia.
#
# Aqui se definen las Variables, ipact=IP externa, hostact es
# la IP configurada, SIP e IAX2, definen el estado de los
# troncales y cada troncal se define en sip1,sip2,iaxa,iaxb
#
ipact=`wget -q http://www.whatismyip.com/automation/n09230945.asp && cat n09230945.asp && rm -f n09230945.asp`
hostact=`host MyDYNDNSHOST | cut -d" " -f4`
sip=`asterisk -rx "sip show registry" | grep rh | awk '{print $4}'`
sip1=`echo $sip | awk '{print $1}'`
sip2=`echo $sip | awk '{print $2}'`
iax2=`asterisk -rx "iax2 show registry" | grep rh | awk '{print $5}'`
iaxa=`echo $iax2 | awk '{print $1}'`
iaxb=`echo $iax2 | awk '{print $2}'`
#
# Cotejar IP externa con IP definida
#
if [ "$ipact" != "$hostact" ]; then
echo "Ha habido un cambio en la ip, y se ha actualizado igual que el script" | mail myaccount@yahoo.com -s "Nueva IP $ipact"
wget http://USER:PASSWORD@members.dyndns.org/nic/update?hostname=MyDYNDNSHOST&myip=$ipact&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG > /dev/null
# Confirmar que sigue siendo la misma
else
echo "La IP sigue siendo $ipact"
fi
#
# Verificar estado de cada troncal VoIP
#
# SIP 1
#
if [ "$sip1" != "Registered" ]; then
echo "Error en Troncal SIP 1" | mail myaccount@yahoo.com -s "Error en Troncal SIP 1"
echo "Error en Troncal SIP 1"
else
echo "El Troncal SIP 1 esta Registrado"
fi
# SIP 2
if [ "$sip2" != "Registered" ]; then
echo "Error en Troncal SIP 2" | mail myaccount@yahoo.com -s "Error en Troncal SIP 2"
echo "Error en Troncal SIP 2"
else
echo "El Troncal SIP 2 esta Registrado"
fi
# IAX 1
if [ "$iaxa" != "Registered" ]; then
echo "Error en Troncal IAX 1" | mail myaccount@yahoo.com -s "Error en Troncal IAX 1"
echo "Error en Troncal IAX 1"
else
echo "El Troncal IAX 1 esta Registrado"
fi
# IAX 2
if [ "$iaxb" != "Registered" ]; then
echo "Error en Troncal IAX 2" | mail myaccount@yahoo.com -s "Error en Troncal IAX 2"
echo "Error en Troncal IAX 2"
else
echo "El Troncal IAX 2 esta Registrado"
fi



mustardman
Posts: 1289
Member Since:
2006-06-18
Has anyone used MON? I see

Has anyone used MON? I see it's a feature on Webmin but I haven't installed the daemon on the server. Considering it as we had Asterisk freeze on a box a few days ago and I'd like to get an email when that happens. Not sure if it could notify if a trunk stops responding.



discusz
Posts: 62
Member Since:
2007-02-22
That is pretty much what I

That is pretty much what I was writing the day/hours before I headed to Vegas.. My Vegas DID worked up untul Thursday nite. I believe it went down as I could not get through it would only ring busy, so I am will continue to work on this script as I had a few more Ideas I am going to add as well.

I may also look at MON as well, and see if that fits.

Jim



16again
Posts: 370
Member Since:
2007-03-04
the right way to go should

the right way to go should be imho to have asterisk snmp enabled. This way you can monitor things like current calls and trunk status in a snmp management machine, and do the alerting from there



discusz
Posts: 62
Member Since:
2007-02-22
I have completed this it

I have completed this it seems to work. even sending a SMS to my cell phone. I re-wrote it yet again. I would like to come up with a module to either read which trunks are setup right from the database.

right now I ahve 2 files setup (iaxtrunks and siptrunks) in /etc/asterisk the perl script I have reads these files and using this against the iax|sip registry and checks to see if the trunks are registered. if not an email is sent.

all you then do is create a cronevent to run this however much or little as you want.

if anyone wants a copy of this email jimh@nucleus.com and I will gladly email it out you.

Jim



lagreca
Posts: 123
Member Since:
2007-03-09
Jim, I would love a copy of

Jim,

I would love a copy of this script. I am a les.net customer (maybe not for much longer) and have been having problems with my DID and SIP registration failing. I would like to know about the problem when it happens, so I fix it before my customers have to tell me they can't get through to me.

Thanks!

--
Joe LaGreca
Founder & Owner, BIGnet Online
619-393-1733 Office
619-318-3246 Cell
www.BIGnetOnline.com



mustardman
Posts: 1289
Member Since:
2006-06-18
Not sure if it was addressed

Not sure if it was addressed in this thread but there is an option in FreePBX 2.3.x in trunk settings to run a custom AGI script in the event of a trunk failure. One of the uses for it as stated in the help text that pops up when you hover over it is to send email alerts. Just have to find or create that agi script.



discusz
Posts: 62
Member Since:
2007-02-22
Ya I took the easy route

Ya I took the easy route 1st. I want to get it working a lot better. The script only took about 20 mins or so to write. Plus most people ar enot running freepbx 2.3.x yet. I jsut upgraded to that yesterday so have not had a chance to look into that. I will today or tonite,



lagreca
Posts: 123
Member Since:
2007-03-09
Anyone have a sample script

Anyone have a sample script to use with the new trunk monitoring option? Maybe one that will email the status of all trunks when one goes down?



discusz
Posts: 62
Member Since:
2007-02-22
I am looking at doing an AGI

I am looking at doing an AGI script but have not had time.

for those who emailed me I am not ignoring you I have a few of you interested in this script so rather than emailing out I am going to setup a link on a website I will email out to everyone.



mustardman
Posts: 1289
Member Since:
2006-06-18
I found this on another

I found this on another site.
http://www.siliconvp.us/modules.php?name=Downloads&d_op=viewdownl...

It's not quite complete. I would imagine you can replace "RCTP" with the actual email address somehow otherwise add it to RCPT however that is done. I believe you put this in a file and put it in /var/lib/asterisk/agi-bin. I'm no expert on this stuff. Just doing some Googling. He also has routines for sending automated txt message, phone call, beeper etc. none of which would work if your phone lines are down.

Here is the relevant part of the script:

#!/bin/sh

# WRITTEN BY PAUL NORRIS, SILICON VALLEY PRODUCTS, 2005
# Use as you see fit, but leave my name in this file

/usr/lib/sendmail -oi $RCPT subject: T1 DOWN AUTOMATED MESSAGE
to: $RCPT
from: monitor
comment: the line below MUST BE EMPTY

The T1 phone circuit is down. This is an automated message.
Please follow these instructions:
Call Verizon Business at 866-822-9603 (or 800-828-4984 opt 1)
Report your voice T1 (PRI circuit) is down.
Your account number is: xxxxxxxxxxx
Have them do an RCF (remote call forward)
Send 516-555-1111 to 516-555-2222
The codes on their interface box in the computer room are:
PR-WIZ-XXXX-0001
32.HCGS.222222..NY
--------------------------
The folowing information is for PAUL NORRIS and NOT VERIZON
$stat
--------------------------
Your concerned support person
Paul Norris

END
done



kerryg
Posts: 6790
Member Since:
2006-05-31
If one of these options is

If one of these options is really good, please let me know and we will look into adding it into trixbox with a nice interface to configure it.

--

Kerry Garrison
http://www.VoipStore.com - http://3cxbook.com
(888) VOIPSTORE - (888) 864-7786



discusz
Posts: 62
Member Since:
2007-02-22
For those of you who want

For those of you who want this, I have gzipped it up. its a Perl file. all you need to do is download, gunzip it./ Follow the info in the actual perl file.

I will add to this when I have time again

I also want to maybe see if this works as an AGi script as well it might.. I just upgraded FreePBX the other day but have not had a chance to try this.

here is the link to my perl script

http://www.hribnak.com/trunkalerts.pl.gz

If anyone has any questions email me at jimh AT nucleus.com



discusz
Posts: 62
Member Since:
2007-02-22
Since a few of you have

Since a few of you have downloaded this script, I have a few questions.

1) Was the setup easy for you?
2) is the script working (easiest way to test is change the password on your SIP/IAX trunk and viola a dead trunk)

Please post some feedback.. I did not get a chance this weekend to look at AGI as I was not home much., I do not think this will work out of the box..

Jim



joevoirol
Posts: 6
Member Since:
2007-05-10
Setup and Execution

I have downloaded this and am testing it on my spare system. I have a couple of questions about the format for the iaxtrunks and siptrunks file. What information needs to go into the file? Should it just be the IP address of the provider or does it need more information? I only have iax2 trunks, no sip trunks. The iaxtrunks file just contains the IP address of 63.211.239.28. It does not work correctly here is the info I get:

============================================================
SIP Trunk information
============================================================

============================================================
IAX2 Trunk information
============================================================
iaxtrunks = Binary file (standard input) matches
An email has been sent!

houston we have a problem
63.211.239.28 trunk is not registering

If you have a chance let me know what I am doing wrong here.

Thanks



gbrook
Posts: 216
Member Since:
2006-06-06
Hi Joe

I had to use the port number as well in order for it to work.

e.g.
63.211.239.28:4569

I also had to modify the trunkalerts.pl file depending on the TrixBox version as the position of "Registered" in the response to iax2 show registry changed between two of the versions

Line 56 (in my file) is
$iaxtrunks = `/usr/sbin/asterisk -rx "iax2 show registry" |/bin/grep \"$_\" | awk '{print $5}'`;

{print $5} is the position of Registered (or not) in the iax2 show registry command response string.

Regards
Garry



percykwong
Posts: 758
Member Since:
2007-04-30
Use Argus.. That's what I

Use Argus.. That's what I use.. It monitors my trunks, my pbx, my servers, my internet connections.. if it's down, I get notified via SMS on my cell phone.. When it comes back up, I get notified again.

--

-----------------------------------------------
Percy Kwong
Trixbox Tech Support - 202.600.3884

Swimminginthought.com



joevoirol
Posts: 6
Member Since:
2007-05-10
Hi Garry

I have created the iaxtrunks file so it is ip:port e.g. 63.211.239.28:4569 I have 3 IAX accounts and they are entered each on a seperate line, and I am still having problems.

$iaxtrunks is "Binary file (standard input) matches", I can never get it to be Registered or Request. If I put a / in front of $5 {print /$5} I get "matches". Field 5 is the correct field for the awk command, I can run awk from the command line and I get the correct response for field 1 and field 5.
# asterisk -rx "iax2 show registry" | awk 'NR==3, NR==5 {print $1,$5}'
63.211.239.28:4569 Registered
192.246.69.186:4569 Request
64.2.142.30:4569 Registered

Does it matter where I put the perl file? It is in /etc/asterisk/perl_scripts and I have changed the permissions to 755 so it is executable.



gbrook
Posts: 216
Member Since:
2006-06-06
I put

trunkalerts.pl in /usr/sbin and it is 755. The iaxtrunks file is in /etc/asterisk and its owner is asterisk.

I then run it with cron every 10 minutes and it works a charm.

Worst case, I can email you my trunkalerts.pl

Cheers
Garry



onecomms
Posts: 289
Member Since:
2006-10-26
sounds like a great idea to

sounds like a great idea to me..... feature request, perhaps??

--

_________________________________
Andy Thompson
1comms
http://www.1comms.co.uk
sales@1comms.co.uk



joevoirol
Posts: 6
Member Since:
2007-05-10
Please

email the trunkalerts.pl file to me at jvoirol at mcs-wireless.com

Thanks



Chance
Posts: 8
Member Since:
2009-05-14
Daemonize this

I am working on an interrupt driven Perl daemon for this exact thing building off of the code posted above. I realize that this is an old thread, but I have found nothing to accomplish this.

If I am wasting my time please feel free to let me know. If the scripting goes well it should be done fairly soon as it is not that complicated.

EDIT:
Code complete, Its not pretty, but it appears to work :) email me at chance (dot) fulton (at) gmail (dot) com if you are interested.
Thanks,

EDIT:

I found some errors in my code, mainly id doesn't work... I had to move the order of some things around,

I opened the trunk files at the start of the main loop, and then never closed them. I forgot my C++ in the fact that you may have to rewind a file in order to read from it again, So basically the file was at EOF after the first iteration, and would never process the trunks again.

I fixed this by placing an open, and a close inside each of the monitor subroutines, it now appears to work just fine, Sorry to have to post this here, as I just "cleaned" out my mailbox, losing the list of members who emailed me for a copy of the script.

Im going to make it easy n you all, and allow http access to the file soon, but for now:

#!/usr/bin/perl -w 
###############################################Forward ######################################
#### This script was written to monitor asterisk SIP/IAX2 trunks. It does the job well
#### Please feel free to do whatever you please to this as it was written with code
#### from many other contributors.
#### I take no responsability for anything that this script does badly. 
#### I am not a perl wizard!
###############################################Configuration ################################
#### You have to create two text files inside of /etc/asterisk called trunkalerts_sip.conf, 
#### and trunkalerts_iax.conf inside put the host that you get back from the command
#### asterisk -rx "sip show registry" and asterisk -rx "iax show registry"
#### I may add a cli flag that creates these with all trunks inside on first run.
#### You also have to parse the script and change any specific instances of email addresses,
#### and intervals etc. They are pretty much all commented.
##############################################Contact#######################################
#### chance dot fulton at gmail dot com if you have any questions.
##############################################The End########################################

use strict;
use warnings;

use constant LOG_DIR    => '/var/log/MonitorTrunks';
use constant LOG_FILE   => 'MonitorTrunks.log';
#use constant PIDDIR     => LOG_DIR;

use Proc::PID::File;
use Proc::Daemon;
use Log::Dispatch;
use Log::Dispatch::File;
use Date::Format;
use File::Spec;

print "Prototypes\n";
sub dienice ($);
sub MonitorSip();
sub MonitorIAX2();
sub mailalert();
#
# fork and background process
#
print "Forking Process\n";
our $ME = $0; 
$ME =~ s|.*/||;
#our $PIDFILE = PIDDIR."/$ME.pid";
print "PID File /var/run/$ME.pid\n"; #$PIDFILE\n";

print "Starting Daemon\n";
startDaemon();

#
# Setup the script variables for email
# Please modify these, as I do not want your email.
#
our $EmailContact = "To:<Sum1semail\@somedomain.com>\n";
our $from= "FROM: <Sum1semail\@somedomain.com>\n";
our $reply_to = "Reply-to: <Sum1semail\@somedomain.com\n";
# Interval to look at the trunks.
our $monitorInterval = 20;
# Interval that we will send a "heartbeat" to the log.
our $logMarkInterval = 1800;

#
# Setup a logging agent
#
our $HOSTNAME = `hostname`;
chomp $HOSTNAME;
our $log = new Log::Dispatch(
      callbacks => sub { my %h=@_; return Date::Format::time2str('%B %e %T', time)." ".$HOSTNAME." $0\[$$]: ".$h{message}."\n"; }
);
$log->add( Log::Dispatch::File->new( name      => 'file1',
                                     min_level => 'warning',
                                     mode      => 'append',
                                     filename  => File::Spec->catfile(+LOG_DIR, LOG_FILE),
                                   )
);
$log->warning("Starting Processing:  ".time());


#
# Setup signal handlers so that we have time to cleanup before shutting down
#
my $keep_going = 1;
$SIG{HUP}  = sub { $log->warning("Caught SIGHUP:  exiting gracefully"); $keep_going = 0; };
$SIG{INT}  = sub { $log->warning("Caught SIGINT:  exiting gracefully"); $keep_going = 0; };
$SIG{QUIT} = sub { $log->warning("Caught SIGQUIT:  exiting gracefully"); $keep_going = 0; };
$SIG{TERM} = sub { $log->warning("Caught SIGTERM:  exiting gracefully"); $keep_going = 0; };

#
# enter main loop
# In this loop we will look at the trunks inside of SIPTRUNKS, and then IAXTRUNKS to determine their state.
# We will then sleep for a predefined interval, and do it all over again.
# When our Interval Counter reaches another predefined limit (multiple of our monitorInterval) we will then send
# <Mark> to the log so everybody knows we arent dead.
#
#debugging lines No longer needed
print "Opening trunk Files\n";
my $logMarkIntervalCounter = 0;
while ($keep_going) {
	print "SipStuff";	
	MonitorSip();
	print "iax2Stuff";
	MonitorIAX2();
	print "$monitorInterval\n";
	sleep $monitorInterval;
	$logMarkIntervalCounter += $monitorInterval;
	if($logMarkIntervalCounter == $logMarkInterval)
	{
		print "Log MARK";
		$log->warning("<Mark>");
		$logMarkIntervalCounter = 0;
	}
}

#
# Mark a clean exit in the log
#
$log->warning("Stopping Processing:  ".time());
#Set the date so that it can be used later.
#handled by the logger
#my $date = `date`;

################################################## ##################################################
#### Initial attempt to daemonize this script as to free up some resources.
#### 20090602
#### Wish me luck...
#### Attempt succeded, I have fixed a bug wher the files were not rewound after the initial run of the
#### script. 
#### Changed from using Proc::PID_File which wa old to PROC::PID::File works a bit differently in that
#### it only puts the lock PID file in /var/run
################################################## #################################################
####
#### Trunk Alerts script written by Jim Hribnak Oct 7th 2007
#### if there is any questions please feel free to drop me an email at jimh at domain nucleus.com
####
################################################## ##################################################
####
#### Script modified by Charles Pippin Feb 21st 2009 - Added counters for loop retry.
#### if there is any questions please feel free to drop me an email at cwpippin at domain gmail.com
####
################################################## ##################################################
####
#### Create the following 2 files in /etc/asterisk
####
#### in the files below add the hosts entry from asterisk -rx "sip show registry" and
#### from asterisk -rx "iax2 show registry".
####
#Startup Code

#
# startDaemon
#
# Fork and detach from the parent process
#
sub startDaemon {

  #
  # Fork and detach from the parent process
  #
  
  #eval { close __DATA__ }; # having __END__ will trigger __DATA__ to open and should be closed
  eval { Proc::Daemon::Init; };
  #
  # Get a PID file
  #
  eval {Proc::Daemon::Init(); };
  #
  # Get a PID file
  #
  dienice("Already running!") if Proc::PID::File->running();
}

#
# dienice
#
# write die messages to the log before die'ing

#I need to figure out a way to stop using $_ as I hate it!
sub dienice ($) {
  my ($package, $filename, $line) = caller;
  $log->critical("$_[0] at line $line in $filename");
  #Close the log handle;
  close(log) if ($log);
  die $_[0];
}


sub MonitorSip(){
################################################## ##################################################
####
#### SIP Related Code
####
	#print "Opening SIP trunk file\n";
	#Moved to open/close everytime this sup is called so the file is rewound, and not stuck at EOF.
	# 07/16/2009
	open(SIPTRUNKS,"</etc/asterisk/trunkalerts_sip.conf");
	while (<SIPTRUNKS>) {
		chomp;
		#Test trunk 5 times to make sure its Up or DOWN before moving on. 
		my $upcounter = 5;
		my $dncounter = 5;
		until ($upcounter == 0) {
			#I need to figure out a way to stop using $_ as I hate it!
			my $siptrunks = `/usr/sbin/asterisk -rx "sip show registry" | grep \"$_\" | awk '{print \$4}'`;
			#print $siptrunks;
			if ($siptrunks =~ "Registered") {
				$upcounter = $upcounter - 1;
			}
			else {
				$dncounter = $dncounter - 1;
				$log->warning("$_ is down\n") ;
				#When dncounter reaches 0 fire an email that tells someone about the error
				if ($dncounter == 0) {
					mailalert();
					#I need to figure out a way to stop using $_ as I hate it!
					$log->warning("houston we have a problem, $_ trunk is not registering");
					`/usr/sbin/asterisk -rx "module reload chan_sip"`;
					$log->warning("sip reload processed");
					$logMarkIntervalCounter = 0;
					$upcounter = 0;
				}
			}
		}
	}
	close SIPTRUNKS;
#end of while loop (read SIP file)
}
sub MonitorIAX2(){
################################################## ##################################################
####
#### IAX Related Code
####
	#print "Opening IAX trunk file\n";
	#Moved to open/close everytime this sup is called so the file is rewound, and not stuck at EOF.
	# 07/16/2009	
	open(IAXTRUNKS,"</etc/asterisk/trunkalerts_iax.conf");
	while (<IAXTRUNKS>) {
		chomp;
		#Test trunk 5 times to make sure its Up or DOWN before moving on.
		my $upcounter = 5;
		my $dncounter = 5;
		until ($upcounter == 0) {
			#I need to figure out a way to stop using $_ as I hate it!
			my $iaxtrunks = `/usr/sbin/asterisk -rx "iax2 show registry" |/bin/grep \"$_\" | awk '{print \$6}'`;
 			#print $iaxtrunks;
			if ($iaxtrunks =~ "Registered") {
				$upcounter = $upcounter - 1;
			}
			else {
				$dncounter = $dncounter - 1;
				$log->warning("$_ is down\n");
				#When dncounter reaches 0 fire an email that tells someone about the error
				if ($dncounter == 0) {
					mailalert();
					#I need to figure out a way to stop using $_ as I hate it!
					$log->warning("houston we have a problem, $_ trunk is not registering");
					`/usr/sbin/asterisk -rx "module reload chan_iax2"`;
					$log->warning("IAX2 reload processed");
					$logMarkIntervalCounter = 0;
					$upcounter = 0;
				}
			}
		}
	} 
	close IAXTRUNKS;
	#end of while loop (read IAX file)
}
################################################## ##################################################
####
#### Email Subroutines
#### Change anywhere below where there is an email address an email addres
#### must have \@ as perl needs to escape the @ symbol
####
################################################## ##################################################
#I need to figure out a way to stop using $_ as I hate it!
sub mailalert() {
    my $sendmail = "/usr/sbin/sendmail -t";
    my $subject = "Subject: $_ is DOWN!!!!\n";
    my $content = "PBX TRUNK $_ is DOWN!!!!\n A reload of the trunk has been processed";
    open(SENDMAIL, "|$sendmail") or dienice("Cannot Open sendmail Email failed!");
    print SENDMAIL $from;
    print SENDMAIL $reply_to;
    print SENDMAIL $subject;
    print SENDMAIL $EmailContact;
    print SENDMAIL $content;
    close(SENDMAIL);
    $log->warning("An email has been sent to $EmailContact!");
}


Chance



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.