#!/usr/local/bin/perl
#
# Abs:   This script is run every five minutes as a laci cronjob on
#        lcls-daemon2 to monitor the modification time of the last
#        cmlogServer database file being written.  If this modification
#        time is not near the current time, this script will notify
#        a list of people via email when appropriate.
#
# Name:  cmlog_database_file_monitor.pl
#
# Rem:   The cmlogServer process run under the laci account on
#        lcls-daemon2 occasionally appears to be "hung".  That is,
#        cmlog viewers cannot connect to it and it is not updating
#        the latest cmlogServer database file.  This script was
#        written to detect this condition and alert a list of
#        people via email when appropriate.
#
#        A check is made whether the modification time of the last
#        cmlogServer database file being written is near the current
#        time.  If this modification time is not near the current
#        time, this script will notify a list of people via email
#        if one of the following conditions is true:
#            1. The monitor file /tmp/cmlog_database_file_monitor.txt
#               does not exist, or
#            2. A 24 hour period has elapsed between the current time
#               and the last time this monitor file was modified.
#
#        This monitor file is removed by the cmlogServer type 2
#        startup file (/usr/local/lcls/package/cmlog/conf/st.cmlog)
#        just before the process is started.  This ensures that
#        this script will send email the first time the modification
#        time of the last cmlogServer database file is not near the
#        current time for the running of this process.
#
#        This monitor file is modified (using the "touch" command)
#        immediately after this script sends email.  This will
#        prevent this script from sending more email for the next
#        24 hours unless the checked condition occurs and the
#        cmlogServer process is restarted (which will remove the
#        monitor file).
#
# Auth:  21-Apr-2009, Bob Hall (rdh)
# Rev:   dd-mmm-yyyy, Reviewer's Name    (USERNAME)
#--------------------------------------------------------------
#
# Mods:
#        28-Aug-2009, Bob Hall (rdh)
#           Prefixed the "Subject" line with "FAILURE: " to
#           make it more obvious that action should be taken.
#
#
#==============================================================

#
# Initialze:
#    1.  The email receipients (the "to" list) of the email
#        messages. 
#    2.  The maximum number of allowed seconds between the
#        current time and the modification time of the last
#        cmlogServer database file being written before the
#        checked "hung" condition will be detected.
#    3.  The maximum number of allowed seconds between the
#        current time and the modification time of the monitor
#        file before email will be sent.  86400 seconds is
#        24 hours.
#    4.  The filepath of the monitor file (also known as the
#        "last_send_file".
#
$to_email_list = "rdh\@slac.stanford.edu,brobeck\@slac.stanford.edu,jingchen\@slac.stanford.edu";
$max_secs_since_modified = 60;
$max_secs_since_last_email_send = 86400;
$last_send_file = "/tmp/cmlog_database_file_monitor.txt";

#
#  Obtain the name of each cmlogServer database file by
#  reverse chronological order.  The newest cmlogServer
#  database file will be obtained first and processing
#  will cease after obtaining this file name.
#
$ls_cmd = "ls -t /u1/lcls/cmlog/prod/cmlog_*";
open(LS, "$ls_cmd |") or die "Cannot run $ls_cmd\n";
while (<LS>)
{
    chomp;

    $cur_file = $_;

    #print("cur_file = $cur_file\n");

#
#   Get information about the newest cmlogServer database file using the
#   "stat" command.  The needed information item is the last modification
#   time, returned in UNIX system time format (the number of seconds since
#   Jan. 1, 1970).
#
    ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $therest) = stat($cur_file)
        or die "Cannot stat file $cur_file";

    #print("mtime = $mtime\n");

#
#   Get the current time using the "time" command in UNIX system time format.
#
    $cur_time = time();

    #print("cur_time = $cur_time\n");

    $elapsed_time = $cur_time - $mtime;

#
#   If the elapsed time between the current time and the modification time of
#   the newest cmlogServer database file is greater than a threshold, the
#   "hung" condition has been detected.
#
    if ($elapsed_time > $max_secs_since_modified)
    {
#
#       The "hung" condition has been detected.  Determine whether email
#       needs to be sent.  Email will be sent if the "monitor" (aka,
#       "last_send_file") file does not exist or the number of seconds
#       between the current time and this monitor file exceeds a threshold
#       (e.g., 24 hours).  See the "Rem" comments in the script header
#       above for further explanation.
#
        $need_to_send = 0;
        if (-e $last_send_file)
        {
            ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $last_send_mtime, $therest) = stat($last_send_file)
                or die "Cannot stat file $last_send_file";

            $last_send_elapsed_time = $cur_time - $last_send_mtime;
            if ($last_send_elapsed_time > $max_secs_since_last_email_send)
            {
               $need_to_send = 1;
            }
        }
        else
        {
            $need_to_send = 1;
        }

        if ($need_to_send)
        {
#
#           Email needs to be sent.  Invoke the send_email subroutine to do this
#           with a title that indicates the detected condition.  Then use the
#           "touch" command to set the modification time of the monitor file
#           in order to indicate the last time email was sent for the current
#           running cmlogServer process.
#
            $title = "FAILURE: Latest cmlog_* file in /u1/lcls/cmlog/prod on lcls-daemon2 not updating";
            &send_email($title);

            system("touch $last_send_file");
        }
    }

    last;
}

#
#  This routine sends email to the email addresses indicated in the
#  "to_email_list" variable with the title ("subject") parameter
#  indicating the detected condition.  The body of the email indicates
#  the recommended action that should be taken as a result of the
#  dectected condition (i.e., restart the cmlog system).
#
sub send_email
{
    local($subject) = @_;

    #print("sending email\n");

    open(MAIL, "|/usr/lib/sendmail -t") or
        die "Can't fork for sendmail\n";

    print MAIL "To: $to_email_list\n";

    print MAIL "From: rdh\@slac.stanford.edu\n";
    print MAIL "Subject: $subject\n";

    print MAIL "After obtaining permission, restart the cmlog system on lcls-daemon2 using the Unix Watchdog.\n";
    print MAIL "Permission from MCC must be obtained because restarting the cmlog system will also include\n";
    print MAIL "restarting the Alarm Handler process and Channel Watcher processes.\n";

    close (MAIL) or
        warn "sendmail didn't close properly";
}
